Download as pdf or txt
Download as pdf or txt
You are on page 1of 259

Fundamentals of Object oriented Programming

Object Oriented Program:

The major objective of object oriented approach is to eliminate some flaws encountered in the procedure oriented
approach. OOP treats data as a critical element in the program development and does not allow to flow freely around
system. It ties data more closely to the functions that operate on it and protects it from external functions. By
unintentional modifications by OOP allows us to decompose a problem into a number of entities called “objects” and
then build data and functions or methods.

Some Features of OOP:

Emphasis on data rather than procedure.

Programs are divided into what are known as “objects”.

Data structures are designed such that they characterize the objects.

Methods that operate on the data of an object are tied together in the data structures.

Data is hidden and cannot be accessed by external functions.

Objects may communicate with each other through methods.

New data and methods can be added whenever necessary.

Follows bottom to top approach in program design.

Basic concepts of Object Oriented Programming?

The general concepts of OOP which form the heart of Java language are.

Classes and Objects.

Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors –
wagging the tail, barking, eating. An object is an instance of aclass.

Class − A class can be defined as a template/blueprint that describes the behaviour/state that the object of its type
support.

Objects in Java:

Let us now look deep into what are objects. If we consider the real-world, we can find many objects around us, cars,
dogs, humans, etc. All these objects have a state and a behaviour.

If we consider a dog, then its state is - name, breed, color, and the behaviour is - barking, waggingthe tail, running.

If you compare the software object with a real-world object, they have very similar characteristics.

Software objects also have a state and behaviour. A software object's state is stored in fields and behaviour is shown via
methods.
Data Abstraction and Encapsulation:

The wrapping up of data and methods into a single unit (called class) is known as encapsulation. Data encapsulation is
the most striking feature of a class. The data is not accessible to the outside world and only these methods, which are
wrapped in the class, can access it. These methods provide the interface between the object’s data and the program.
This insulation of the data from direct access by the program is called data hiding. Encapsulation makes it possible for
objects to be treated like ‘black boxes’.

Abstraction refers to the act of representing essential features without including the background details or
explanation.

Inheritance:

Inheritance is the process by which objects of one class acquire the properties of objects of another class. Inheritance
supports the concept of hierarchical classification.

In OOP, the concept of inheritance provides the idea of reusability. This means that we can add additional features to
an existing class without modifying it. This is possible by deriving a new class from the existing one. The new class will
have the combined features of both the classes.

Polymorphism

Polymorphism is another important OOP concept. Polymorphism means the ability to take more than one form. For
example, an operation may exhibit different behavior in different instances. The behavior depends upon the types of
data used in the operation.

Dynamic Binding:

Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding
means that the code associated with a given procedure call is not known until the time of the call at runtime.

Message Communication:

An object-oriented program consists of a set of objects that communicate with each other. The process of
programming in an object-oriented language, therefore, involves the following basic steps:

Creating classes that define objects and their behavior.


Creating objects from class definitions.
Establishing communication among objects.

Objects communicate with one another by sending and receiving information much the same way as people pass
messages to one another.

Benefits and disadvantages of OOP and what are the applicationsof OOP:

Through inheritance, we can eliminate redundant code and extend the use of existing class.

We can build a program from standing working modules that can communicate with one another rather than having to
start writing the code from scratch. This leads to saving of development time and highs productivity.

The principles of data hiding helps programmer to build a secure program. This code is not overrun other parts of
programs.

It is possible to have multiple objects to co exists without an interference.


It is easy to partition the work in a project based on objects.

The data-centered design approach to capture more details of model in an implementation form.

Object oriented systems can be easily upgraded from small to large systems.

Message passing techniques for communication between objects make the interface descriptions, with external
systems much simpler.

Software complexity can be easily managed.

Applications of OOP

The most popular application Of OOP has been in the area of user interface design such as windows. OOP is useful in
this type of applications because it can simplify complex problem. The promising areas for application of OOP include:

Real time Systems.


Simulation and modelling.
Object oriented databases.
Hypertext, hypermedia and expert text.
Artificial Intelligence (AI) and expert systems.
Neural networks and parallel programming.
Decision support and office automation systems.
CIM / CAD / CAM systems.

Some disadvantages:

Steep learning curve: The thought process involved in oop’s may not be natural for some people and it can take to get
used to it. It is a programming techniques such as inheritance and polymorphism can be challenging to a comprehend
initially

Lager program size

Slower programs :

Not suitable for all types of problems

JAVA EVALUTION:

Java is purely Object Oriented Language developed by James Gosling and his team of Sun Microsystems of U.S.A. in
1991. Java was designed for the development of software for consumer electronic devices like TVs and VCRs, toasters
etc. The initial name of the language is oak and later it was renamed as Java.
Java is the first programming language that supports a complete Platform Independency that is not tied to any
particular hardware or operating system. Programs developed in Java can be executed on any system.

We can develop two types of applications one is Standalone Application and another one is Web Applets. Standalone
applications can execute by their own whereas the Applets are small java programs developed for Internet applications
and needs a separate environment to execute.

Year Development

Sun Micro Systems decided to develop software that could used to


manipulate consumer electronic devices. A team of James Gosling known
1990
as Green Project team came into work.

1991 The team announced a new language oak.

The team demonstrated the application using a hand-held device with a


tiny touch-sensitive screen.
1992

1993 The team came up for developing web applets (small programs) that
could run on all types of computers connected to the Internet.

1994 The team developed a web browser called Hot Java to locate and run
applet programs on Internet.

1995 Oak was renamed as Java. Many companies like Microsoft and Netscape
announced their support to Java.

1996 Sun Microsystems released JDK 1.1 (Java Development Kit) for general
purpose object-oriented programming.

1997 JDK 1.1

1998 Java 2 with version SDK 1.2 was released.

1999 Standard Edition (J2SE) and Enterprise Edition (J2EE) are released.

2000 J2SE with SDK 1.3 was released.

2002 J2SE with SDK 1.4 released.

2004 J2SE with JDK 5.0 (JDK 1.5) was released.

Sun Microsystems has divided into 3 parts:

Java SE: It is the java standard edition that contains basic core java classes. This is edition is used to develop
standard applets and applications

Java EE: It is the java enterprise edition and it contains classes that are beyond java SE. In fact java SE in order to
used many of the classes in java EE.java EE mainly concentrates on providing business solutions on a network
Java ME: It standards for java Microedition.java ME is for developers who develop code for portable devices. such as
a PDA or a cellular phone code on these devices needs to be small in size and should take less memory

Requirements for Hardware and Software:

Java is currently supported on Windows, Sun Solaris, Macintosh, and UNIX systems. The minimum hardware and
software requirements for windows version of Java are as follows.

IBM 486 System


Minimum 8GB Memory
Windows Operating System
Hard drive
Custom Drive
Mouse

Differences between C, C++ and Java:

Metrics C C++ Java

ProgrammingParadigm Procedural language Object-Oriented Pure Object Oriented


Programming (OOP) Oriented

Origin Based on assembly Based on C language Based on C and C++


language

Developer Dennis Ritchie in1972 Bjarne Stroustrup in1979 James Gosling in 1991

Interpreted language
(Compiler + interpreter)
Translator Compiler only Compiler only

Platform Dependency Platform Dependent Platform Dependent Platform Independent

Executed by JVM (Java


Virtual Machine)
Code execution Direct Direct

Approach Top-down approach Bottom-up approach Bottom-up approach

File generation .exe files .exe files .class files

Pre-processordirectives Support header files Supported (#header, Use Packages (import)


(#include, #define) #define)

keywords Support 32 keywords Supports 63 keywords 50 defined ke9y|wPoradgs e

Datatypes (union,structure) Supported Supported Not supported

Inheritance No inheritance Supported Supported except


Multiple inheritance

Support Function Operator overloading is


overloading not supported
Overloading No overloading
(Polymorphism)

Pointers Supported Supported Not supported


Allocation Use malloc, calloc Use new, delete Garbage collector

Exception Handling Not supported Supported Supported

Templates Not supported Supported Not supported

Destructors No constructor neither Supported Not supported


destructor

Multithreading/ Interfaces Not supported Not supported Supported

Database connectivity Not supported Not supported Supported

Storage Classes Supported ( Supported ( Not supported

auto, extern ) auto, extern)

FEATURES OF JAVA

Sun Micro systems officially describes java with the following attributes.

Compiled and interpreted :Usually a computer language is either compiled or interpreted. Java combines both these
approaches thus making java a two stage system. First, java compiler translates source code into known as bytecode.
instructions. Bytecodes are not machine instructions and therefore, in the second stage, java interpreter generates
machine code that can be directly executed by the machine that is running the java program.

Platform-independent and portable: Java programs can be easily moved from one computer system to another,
anywhere and anytime. Changes and upgrades in operating systems, processors and system resources will not force
any changes in java programs. Java ensures portability in two ways. First, java compiler generates bytecode
instructions that can be implemented on any machine. Secondly, the size of the primitive datatypes are machine
independent.

Object-oriented : Java is true object oriented language. All program code and data reside with in objects and classes.
Java comes with an extensive set of classes, arranged in packages, that we can use in our programs by inheritence.

Robust and secure : Java is robust language. It provides much secure & reliable code. It has strict compile time and
runtime checking for data types. It has a garbage collector to rectify memory management problems. It also has the
concept of exception handling.

Distributed: Java applications can open and access remote objects on internet. Multiple programs can communicate
from client system to the server system.

Familiar, simple and small : Java is a small and simple language. Because, java does no use pointers, preprocessor
header files, goto statement and many others. It also eliminated operator overloading and multiple inheritence.

Familiarity is another striking feature of Java, to make the language look familiar to the existing programmers, it was
modeled on C and C++ languages.

Multithreaded and interactive: Multithreaded means handling multiple tasks simultaneously. Java supports
multithreaded programming. This means that we need not wait for the application to finish one task before beginning
another. This feature greatly improves the interactive performance of graphics applications.

High performance: Java performance is impressive for an interpreted language, mainly due to the use of intermediate
byte code. According to sun, java speed is comparable to the native C/C++.
Dynamic and extensible: Java is dynamic language. Java is capable of dynamically linking in new class libraries,
methods and objects Java programs supports functions written in other languages such as C and C++. These functions
are known as native methods. Native methods are linked dynamically at run time.

Scalability and performance: J2SĘ5.0 assures a significant increase in scalability and performance by improving the
startup time and reducing the amount of memory used in java2 runtime environment.

Java Naming Conventions:

Java naming convention is a rule to follow as you decide what to name your identifiers such as class, package, variable,
constant, method, etc.

But, it is not forced to follow. So, it is known as convention not rule. These conventions are suggested by several Java
communities such as Sun Microsystems and Netscape.

All the classes, interfaces, packages, methods and fields of Java programming language are given according to the Java
naming convention. If you fail to follow these conventions, it may generate confusion or erroneous code.

Advantage of Naming Conventions in Java:

By using standard Java naming conventions, you make your code easier to read for yourself and other programmers.
Readability of Java program is very important. It indicates that less time is spent to figure out what the code does.

The following table shows the popular conventions used for the different identifiers.

IdentifiersType Naming Rules Examples

Class It should start with the uppercase letter.It public class Employee
should be a noun such as Color, Button,
System, Thread, etc. {

Use appropriate words, instead of //code snippet


acronyms.
}

Interface It should start with the uppercase letter. It interface Printable


should be an adjective such as Runnable,
Remote, ActionListener. {

Use appropriate words, instead of //code snippet


acronyms.
}

Method It should start with lowercase letter.It Employee


should be a verb such as main(), print(),
println(). {

If the name contains multiple words, start // method void draw(){


it with a lowercase letter followedby an
//code snippet
uppercase letter such as
actionPerformed(). }

Variable It should start with a lowercase letter such class Employee


as id, name.
{

Identifiers Type Naming Rules Examples

Class It should start with the uppercase letter. public class Employee
It should be a noun such as Color, Button,
System, Thread, etc. {

Use appropriate words, instead of //code snippet


acronyms.
}

Interface It should start with the uppercase letter. interface Printable


It should be an adjective such as
Runnable, Remote, ActionListener. {

Use appropriate words, instead of //code snippet


acronyms.
}

Method It should start with lowercase letter. It Employee


should be a verb such as main(), print(),
println(). {

If the name contains multiple words, start // method void draw(){


it with a lowercase letter followed by an
//code snippet
uppercase letter such as
actionPerformed(). }

Variable It should start with a lowercase letter class Employee


such as id, name.
{

JDk:

Java environment includes a large number of development tools and hundreds ofclasses and methods called Java
Development Kit (JDK).

JDK comes with a collection of tools that are used for developing and running a Javaprograms. They include:

Javac – Java Compiler

Java – Java Interpreter

Platform Independent:
The concept of platform independency makes java as architecture neutral language.To provide better portability, Sun
Microsystems concentrated on a new language and the result was Java. It can produce code that would run on a
variety of CPUs under different environments. Once java code is produced it can be run anywhere on any environment.
Moreover, as the java code runs on any platform, it can be adapted to internet too because internet programming
does require the same kind of approach. Platform independency is achieved by java through its JVM (Java Virtual
Machine).

JVM(Java Virtual Machine):

The Java achieves architecture neutrality because Java compiler produces an intermediary code known as byte code
for a machine that does not exist. This machine is called the Java Virtual Machine. Following fig illustrates the process
of compiling of java program

Overview of Java Language

Documentation Section

Package Statement

Import Statements

Interface Statements

Class Declarations

Main method class

Main method declaration

EXAMPLE
/* Program for Square root */import java.lang.Math;

class Mass

public static void main(String args[ ])

double x = 5; //Declaration and initializationdouble y; //Simple declaration

y = Math.sqrt(x);

System.out.println(“y = ”+ y);

Documentation section:

The documentation section comprises a set of comment lines giving the name of the program, and other details. Java
uses a special type of comment /**…..*/ known asdocumentation comment.

Ex: /** This is the first program */

Package statement:

The first statement allowed in Java file is package statement. This statement declares package name and informs the
compiler that the classes defined here belong to this package.Java provides built-in packages.

Syntax:

package <package name>;Java.util (random, number, date, vector) Java.io (input, output support classes)

Java.awt (include classes for windows, menus, buttons)

Java.net (for networking)

Java.lang (for primitive types strings, math functions, threads, exceptions)

Java.applet (classes for creating and implementing applets).

import statement:

This statement is similar to #include statement in c. This statement instructs the interpreter to load the class contained
in the package name using import statement, we can have access to classes that are part of packages.

Syntax: import <package name>.<class name>;

interface statement:
An interface is like a class but includes a group of method declarations. It is used only to implement the multiple
inheritance.

public class sample

public static void main(String args[])

System.out.println(“Java is better than C++”);

Class declaration:

The first line declares a class. Class is a keyword and declares a new class; sample is kava identifier that specifies
name of the class.

The second line is open brace; every class definition in java begins with an open brace and ends with a matching
close brace.

Main line:

The third line defines a method named main, which is similar to main () function in C. every java application program
must include the main () method. This is the starting point for the interpreter to begin execution of program. A
program may have any number of classes but only one class must include main function.

This line contains no. of keywords, public, static and void.

The keyword public specifies that the main method is accessible to all other classes.

The main method must be declared as static since the interpreter uses these methods before any objects are created.

The type modifier void states that the main method does not return any value.

Output line:

System.out.println (“welcome”). It is similar to printf () statement in C. The println is member of out object which is a
static data member of system class. The method println always apply a new line character to the end of the string.

Every java statement must be ended with semicolon.

Java Tokens:

Smallest individual units in a program are known as tokens. Java language includes 5 types of tokens. They are reserved
words or key words, Identifiers, Literals, Operators, and Separators.

Note: Every java statement forms with set of tokens, forms with the java character set. The characters are defined by
the Unicode character set. The Unicode is a 16-bit character coding system currently supports more than 34000,
defined characters derived characters from 24 languages.

Key words:

A keyword is pre reserve word it’s meaning already know the compiler.
abstract boolean break byte

case cast* catch char

const* continue default do

else extends false** final

float for future* generic*

if implements import inner*

int interface long native

null** operator* outer* package

protected public rest* return

static super switch synchronized

threadsafe* throw throws transient

try var* void volatile

Identifiers

The purpose of identifier is for naming classes, methods, variables, objects, labels, packages and interfaces in a
program.

Rules:

• They must not begin with a digit.


• Uppercase and lowercase letters are different.
• They can be of any length.
• They can have alphabets, digits and the underscore and dollar sign characters. Various
naming conventions have to follow when declaring identifiers.
• Names of all public methods and instance variables start with a lowercase letter.
• When more than one word is used in a name, the second and subsequent words are
marked with uppercase letters.
• All private and local variables use only lowercase letters combined with underscore.
• All classes and interfaces start with uppercase letter.
• Variables that represent constant values use uppercase letters.
Literals or constants in java:

Literals in Java are sequence of characters that represent constant values to be stores in variables. Java specifies 5
major types of literals.

• Integer literal.
• Floating point literal.
• Character literal.
• String literal.
• Boolean literal.

Ex: final int x=10; final float pi=3.14f;

Separators:

Separators are symbols used to indicate where groups of code are divided and arranged.

Name Use

Parenthesis ( ) It is used in method and expression and surrounding


cast types.

Braces { } It is used to automatically initialize values of an array,


define block of code for classes and methods.

Square brackets [ ] It is used to declare array type and values.

Semicolon ; Used to separate statements

Comma , Used to separate consecutive identifiers in variable


declaration.

Period . Used to separate package name from sub packages.

Constants:

Constants in java refer to fixed values that do not change during the program execution of a program. Java supports
several types of constants.

• Numerical constants.
• Integer constants.
• Real constants.
• Character constants.
• Single character constants

String constants

Integer constants refer to a sequence of digits. There are three types of integer’s namely decimal, octal and
hexadecimal integers.

Ex: 123, -321, O37 (octal), Ox2, Ox9f (hexadecimal).


Real constants

it used to represent the numbers containing fractional parts. A real number may also be expressed in exponential
notation also.

Ex: 215.65, 0.65e4, 12e-2

Single Character constants

I t contain a single character enclosed within a pair of singlequotation marks.

Ex: ‘a’. ‘5’, ‘\n’

Backslash character constants

Java supports some special backslash character constants that are used in output methods. These characters
combinations are known as escape sequences.

Constant Meaning

\b backspace

\f form feed

\n new line

\r carriage return

\t horizontal tab

\’ single quote

\” double quote

\\ backslash

String constant

I t is a sequence of characters enclosed between double quotes. The characters may be alphabets, digits,
special characters, and blank spaces.

Ex: “sai”, “2010”, “5+3”

Symbolic Constants

The constants may appear repeatedly in a number of places in the program. A constant is declared as follows.

Ex: final float pi=3.14f;

Data types

Every variable in Java has a data type. Data types specify the size and type of values that can be stored. Java language
is rich in its data types. The variety of data types available allows the programmer to select the type appropriate to the
needs of the application. Data types in Java under various categories are shown below
Integer Types:-
Integer types can
hold whole numbers
such as 123, 96, and
5639. The size of the
values that can be
stored depends on
the integer data type
we choose. Java
supports four types
of integers as shown
below. They are byte, short, int, and long. Java does not support the concept of unsigned types and therefore all Java
values are signed meaning they can be positive or negative.
Variables:

The variables are the names of storage locations. A variable must be declared before it is used in the program. A
variable can be used to store a value of any data type. The declaration statement defines the type of variable. The
declaration of variable is:

Type variable1, variable2, ……., variable N;

Scope of variables:

Java variables are generally classified into three types.

Instance Variables

Class variables

Local variables
1)Local Variables:

Local Variables are a variable that are declared inside the body of a method.

Instance Variables

Instance variables are defined without the STATIC keyword .They are defined Outside a method declaration. They are
Object specific and are known as instance variables.

Static Variables

Static variables are initialized only once, at the start of the program execution. These variables should be initialized first,
before the initialization of any instance variables.

Scanner Class:

Scanner class is defined in java.util package. It is used to scan the primitive typesfrom input resources (jdk 1.5).

int nextInt()

float nextFloat()

boolean nextBoolean()

char nextChar()

String next()

string nextLine()

double nextDouble()

Long nextLong()

byte nextByte()

Short nextShort()

Ex:

Scanner sc= new Scanner(System.in);

int a =sc.nextInt();

Operators:

Operator is nothing but a symbol operator can performs an operation between different operands. Java supports a rich
set of operators like arithmetic operators, relational operators, logical operators, and bitwise operators.

Arithmetic operators

These operators are used to perform arithmetic operations on variables and to construct mathematical expressions.
EXAMPLE:

import java.util.Scanner;

class First{

public static void main(String arg[])

int a,b;

Scanner p=new Scanner(System.in);

System.out.println("enter two values:");

a=p.nextInt();

b=p.nextInt();

System.out.println(a+b);

System.out.println(a-b);

System.out.println(a*b);

System.out.println(a%b);

System.out.println(a/b);

Mixed Mode:

When one of the operand is real and other is integer then the operation is called mixed mode arithmetic
expression.

Ex: 15 / 10.0 = 1.5 whereas 15/10 = 1

Relational operators:

These are used to test for equality of expressions. These results either true or false

value.

Operator Meaning

< Less than

> Greater than

<= Less than or equal to


>= Greater than or equal to

== Equal to

!= Not equal to

Example:

import java.util.Scanner;

class First{

public static void main(String arg[])

int a,b;

Scanner p=new Scanner(System.in);

System.out.println("enter two values:");

a=p.nextInt();

b=p.nextInt();

System.out.println(a<b);

System.out.println(a>b);

System.out.println(a<=b);

System.out.println(a>=b);

System.out.println(a==b);

System.out.println(a!=b);

Logical operators:

Logical operators are used to form compound conditions by combining two or morerelational expressions.

Operator Meaning

&& Logical AND

|| Logical OR

! Logical NOT
Example:

import java.util.Scanner;

class First{

public static void main(String arg[])

int a,b,c;

Scanner p=new Scanner(System.in);

System.out.println("enter three values:");

a=p.nextInt();

b=p.nextInt();

c=p.nextInt();

System.out.println(a<b && a<c);

System.out.println(a>b || b==c);

System.out.println(!(a!=b));

System.out.println(!(a<b && a<c));

Assignment operators

Assignment operator is used to assign the value of an expression to a variable. Java has a set of shorthand assignment
operators which are used in the form:

Variable op=exp;

Simple assignment operator is = (equal to). The general syntax of simple assignmentoperator is

Variable = constant or expression;

Operator Meaning

= Equal

+= Plus Eqaul

-= - eqaul

*= Multiple Equal
%= Modula Equal

/= Division Equal

import java.util.Scanner;

class First{

public static void main(String arg[])

int a,b,c;

Scanner p=new Scanner(System.in);

System.out.println("enter three values:");

a=p.nextInt();

b=p.nextInt();

a+=b;

System.out.println(a+" "+b);

b*=a;

System.out.println(a+" "+b);

Increment and decrement operators

Java has two very useful operators not generally found in many other languages. These are increment (++) and
decrement (--) operators. The operators ++ adds 1 to the operand while – subtracts 1 from the operand. Both are
unary operators and are used in the following form:

++m or m++; --m or m--;

import java.util.Scanner;

class First{

public static void main(String arg[])

{
int a=10

System.out.println(a++);

System.out.println(++a);

System.out.println(--a);

System.out.println(a--);

Conditional operator

The? : is a ternary operator available in Java. The operator is used to constructconditional expression in Java.

Syntax: exp1 ? exp2 : exp3;

The exp1 is evaluated first. Whene ver it is true, then exp2 is evaluated, if it is false then exp3 will be executed.

Ex: c = a>b?a:b;

import java.util.Scanner;

class First{

public static void main(String arg[])

int a,b,c;

Scanner p=new Scanner(System.in);

System.out.println("enter a value:");

a=p.nextInt();

b=(a%2==0)?"Even:"Odd";

System.out.println(b);

Bitwise operators

Java has set of bitwise operators to manipulate data at bit level. Bitwise operators may not be applied for float or
double.
Operator Meaning

& Bitwise AND

! Bitwise OR

^ Bitwise exclusive OR

~ Bitwise one’s complement

<< Shift left

>> Shift right

>>> Shift right with zero fill

Example:

import java.util.Scanner;

class First{

public static void main(String arg[])

int a,b,c;

Scanner p=new Scanner(System.in);

System.out.println("enter three values:");

a=p.nextInt();

b=p.nextInt();

System.out.println(a&b);

System.out.println(a|b);

System.out.println(a^b);

System.out.println(a<<b);

System.out.println(a>>b);

}
}

Special operators

Java supports special operators such as instanceof operator and member selectionoperator.

Instanceof:

It is an object reference operator and returns true if the object on the left side is the instance of the class given on
right side otherwise it returns false.

Ex: sai instanceof student;

The statement is true if the object sai belongs to the class student.

DOT operator:

The dot (.) operator is used to access the instance variables and methods of classobjects.

Ex: sai.age; sai.total_marks ();

Operators and their precedence:

Priority Operator Associativity

1 . () L to R

2 -, ++, --, !, ~, (type) R to L

3 *, /,% L to R

4 +,- L to R

5 << , >> , >>> L to R

6 <, <=, >, >=, instanceof L to R

7 ==, != L to R

8 to 10 &, ^, | L to R

11 , 12 && and || L to R

13 ?: R to L

14 = R to L
JAVA COMMENTS:

Comments can be used to explain Java code, and to make it more readable. It can also be used to prevent execution
when testing alternative code.

Single-line comments start with two forward slashes (//).

Any text between // and the end of the line is ignored by Java (will not be executed).

This example uses a single-line comment before a line of code:

Example

// This is a comment System.out.println("Hello World");

Java Multi-line Comments

Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by Java.

This example uses a multi-line comment (a comment block) to explain thecode:

/* The code below will print the words Hello World to the screen, and it is amazing */ System.out.println("Hello
World");

ESCAPE SEQUENCE CHARACTERS:

A character preceded by a backslash (\) is an escape sequence and has a special meaning to thecompiler.

The following table shows the Java escape sequences.


Escape Description
Sequence

\t Inserts a tab in the text at this point.

\b Inserts a backspace in the text at this point.

\n Inserts a newline in the text at this point.

\r Inserts a carriage return in the text at this point.

\f Inserts a form feed in the text at this point.

\' Inserts a single quote character in the text at this


point.

\" Inserts a double quote character in the text at this


point.

\\ Inserts a backslash character in the text at this point.


Decision making statements or Branching

Branching is used to break the sequential order of a program.

In the term software or computer programming, it has a set of instructions called program. These instructions
are also called statements, which occurs sequentially or in either conditional way or in the iterative way. To
handle such types of statements, some flow of controls required. These flow controls are called control
statements.

In other words, the control statements are used to control the cursor in a program according to the condition or
according to the requirement in a loop. Further we can say, changing the order of flow controls, these are
required. There are mainly three types of control statements or flow controls. These are illustrated as below:

Branching

Looping

Jumping

Branching statements

It is also called decision making statement. These are used when a condition arises in

a statement. The various branching statements used are as:

If statement

Switch statement

Conditional operator

If statement:

The if statement is a powerful decision making statement which can handle a single condition or group of
statements. These have either true or false action. There are mainly four types of if statements used in java are
as:

• Simple if statement
• If else statement
• Nested if statement
• Else – if statement or multi condition if statement.
Simple if statement:

When only one condition occurs in a statement then simple if statement is used having one block. The general
syntax of

simple if statement is:

if (condition)

If_block;

Statement –x;
If – else statement:

This statement also has a single condition with two different blocks. One is true block and the other is false
block. The general syntax is used as:

if (condition)

If-block;

Else

Else-block;

}
Nested – if statement:

When an if statement occurs within another if statement, then such type of statement is called nested if
statement. When we have number of conditions are involved in our program then we may have to use netsed if
else. The general syntax of this statement is as:

if else Ladder statement of if else if statement:

In a complex problem, no. of conditions arise in a sequence, then we can use ladder if or else if statement to
solve the problem in a simple manner. In this statement 1st condition will be checked, if it is true then action will
be taken, otherwise further next condition will be checked and this process will continue till the end of the
conditions. The general syntax is as:
Switch statement:

When no. of conditions occurs in a problem and it is very difficult to solve such type of complex problem with the
help of ladder if statement. Then there is need of such type of statement which should have different
alternatives or different cases to solve the problem in simple and easy way. For this purpose switch statement is
used. It is also called case statement because it has different cases and different blocks. It is also called multi
decision statement having multiple blocks. The float type of values is not accepted in switch statements. The
general syntax of the switch statement is:

Note:

here can be one or N number of case values for a switch expression.

The case value must be of switch expression type only. The case value must be literal or constant. It doesn't
allow variables.

The case values must be unique. In case of duplicate value, it renders compile-time error.

The Java switch expression must be of byte, short, int, long (with its Wrapper type), enums and string.

Each case statement can have a break statement which is optional. When control reaches to the break
statement, it jumps the control after the switch expression. If a break statement is not found, it executes the
next case.

The case value can have a default label which is optional.


Syntax:

Loops

Looping statement:

When a single statement or group of statements will be executed again and again in a program (in an iterative
way), then such type of processing is called loop.

Entry Control Loop:

In entry control loop first of all condition is checked, if it is true, then body of loop is executed, otherwise the
control is moved out of the loop i.e. we can exit from the loop, when the condition becomes false.

The while loop and for loops are the example

of the entry controlled loop. The flow symbol for entry control loop is as:

Exit Control loop:

In the exit control loop, first body of loop is executed and then condition is checked. If condition is true, then
again body of the loop is executed. If the condition is false, then control will move out from the loop. Example of
exit control loopis do statement. The general flow symbol is:

While statement:

While statement or while loop is an entry control loop. In this, first of all condition is checked and if it is true,
then group of statements or body of loop is

executed. It will execute again and again till condition becomes false. The general syntax is:
while(condition)

While-body;

Do statement or Do-loop:

Do statement is exit control loop. It is also called do-while statement. In this statement, first body of the loop is
executed and then the condition is checked. If condition is true, then the body of the loop is executed. When
condition becomes false, then it will exit from the loop. The syntax of do-loop is as follows:

Syntax:

do{

do-while body;

}while(condition);

For statement or for loop:

It a-looping statement, which repeat again and again till it satisfies the defined condition. It is one step loop,
which initialize, check the condition and increment decrement the step in the loop in a single statement. The
general syntax is as:

For(initial value; condition; increment or decrement)

For-body;

It is also entry controlled loop, where first condition is checked and the body of the loop be executed. In this
case, first we initialize the value, then in the loop we apply the condition and further we increment or decrement
the loop according to requirement. After execution or completion of the body of the loop when the condition
becomes false, the statement-x will be executed.

Nested for statement:

When a for statement is executed within another for statement, then it is called nested for statement. We can
apply number of nested for statements. The general syntax is:

for (initial value1; test condition1; increment1/decrement1)

{
for (initial value2; test condition2; increment2 /decrement2)

inner- body of the loop;

outer-body of the loop;

statement-X;

For one value of outer loop, inner loop will repeat n times. So inner loop will be completed first and then outer
loop will be completed. After completion of inner and outer loop, statement-x will be executed.

Jumping Statements:

Sometimes, when executing a loop it becomes want to skip a part of the loop or to leave the loop as soon as a
certain condition occurs. For example, consider the case of searching for a particular number in a list containing,
say, 100 numbers. A program loop written for reading and testing the numbers a 100 times must be terminated
as soon as the desire number is found. Java permits a jump from one statement to the end or beginning of a
loop as well as a jump out of a loop.

When the break statement is encountered inside a loop, the loop is immediately exited and the program
continues with the statement immediately following the loop. When the loops are nested, the break would only
exit from the loop containing it. That is, the break will exit only a single loop.

During the loop operations, it may be necessary to skip a part of the body of the loop under certain conditions.
Unlike the break which causes the loop termination, the continue, as the name implies, cause the loop to be
continued with the next iteration (repetition) after skipping any statement in between.

Type casting

Type casting means represent a value of type into a variable of another type. Casting into a smaller type may
result in a loss of data. For some types java does the conversion of the assigned value automatically; there is no
need of cast. This is known as automatic type conversion. Automatic type conversion is possible only if we are
assigning values into higher precision types.

Syntax:

variable = (type) value;Ex: int m=60; byte n=(byte) m;

In java we have two types of type casting, they are:

Implicit

Explicit

Implicit:
To convert lower datatype to higher datatype is called implicit typecasting. In implicit type casting convert one to
another datatype automatically.

Example:

import java.util.Scanner;

class First{

public static void main(String arg[])

char a='b';

int b=40;

int c=a+b;

System.out.println(c);

Explicit:

To convert higher to lower datatype is called explicit typecasting. In java higher to lower can’t convert
automatically.

Example:

import java.util.Scanner;

class First{

public static void main(String arg[])

int b=20;

byte a=45;

byte c=(byte)(b+a);

System.out.println(c);

}
}

Branching

Branching is used to break the sequential order of a program. In java we have two types of branching available.

Conditional branching

Unconditional branching

Conditional Branching:

Simple if:
OOPS(Object Oriented Programming Language)

Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-Oriented Programming is a
methodology or paradigm to design a program using classes and objects. It simplifies software development and
maintenance by providing some concepts:

Object:

An entity that has state and behaviour is known as an object e.g., chair, bike, marker, pen, table, car, etc. It can be
physical or logical (tangible and intangible). The example of an intangible object is the banking system.

An object has three characteristics:

State: represents the data (value) of an object.

Behaviour: represents the behaviour (functionality) of an object such as deposit, withdraw, etc.

Identity: An object identity is typically implemented via a unique ID. The value of the ID is not visible to the external
user. However, it is used internally by the JVM to identify each object uniquely.

An object is an instance of a class. A class is a template or blueprint from which objects are created. So, an object is the
instance (result) of a class.

Object Definitions:

An object is a real-world entity.

An object is a runtime entity.

The object is an entity which has state and behaviour.

The object is an instance of a class.

Class:

A class is a group of objects which have common properties. It is a template or blueprint from which objects are
created. It is a logical entity. It can't be physical.

A class in Java can contain:

Fields
Methods

Constructors

Blocks

Nested class and interface

Example:

class Student{

int id;

String name;

public static void main(String args[]){

Student s1=new Student(); ➔ Object Creation

System.out.println(s1.id);

System.out.println(s1.name);

Types of varibles

Instance Variables:

If the value of a variable is varied from object to object, then such type of variables are called instance variables.

For every object a separate copy of instance variables will be created.

Where we can declare Instance Variables:

Inside Constructor.

Outside of the class by using object reference variable.

Example:

class First{

String name;

int roll;
First(String a,int b)

name=a;

roll=b;

public void display()

System.out.println("Name of the student:"+name);

System.out.println("Roll of the student:"+roll);

public static void main(String arg[])

First t=new First("ravi",98);

First p=new First("ramesh",87);

t.display();

p.display();

How to Access Instance Variables:

We can access instance variables with in the class directly and outside of the class by using object reference.

Example:

class Abc{

int b=30;

class First{

int a=20;

public static void main(String arg[])

First t=new First();


Abc p=new Abc();

System.out.println(t.a+p.b);

Types of Methods:

Inside Python class 3 types of methods are allowed

Instance Methods

Static Methods

Instance Method:

Instance methods are the methods defined under a class and we can call such functions only after creating an object
of that class. In fact, the call to the instance method is made through the created object itself.

Instance methods can access instance variables and instance methods directly and undeviating.

Instance methods can access static variables and static methods directly.

class Abc{

public void m1()

System.out.println("Hello world");

}
class First{

public void m2()

System.out.println("I am from m2");

public static void main(String arg[])

Abc t=new Abc();

First p=new First();

p.m2();

t.m1();

}
Constructor

Constructor:

Constructor is a special type of function whose name is same as the class name.

The main advantage of constructor is to initialize of an object but not creation of an object, whenever an object was
created then the constructor will invoke automatically.

once we creates a object compulsory we should Perform initialization then only the object is an Position respond
properly.

Whenever we are creating an object some Peale of the code will be executed automatically to perform initialization of
the object. This peace of the code is nothing but constructors. hence the main purpose of Constructor is initialization
of an Object.

Example:

class First{

First()

System.out.println("Hello world");

}
public static void main(String arg[])

First t=new First();

Rules for constructor:

Constructor name must be the same as its class name

Return type concept not applicable for constructor.

If you are trying to declare return type for the constructor then we won’t get any compile time error because compiler
treats its normal method.

Class Test{

void Test()

{ .

A Java constructor cannot be abstract, static, final, and synchronized.

The only applicable modifiers for constructors are public, private, protected, default. If you trying to use any other
modifier we will get compile time error.

Constructor again divided into 3 types:

Default Constructor

No- argument constructor

Parameterized constructor

Default constructor:

Compiler is responsible to generate default constructor (but not jvm).

If you are not writing any construct then only compiler will generate default constructor.

Example:

class First{

public void m1()

{
System.out.println("Hello world");

public static void main(String arg[])

First t=new First();

t.m1();

No-argument constructor:

Whenever constructor having no parameters is called default constructor.

Example:

class First{

int Stri

First()

System.out.println ("Hello world")

public static void main(String arg[])

First t=new First();

t.m1();

NOTE: Using default constructor will get duplication of data.


Parameterized Constructor:

When a constructor having parameters then that constructor called as parameterised constructor.

Example:

class First

static String cname="XYZ";

String name;

int roll;

First(String a,int b)

name=a;

roll=b;

public void display()

System.out.println("Name of the student:"+name);

System.out.println("Roll of the student:"+roll);

System.out.println("Name of the college:"+cname);

public static void main(String arg[])

First t=new First("ravi",98);

First p=new First("ramesh",87);


t.display();

p.display();

Instance Initializer block:

The instance block can be defined as the name-less method in java inside which we can define logic and they
possess certain characteristics as follows. They can be declared inside classes but not inside any method. Instance
block logic is common for all the objects.

Note: The java compiler copies the code of instance initializer block in every constructor.

Example:

class First

System.out.println ("Hello world");

public static void main(String arg[])

First t=new First ();

Rules:

The instance initializer block is created when instance of the class is created.

The instance initializer block is invoked after the parent class constructor is invoked (i.e. after super() constructor call).

The instance initializer block comes in the order in which they appear.

Difference between instance block and constructor:

The main Purpose of constructor is to perform initialization of an object.


But other than initialization if you want to perfumes any activity for every object creation then we should go for
instance block. (Like updating one entry in the database for every object creation (00) incrementing count value for
every etc.)

Both constructor and instance block hove their own different purposes and replacing one concept with and then
concept may not work always.

Both constructor and instance block will be executed for every object creation. But instance block first followed by
constructor next.

Static:

The static keyword in Java is used for memory management mainly. We can apply static keyword with variables,
methods, blocks and nested classes. The static keyword belongs to the class than an instance of the class.

The static can be:

Variable (also known as a class variable)

Method (also known as a class method)

Block

Nested class

Static Variables:

If you declare any variable as static, it is known as a static variable.

If the value of a variable is not varied from object to object, such type of variables we have to declare with in the class
directly but outside of methods. Such types of variables are called Static variables.

For total class only one copy of static variable will be created and shared by all objects of that class.

We can access static variables either by class name or by object reference. But recommended to use class name.

Example:

class First{

static String cname="XYZ";

String name;

int roll;

First(String a,int b)

name=a;

roll=b;
}

public void display()

System.out.println("Name of the student:"+name);

System.out.println("Roll of the student:"+roll);

System.out.println("Name of the college:"+cname);

public static void main(String arg[])

First t=new First("ravi",98);

First p=new First("ramesh",87);

t.display();

p.display();

How to Access static Variables:

We can access static variables either by class name or by object reference. But recommended to use class name.

Example:

class Abc{

static int b=30;

class First{

static int a=20;

public static void main(String arg[])

System.out.println(a+Abc.b);

}
Static method:

A static method in Java is a method that is part of a class rather than an instance of that class. Every instance of a class
has access to the method. Static methods have access to class variables (static variables) without using the class's
object (instance). Only static data may be accessed by a static method.

A static method in Java is a method that is part of a class rather than an instance of that class.

Every instance of a class has access to the method.

Static methods have access to class variables (static variables) without using the class’s object (instance).

Only static data may be accessed by a static method. It is unable to access data that is not static (instance variables).

In both static and non-static methods, static methods can be accessed directly.

Example:

class Abc{

public static void m1()

System.out.println("Hello world");

class First{

public static void m2()

System.out.println("I am from m2");

public static void main(String arg[])

Abc.m1();

m2();

}
}

Static block:

When a block is decorated or associated with the word static, it is called a static block. Static Block is known as
the static clause. A static block can be used for the static initialization of a class.

To invoke the static block, there is no specific way since the static block gets executed automatically, whenever in the
memory the class is loaded. Observe the following illustration.

Example:

class First{

static {

System.out.println("Hello world");

public static void main(String arg[])

NOTE:

We know that static blocks are loaded automatically (see the above examples) when the class is loaded. In other
words, there is no need for a method to invoke the static blocks. Then the question arises is there any need of the
main() method? The answer depends on the GDK version the user is using.

Inheritance

To access one class properties into another class is called inheritance.

Types of Inheritance:
Single Inheritance

Multi-Level Inheritance

Hierarchical Inheritance

Multiple Inheritance

Hybrid Inheritance

Cyclic Inheritance

Why use inheritance:

For Method Overriding (so runtime polymorphism can be achieved).

For Code Reusability.

Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are
created.

Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class,
or child class.

Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class
or a parent class.

Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of
the existing class when you create a new class. You can use the same fields and methods already defined in the
previous class.

The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of
"extends" is to increase the functionality.

In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called child or
subclass.

Single Inheritance:

The concept of inheriting the properties from one class to another class is known as single inheritance.

Example:

class Abc{

public void m1()

System.out.println("i am from m1");

class Bca extends Abc{

public void m3()


{

System.out.println("i am from m3");

class First{

public static void main(String arg[])

Bca t=new Bca();

t.m1();

t.m3();

Multi-Level Inheritance:

The concept of inheriting the properties from multiple classes to single class with the concept of one after
another is known as multilevel inheritance.

Example:

class Abc{

public void m1()

System.out.println("i am from m1");

class Bca extends Abc{

public void m2()

System.out.println("i am from m2");

class Cab extends Bca{

public void m3()

{
System.out.println("i am from m3");

class First{

public static void main(String arg[])

Cab t=new Cab();

t.m1();

t.m2();

t.m3();

Hierarchical Inheritance:

The concept of inheriting properties from one class into multiple classes which are present at same level is known as
Hierarchical Inheritance.

Example:

class Abc{

public void m1()

System.out.println("i am from m1");

class Bca extends Abc{

public void m2()

System.out.println("i am from m2");

class Cab extends Abc{

public void m3()


{

System.out.println("i am from m3");

class First{

public static void main(String arg[])

Cab t=new Cab();

t.m1();

t.m3();

Bca p=new Bca();

p.m1();

p.m2();

Multiple Inheritance:

The concept of inheriting the properties from multiple classes into a single class at a time, is known as multiple
inheritance.

Example:

class Abc{

public void m1()

System.out.println("i am from m1");

class Bca{

public void m2()

System.out.println("i am from m2");

}
}

class Cab extends Bca,Abc{

public void m3()

System.out.println("i am from m3");

class First{

public static void main(String arg[])

Cab t=new Cab();

t.m1();

t.m2();

t.m3();

Output: First.java:13: error: '{' expected

class Cab extends Bca,Abc{

Note: Multiple Inheritance not support by java.

Hybrid Inheritance:

Combination of Single, Multi-level, multiple and Hierarchical inheritance is known as Hybrid Inheritance.

Cyclic Inheritance:

The concept of inheriting properties from one class to another class in cyclic way, is called Cyclic inheritance. Python
won't support for Cyclic Inheritance of course it is really not required.

Example:

class Abc extends Bca{

public void m1()


{

System.out.println("i am from m1");

class Bca extends Abc{

public void m2()

System.out.println("i am from m2");

class First{

public static void main(String arg[])

Bca p=new Bca();

p.m1();

p.m2();

Output:

First.java:1: error: cyclic inheritance involving Abc

class Abc extends Bca{

Composition:
Composition is a "belong-to" type of relationship in which one object is logically related with other objects. It is also
referred to as "has-a" relationship. We can understand has-a or belong-to by using the following example:

Aggregation :

Aggregation relationship is also a "has-a" relationship. The only difference between Aggregation and Composition is
that in Aggregation, objects are not tightly coupled or don't involve owning. All the objects are independent of each
other and can exist even if the parent object gets deleted.

Aggregation Composition

Association between two objects that defines A specific type of Aggregation that implies
the "has-a" relationship is referred to as ownership is referred to as Composition.
Aggregation.

In Aggregation, objects can remain in the In a composition relationship, objects


scope of a system without each other. cannot remain in the scope of a system
without each other.

In Aggregation, linked objects are independent In Composition, objects are tightly coupled
of each other. or dependent on each other.

In Aggregation, if we delete the parent object, In Composition, if we delete a parent


the child object will still exist in the system. object, the child object also gets deleted.
For example, if we remove wheels from a car, For example, if we delete a folder, the files
the car can function adequately with another will also get deleted which contain in the
wheel. folder.

We represent it by using the filled diamond. We represent it by using the empty


diamond.

In Aggregation, child objects don't have a In Composition, child objects have a


lifetime. lifetime.

In Aggregation, if we delete an assembly, it In the case of owning a class, it affects the


will never affect its parts. containing class object.
Arrays

An array is a collection of similar type of elements which has contiguous memory location.

Java array is an object which contains elements of a similar data type. Additionally, the elements of an array are stored
in a contiguous memory location.

Array in Java is index-based, the first element of the array is stored at the 0th index, and 2nd element is stored on 1st
index and so on.

Advantage:

Code Optimization: It makes the code optimized; we can retrieve or sort the data efficiently.

Random access: We can get any data located at an index position.

Disadvantages

Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime. To solve this
problem, collection framework is used in Java which grows automatically

Types of Array in java

There are two types of array.

Single Dimensional Array

Multidimensional Array

Single Dimensional Array:

An array with only one subscript is called single dimension array.


Single Dimensional Array in Java

Syntax to Declare an Array in Java

dataType[] arr; (or)

dataType []arr; (or)

dataType arr[];

Instantiation of an Array in Java

a=new datatype[size];

We can create 1D arrays in three ways.

step-by-step

one-go

using scanner class

step-by-step:

class First{

public static void main(String arg[])

int[] a=new int[5];

a[0]=65;

a[1]=78;

a[2]=98;

a[3]=91;

a[4]=76;

for(int i=0;i<a.length;i++)

System.out.println(a[i]);

One-go:

class First{

public static void main(String arg[])


{

int[] a={45,76,89,12,43};

for(int b:a)

System.out.println(b);

Using Scanner class:

import java.util.Scanner;

class First{

public static void main(String arg[])

Scanner p=new Scanner(System.in);

int[] a=new int[5];

System.out.println("Enter array elments:");

for(int i=0;i<a.length;i++)

a[i]=p.nextInt();

for(int b:a)

System.out.println(b);

For-each loop:

import java.util.Scanner;
class First{

public static void main(String arg[])

Scanner p=new Scanner(System.in);

int[] a=new int[5];

System.out.println("Enter array elments:");

for(int b:a)

System.out.println(b);

Write a program to add sum of the elements in an array:

import java.util.Scanner;

class First{

public static void main(String arg[])

Scanner p=new Scanner(System.in);

int[] a=new int[5];

System.out.println("Enter array elments:");

for(int i=0;i<a.length;i++)

a[i]=p.nextInt();

}
for(int b:a)

System.out.println(b);

Write a program to multiple array elements:

import java.util.Scanner;

class First{

public static void main(String arg[])

Scanner p=new Scanner(System.in);

int[] a=new int[5];

int mul=0;

System.out.println("Enter array elments:");

for(int i=0;i<a.length;i++)

a[i]=p.nextInt();

for(int b:a)

mul=mul*b;

System.out.println(mul);

Write a program to searching element in an array

import java.util.Scanner;
class First{

public static void main(String arg[])

Scanner p=new Scanner(System.in);

int[] a=new int[5];

int count=0;

System.out.println("Enter array elments:");

for(int i=0;i<a.length;i++)

a[i]=p.nextInt();

System.out.println("Enter a value:");

int n=p.nextInt();

for(int b:a)

if(b==n)

count++;

if(count>0)

System.out.println("Available");

else

System.out.println("Not available");

}
Write a program to print even numbers in an array:

import java.util.Scanner;

class First{

public static void main(String arg[])

Scanner p=new Scanner(System.in);

int[] a=new int[5];

int count=0;

System.out.println("Enter array elments:");

for(int i=0;i<a.length;i++)

a[i]=p.nextInt();

System.out.println("-------------");

for(int b:a)

if(b%2==0)

System.out.println(b);

Write a program to print odd numbers in an array:

import java.util.Scanner;

class First{

public static void main(String arg[])

Scanner p=new Scanner(System.in);


int[] a=new int[5];

int count=0;

System.out.println("Enter array elments:");

for(int i=0;i<a.length;i++)

a[i]=p.nextInt();

System.out.println("-------------");

for(int b:a)

if(b%2!=0)

System.out.println(b);

Write a program to print array in sorting order:

import java.util.Scanner;

class First{

public static void main(String arg[])

Scanner p=new Scanner(System.in);

int[] a=new int[5];

System.out.println("Enter array elments:");

for(int i=0;i<a.length;i++)
{

a[i]=p.nextInt();

System.out.println("-------------");

for(int i=0;i<a.length;i++)

for(int j=i+1;j<a.length;j++)

if(a[i]>a[j])

int n=a[i];

a[i]=a[j];

a[j]=n;

for(int b:a)

System.out.print(b+" ");

System.out.println("-------------");

for(int i=a.length-1;i>=0;i--)

System.out.print(a[i]);

Anonymous Array in Java


Java supports the feature of an anonymous array, so you don't need to declare the array while passing an array to the
method.

Example:

class A{

public static void m1(int a[])

for(int b:a)

System.out.println(b);

public static void main(String a[])

m1(new int[]{2,3,4});

Two-Dimensional array:

An array with only 2 subscripts is called two-dimensional array.

Or

Collection of 1D arrays is called two-dimensional array.

syntax to Declare Multidimensional Array in Java

dataType[][] r; (or)

dataType [][]r; (or)

dataType r[][]; (or)

dataType []r[];

Example to instantiate Multidimensional Array in Java

int[][] arr=new int[3][3];

We can create 1D arrays in three ways.

step-by-step

one-go
using scanner class

Step-by-Step:

class First{

public static void main(String... ar)

int[][] a=new int[2][2];

a[0][0]=78;

a[0][1]=56;

a[1][0]=87;

a[1][1]=65;

for(int i=0;i<2;i++)

for(int j=0;j<2;j++)

System.out.print(a[i][j]+" ");

System.out.println();

One-go:

class First{

public static void main(String... ar)

int[][] a={{24,56},{78,98}};

for(int i=0;i<2;i++)

for(int j=0;j<2;j++)

{
System.out.print(a[i][j]+" ");

System.out.println();

Using Scanner class:

Example:

import java.util.Scanner;

class First{

public static void main(String arg[])

Scanner p=new Scanner(System.in);

int[][] a=new int[2][2];

System.out.println("Enter values:");

for(int i=0;i<2;i++)

for(int j=0;j<2;j++)

a[i][j]=p.nextInt();

System.out.println("-------------");

for(int i=0;i<2;i++)

for(int j=0;j<2;j++)

System.out.print(a[i][j]+" ");

System.out.println();
}

Output:

D:\9-10 Am>javac First.java

D:\9-10 Am>java First

Enter values:

98

67

56

12

-------------

98 67

56 12

Addition of two matrixes:

Example:

import java.util.Scanner;

class First{

public static void main(String arg[])

Scanner p=new Scanner(System.in);

int[][] a=new int[2][2];

int[][] b=new int[2][2];

int[][] c=new int[2][2];

System.out.println("Enter values:");

for(int i=0;i<a.length;i++)

for(int j=0;j<a.length;j++)
{

a[i][j]=p.nextInt();

System.out.println("-------------");

System.out.println("Enter values:");

for(int i=0;i<b.length;i++)

for(int j=0;j<b.length;j++)

b[i][j]=p.nextInt();

for(int i=0;i<c.length;i++)

for(int j=0;j<c.length;j++)

c[i][j]=a[i][j]+b[i][j];

for(int i=0;i<c.length;i++)

for(int j=0;j<c.length;j++)

System.out.print(c[i][j]+" ");

System.out.println();

}
}

Output:

D:\9-10 Am>javac First.java

D:\9-10 Am>java First

Enter values:

-------------

Enter values:

68

10 12

Multiplication of two matrixes:

Example:

import java.util.Scanner;

class First{
public static void main(String arg[])

Scanner p=new Scanner(System.in);

int[][] a=new int[2][2];

int[][] b=new int[2][2];

int[][] c=new int[2][2];

System.out.println("Enter values:");

for(int i=0;i<a.length;i++)

for(int j=0;j<a.length;j++)

a[i][j]=p.nextInt();

System.out.println("-------------");

System.out.println("Enter values:");

for(int i=0;i<b.length;i++)

for(int j=0;j<b.length;j++)

b[i][j]=p.nextInt();

for(int i=0;i<c.length;i++)

for(int j=0;j<c.length;j++)

c[i][j]=a[i][j]*b[i][j];

}
for(int i=0;i<c.length;i++)

for(int j=0;j<c.length;j++)

System.out.print(c[i][j]+" ");

System.out.println();

Output:

D:\9-10 Am>javac First.java

D:\9-10 Am>java First

Enter values:

-------------

Enter values:

5 12

21 32
Jagged Array in Java:

If we are creating odd number of columns in a 2D array, it is known as a jagged array. In other words, it is an array of
arrays with different number of columns.

Advantages of Jagged Array

Jagged arrays have several advantages over multidimensional arrays with a fixed size:

Memory Efficiency: Jagged arrays are more memory-efficient than multidimensional arrays because they only allocate
memory for the elements they need. In a multidimensional array with a fixed size, all the memory is allocated, even if
some elements are unused.

Flexibility: Jagged arrays are more flexible than multidimensional arrays because they can have different sizes for each
row. Jagged arrays enable the representation of non-rectangular or irregular data structures.

Easy to Initialize: Jagged arrays are easy to initialize because you can specify the size of each row individually. The
suitability of jagged arrays lies in their ability to store data that varies in size or is generated dynamically.

Enhanced Performance: Jagged arrays can provide enhanced performance in certain scenarios, such as when you need
to perform operations on each row independently or when you need to add or remove rows dynamically.

More natural representation of data: In some cases, jagged arrays may be a more natural representation of data than
rectangular arrays. For example, when working with irregularly shaped data such as geographic maps, a jagged array
can be a more intuitive way to represent the data.

Easier to manipulate: Jagged arrays can be easier to manipulate than rectangular arrays because they allow for more
direct access to individual elements. With rectangular arrays, you may need to use more complex indexing or slicing
operations to access subsets of the data.

Example:

import java.util.Scanner;

class First{

public static void main(String arg[])

Scanner p=new Scanner(System.in);

int[][] a={{12,34,56},{67,89},{98,34,87}};

for(int i=0;i<a.length;i++)

for(int j=0;j<a[i].length;j++)

{
System.out.print(a[i][j]+" ");

System.out.println();

Output:

D:\9-10 Am>javac First.java

D:\9-10 Am>java First

12 34 56

67 89

98 34 87

Example-2:

import java.util.Scanner;

class First{

public static void main(String arg[])

Scanner p=new Scanner(System.in);

int[][] a=new int[3][];

a[0]=new int[3];

a[1]=new int[2];

a[2]=new int[1];

System.out.println("Enter array elements:");

for(int i=0;i<a.length;i++)
{

for(int j=0;j<a[i].length;j++)

a[i][j]=p.nextInt();

for(int i=0;i<a.length;i++)

for(int j=0;j<a[i].length;j++)

System.out.print(a[i][j]+" ");

System.out.println();

Output:

D:\9-10 Am>javac First.java

D:\9-10 Am>java First

Enter array elements:

45

67

89

23

45

98

45 67 89

23 45

98
What is the class name in java:

In Java, an array is an object. For array object, a proxy class is created whose name can be obtained by
getClass().getName() method on the object.

Example:

class A{

public static void main(String ar[])

int[] a=new int[6];

System.out.println(a.getClass().getName());

Output:

D:\9-10 Am>javac First.java

D:\9-10 Am>java First

[I

Command Line Arguments:

The command line argument in java is the information passed to the program at the time of running the
program.

The arguments passed from the console can be received in the java program and it can be used as an input.

Example:

class A{

public static void main(String a[])

{
for(String b:a)

System.out.println(b);

Output:

D:\java>javac A.java

D:\java>java A "abc" "bca"

Array elements are:

abc

bca

In command line arguments, you pass anything it always take string type only if you convert String to any data type
follow the Example:

Example:

class A{

public static void main(String a[])

int s1=Integer.parseInt(a[0]);

int s2=Integer.parseInt(a[1]);

System.out.println(“Total=”+(s1+s2));

Output:

D:\java>javac A.java

D:\java>java A 5 6
Total=11

Variable length argument method (or) var-arg method:

The varrags allows the method to accept zero or muliple arguments. Before varargs either we use overloaded method
or take an array as the method parameter but it was not considered good because it leads to the maintenance
problem. If we don't know how many argument we will have to pass in the method, varargs is the better approach.

Java 1.5 introduced varargs. Varargs is a short name for variable arguments

Syntax:

<Return type>(datatype… variblename){}

Example:

class First{

public void m1(int... b)

for(int c:b)

System.out.println(c);

public static void main(String... a)

First t=new First();

t.m1(2,3,4);

While using the varargs, you must follow some rules otherwise program code won't compile. The rules are as follows:

Here can be only one variable argument in the method.

Variable argument (varargs) must be the last argument.

void method(String... a, int... b){}//Compile time error


void method(int... a, String b){}//Compile time error

Mathematical functions

Mathematical functions such as cos, sqrt, log etc. are frequently used in analysis of real life problems. Java supports
these basic math functions through Math class defined in the java.lang package. These functions should be used as
follows.

Math.function_name();

Ex:double y= Math.sqrt();

The various functions available with the Math class are listed below.

Function Action

sin(x) Returns the sine of the single x in radians

cos(x) Returns the cosine of the angle x in radians


Function Action

tan(x) Returns the tangent of the angle x in radians

asin(y) Returns the angle whose sine is y

acos(y) Returns the angle whose cosine is y

atan(y) Returns the angle whose tangent is y

pow(x,y) Returns x raised to y (xy)

exp(x) Returns e raised to x (ex)

log(x) Returns the natural logarithm of x

sqrt(x) Returns the square root of x (double precision)

abs(x) Returns the absolute value of x

max(a,b) Returns the maximum of a and b

min(a,b) Returns the minimum of a and b

ceil(x) Returns the smallest whole number greater than or equal

to x.

floor(x) Returns the largest whole number less than or equal to x.

rint(x) Returns the truncated value of x.

round(x) Returns the integer closest to the argument.

Java Method Signature:

In Java programming, a method signature refers to the unique identifier of a method. It consists of the method name
and its parameter list. The signature helps differentiate one method from another and allows the Java compiler to
match method calls with their corresponding definitions. The method signature includes the following components:

Method name: It is the name given to the method, which should be a valid Java identifier and follows the naming
conventions. The method name should be descriptive and reflect the functionality it performs.

Parameter list: It specifies the parameters or arguments that a method expects to receive when it is called. Each
parameter in the list consists of the parameter type and its name. Multiple parameters are separated by commas. If a
method doesn't require any parameters, an empty parameter list is used. For example:

public void methodName() {}

If a method has parameters, the signature includes the parameter types and names:

public void methodName(int param1, String param2) {}


Return type: It defines the data type of the value that the method returns. If a method doesn't return any value, the
return type is specified as void. If it returns a value, the return type should match the data type of the returned value.
For example:

Polymorphism:

Polymorphism means "many forms".

Polymorphism again divided into two types:

Eg1: yourself is best example of polymorphism. In front of your parents you will have one type of behavior and with
friends another type of behavior. Same person but different behavior’s at different places, which is nothing but
polymorphism.

Overloading

Overriding

Method overloading:

If a class has multiple methods having same name but different in parameters, it is known as Method
Overloading. If we have to perform only one operation, having same name of the methods increases the readability of
the program.

Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java

By changing number of arguments

By changing the data type

In java, method overloading is not possible by changing the return type of the method only.

Method Overloading: changing no. of arguments:

Example

class First{

public void m1()

System.out.println("no arg method");


}

public void m1(int a)

System.out.println("one arg method");

public void m1(int a,int b)

System.out.println("Two arg method");

public static void main(String arg[])

First t=new First();

t.m1();

t.m1(2);

t.m1(4,5);

Method Overloading: changing data type of arguments:

class First{

public int m1()

System.out.println("no arg method");

return 0;
}

public double m1(double a)

System.out.println("one arg method");

return 0.0;

public static void main(String arg[])

First t=new First();

t.m1();

t.m1(2.6f);

In java, method overloading is not possible by changing the return type of the method only because of ambiguity. Let's
see how ambiguity may occur:

Compile Time Error is better than Run Time Error. So, java compiler renders compiler time error if you declare the
same method having same parameters.

Can we overload java main() method:

Yes, by method overloading. You can have any number of main methods in a class by method overloading.
But JVM calls main() method which receives string array as arguments only.

Eample:

class First{

public static void main(int a)

System.out.println("hello");

}
public static void main(double a)

System.out.println("hii");

public static void main(String arg[])

main(2);

main(3.4);

Method Overloading and Type Promotion:

One type is promoted to another implicitly if no matching data type is found. Let's understand the concept by the
figure given below:

Exmple:

class First{

public int m1()

System.out.println("no arg method");

return 0;

public double m1(int a)

System.out.println("one arg method");

return 0.0;
}

public static void main(String arg[])

First t=new First();

t.m1();

t.m1('c');

If there are matching type arguments in the method, type promotion is not performed.

Example:

class First{

public void m1(int a,int b)

System.out.println("no arg method");

public void m1(long a,long b)

System.out.println("one arg method");

public static void main(String arg[])

First t=new First();

t.m1(1,2);

t.m1(1l,2l);

}
}

If there are no matching type arguments in the method, and each method promotes similar number of arguments,
there will be ambiguity.

Example:

class First{

public void m1(int a,long b)

System.out.println("no arg method");

public void m1(long a,int b)

System.out.println("one arg method");

public static void main(String arg[])

First t=new First();

t.m1(1,2);

Output:

D:\9-10 Am>javac First.java

First.java:15: error: reference to m1 is ambiguous

t.m1(1,2);

both method m1(int,long) in First and method m1(long,int) in First match

1 error.
Example:

class First{

public void m1(int a)

System.out.println("no arg method");

public void m1(int... a)

System.out.println("one arg method");

public static void main(String arg[])

First t=new First();

t.m1(1,2);

In the above program,If you pass only one argument then always prefers method contain only one argument method
but not prefer var-arg method. Because var-arg method release in 1.5V.

Example:

class First{

public void m1(int a)

System.out.println("no arg method");

}
public void m1(int... a)

System.out.println("one arg method");

public static void main(String arg[])

First t=new First();

t.m1(1);

Example :

class Abc{

class Bca extends Abc{

class First{

public void m1(Abc a)

System.out.println("i am from Abc");

public void m1(Bca b)

System.out.println("i am from Abc");

public static void main(String arg[])

{
Abc t=new Abc();

Bca r=new Bca();

Abc s=new Bca();

First p=new First();

p.m1(t);

p.m1(r);

p.m1(s);

Constructor overloading:

In Java, we can overload constructors like methods. The constructor overloading can be defined as the concept
of having more than one constructor with different parameters so that every constructor can perform a different task.

Example:

class First{

First()

System.out.println("no-arg constructor");

First(int a)

System.out.println("argument constructor");

public static void main(String arg[])

First t=new First();

First t1=new First(1);

}
class First{

public void m1(Object a)

System.out.println("Hello");

public void m1(String b)

System.out.println("hii");

public static void main(String arg[])

First t=new First();

t.m1(null);

Output:

D:\9-10 Am>javac First.java

D:\9-10 Am>java First

Hii

In the above program we will get a output “hii” because null is default value for both Object and String class. Every
class is always child of Object class. In this type of situation always prefer child class only. So we get “hii”.
Example 2:

class First{

public void m1(StringBuffer a)

System.out.println("Hello");

public void m1(String b)

System.out.println("hii");

public static void main(String arg[])

First t=new First();

t.m1(null);

Output:

D:\9-10 Am>javac First.java

First.java:13: error: reference to m1 is ambiguous

t.m1(null);

both method m1(StringBuffer) in First and method m1(String) in First match

1 error

In the above program both String and StringBuffer default values are null and String and StringBuffer Childs of Object
class. So we get a ambiguity problem.

This Keyword

this:
Here can be a lot of usage of Java this keyword. In Java, this is a reference variable that refers to the current
object.

Usage of Java this keyword

Here is given the 6 usage of java this keyword.

this can be used to refer current class instance variable.

this can be used to invoke current class method (implicitly)

this() can be used to invoke current class constructor.

this can be passed as an argument in the method call.

this can be passed as argument in the constructor call.

this can be used to return the current class instance from the method.

this: to refer current class instance variable:

The keyword can be used to refer current class instance variable. If there is ambiguity between the instance variables
and parameters, this keyword resolves the problem of ambiguity.

Without this keyword:

Follow the example:

class First{

String name;

int roll;

First(String name,int roll)

name=name;

roll=roll;

public void display()

System.out.println("Name of the student:"+name);

System.out.println("Roll of the student:"+roll);

public static void main(String arg[])

First t=new First("ravi",98);


First p=new First("ramesh",87);

t.display();

p.display();

Output:

D:\9-10 Am>javac First.java

D:\9-10 Am>java First

Name of the student:null

Roll of the student:0

Name of the student:null

Roll of the student:0

With this keyword:

Example:

class First{

String name;

int roll;

First(String name,int roll)

this.name=name;

this.roll=roll;

public void display()

System.out.println("Name of the student:"+name);

System.out.println("Roll of the student:"+roll);

public static void main(String arg[])

{
First t=new First("ravi",98);

First p=new First("ramesh",87);

t.display();

p.display();

Output:

D:\9-10 Am>javac First.java

D:\9-10 Am>java First

Name of the student:ravi

Roll of the student:98

Name of the student:ramesh

Roll of the student: 87

Note:

If local variables(formal arguments) and instance variables are different, there is no need to use this keyword .

It isbetter approach to use meaningful names for variables. So we use same name for instance variables and
parameters in real time, and always use this keyword.

2. To invoke current class method:

Example:

class First{

public void m1()

System.out.println("I am from m1");

public void m2()

System.out.println("I am from m2");

this.m1();

}
public static void main(String arg[])

First t=new First();

t.m2();

this () : to invoke current class constructor:

Example:

class First{

First()

System.out.println("no arg constructor");

First(int a)

this();

System.out.println("arg constructor");

public static void main(String arg[])

First t=new First(1);

Note:
Call this() must be the first statement in the constructor. Otherwise we get a compile time error.

Example:

class First{

First()

System.out.println("no arg constructor");

First(int a)

System.out.println("arg constructor");

this();

public static void main(String arg[])

First t=new First(1);

D:\9-10 Am>javac First.java

First.java:10: error: call to this must be first statement in constructor this();

Overriding:

If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java (
Or) If a subclass provides the specific implementation of the method that has been declared by one of its parent class,
it is known as method overriding.
Usage of Java Method Overriding:

Method overriding is used to provide the specific implementation of a method which is already provided by its
superclass.

Method overriding is used for runtime polymorphism

Rules for Java Method Overriding

The method must have the same name as in the parent class

The method must have the same parameter as in the parent class.

There must be an IS-A relationship (inheritance).

Example:

Class Abc {

Public void m1()

System.out.println(“I am from Abc class”);

}
class Bca extends Abc {

Public void m1()

System.out.println(“I am, from Bca class”);

Class First {

Public static void main (string arg[]){

Bca t=new Bca();

t.m1();

}
Note:

Java Method overriding is mostly used in runtime Polymorphism .

We cant override main method.

Covariant Return Type:

The covariant return type specifies that the return type may vary in the same direction as the subclass.

Before Java5, it was not possible to override any method by changing the return type. But now, since Java5, it is
possible to override method by changing the return type if subclass overrides any method whose return type is Non-
Primitive but it changes its return type to subclass type. Let's take a simple example:

Advantages:

Covariant return type assists to stay away from the confusing type casts in the class hierarchy and makes the code
more usable, readable, and maintainable.

In the method overriding, the covariant return type provides the liberty to have more to the point return types.

Covariant return type helps in preventing the run-time ClassCastExceptions on returns.

Let's take an example to understand the advantages of the covariant return type.

Example:

class A{

public Object m1()

System.out.println("Hello world");

return null;

class B extends A{

public String m1()


{

System.out.println("Hello");

return null;

class First{

public static void main(String arg[])

B t=new B();

t.m1();

Access Modifiers in overriding:

If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive.

Public----protected---default----private

Example:

class A{

public void m1()

System.out.println("Hello world");

class B extends A{

void m1()

System.out.println("Hello");
}

class First{

public static void main(String arg[])

B t=new B();

t.m1();

Output:

D:\9-10 Am>javac First.java

First.java:10: error: m1() in B cannot override m1() in A

void m1()

attempting to assign weaker access privileges; was public

1 error

In the above program we will get a compile time error because public modifier can’t override to default. Because
weaker access privileges.

Examplle2:

class A{

void m1()

System.out.println("Hello world");

class B extends A{
public void m1()

System.out.println("Hello");

class First{

public static void main(String arg[])

B t=new B();

t.m1();

Output:

D:\9-10 Am>javac First.java

D:\9-10 Am>java First

Hello

Runtime Polymorphism in Java

Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved
at runtime rather than compile-time.

Example:

class Abc{

public void m1()


{

System.out.println("I am from Abc");

class Bca extends Abc{

public void m1()

System.out.println("I am from Bca");

class First{

public static void main(String... arg)

Abc t=new Abc();

t.m1();

Bca p=new Bca();

p.m1();

Abc r=new Bca();

r.m1();

In this example, we are creating two classes Abc and Bca. Bca class extends Abc class and overrides its m1() method.
We are calling the m1 method by the reference variable of Parent class. Since it refers to the subclass object and
subclass method overrides the Parent class method, the subclass method is invoked at runtime.

Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.

Upcasting:

If the reference variable of Parent class refers to the object of Child class, it is known as upcasting.

Example:

class Abc{

public void m1()


{

System.out.println("I am from Abc");

class Bca extends Abc{

public void m1()

System.out.println("I am from Bca");

class First{

public static void main(String... arg)

Abc t=new Abc();

t.m1();

Bca p=new Bca();

p.m1();

Abc r=new Bca();

r.m1();

Note: A method declare with the keyword final is known as the final method. Note that a final method cannot
be overridden.

In case override final method we get a compile time error.

Example:

class Abc{

public final void m1()

System.out.println("I am from Abc");

}
class Bca extends Abc{

public void m1()

System.out.println("I am from Bca");

class First{

public static void main(String... arg)

Bca p=new Bca();

p.m1();

Output:

D:\9-10 Am>javac First.java

First.java:8: error: m1() in Bca cannot override m1() in Abc

public void m1()

overridden method is final

1 error

Note:

we cannot override static methods because method overriding is based on dynamic binding at runtime and the
static methods are bonded using static binding at compile time. So, we cannot override static methods.

if we call a static method by using the parent class object, the original static method will be called from the parent
class.

Example:
class Abc{

public static void m1()

System.out.println("I am from Abc");

class Bca extends Abc{

public void m1()

System.out.println("I am from Bca");

class First{

public static void main(String... arg)

Bca p=new Bca();

p.m1();

Output:

D:\9-10 Am>javac First.java

First.java:8: error: m1() in Bca cannot override m1() in Abc

public void m1()

overridden method is static

1 error

If we call a static method by using the child class object, the static method of the child class will be called.
Example:

class Abc{

public void m1()

System.out.println("I am from Abc");

class Bca extends Abc{

public static void m1()

System.out.println("I am from Bca");

class First{

public static void main(String... arg)

Bca p=new Bca();

p.m1();

Output:

D:\9-10 Am>javac First.java

First.java:8: error: m1() in Bca cannot override m1() in Abc

public static void m1()

overriding method is static

1 error
Note: a private method cannot be overridden since it is not visible from any other class.

Example:

class Abc{

private void m1()

System.out.println("I am from Abc");

class Bca extends Abc{

void m1()

System.out.println("I am from Bca");

class First{

public static void main(String... arg)

Bca p=new Bca();

p.m1();

Output:

D:\9-10 Am>javac First.java

D:\9-10 Am>java First

I am from B
If you override private then it consider as a new method in child class.

you cannot override the private method in Java because it's bonded during compile time using static binding.

Note:

If a parent class contains abstract method you can override the method in child class.

Example:

abstract class Abc{

public abstract void m1();

class Bca extends Abc{

public void m1()

System.out.println("I am from Bca");

class First{

public static void main(String... arg)

Bca p=new Bca();

p.m1();

Output:

D:\9-10 Am>javac First.java

D:\9-10 Am>java First

I am from Bca

Static and dynamic binding

There are two types of binding


Static Binding (also known as Early Binding).

Dynamic Binding (also known as Late Binding).

Static Binding:

When type of the object is determined at compiled time(by the compiler), it is known as static binding.

Example:

class Abc{

public void m1()

System.out.println("I am from Abc");

class First{

public static void main(String... arg)

Abc p=new Abc();

p.m1();

Output:

Dynamic Binding:

When type of the object is determined at run-time, it is known as dynamic binding.

Example:

class Abc{

public void m1()

System.out.println("I am from Abc");

}
}

class Bca extends Abc{

public void m1()

System.out.println("I am from Bca");

class First{

public static void main(String... arg)

Abc p=new Bca();

p.m1();

Output:

D:\9-10 Am>javac First.java

D:\9-10 Am>java First

I am from Bca

Super:

The super keyword in Java is a reference variable which is used to refer immediate parent class object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly which is referred by
super reference variable.

Uses:

super can be used to refer immediate parent class instance variable.

super can be used to invoke immediate parent class method.

super() can be used to invoke immediate parent class constructor.

super can be used to refer immediate parent class instance variable.:

Example:

class A{
int a=20;

int b=30;

class First extends A{

public void disp()

System.out.println(super.a+super.b);

public static void main(String arg[])

First t=new First();

t.disp();

Output:

D:\Arr>javac First.java

D:\Arr>java First

50

super can be used to invoke immediate parent class method.

Example:

class A{

int a=20;

int b=30;

public void m1()

System.out.println(a+b);
}

class First extends A{

public void disp()

super.m1();

public static void main(String arg[])

First t=new First();

t.disp();

Output:

D:\Arr>javac First.java

D:\Arr>java First

50

super is used to invoke parent class constructor.

Example:

class Abc{

Abc()

System.out.println("I am from Abc class");

class First extends Abc{


First()

super();

System.out.println("i am from Bca class");

public static void main(String... arg)

First t=new First();

Output:

D:\9-10 Am>javac First.java

D:\9-10 Am>java First

I am from Abc class

i am from Bca class

Method hiding:

Static methods are bonded during compile time using types of reference variables not object. We know that static
methods are accessed by using the class name rather than an object. Note that the static method can be overloaded,
but cannot be overridden in Java.

Method hiding can be defined as, "if a subclass defines a static method with the same signature as a static method in
the super class, in such a case, the method in the subclass hides the one in the superclass." The mechanism is known
as method hiding. It happens because static methods are resolved at compile time.

The method hiding factors measure the invisibilities of methods in classes.

An attribute is called visible if it can be accessed by another class or object. An attribute should be hidden within a
class. They can be kept from being accessed by other objects by being declared private.

Ideally, the method hiding factor must have a large value.


Example:

class Abc{

public static void m1()

System.out.println("I am from Abc");

class First extends Abc{

public static void m1()

System.out.println("I am from First");

public static void main(String... ab)

First t=new First();

Abc p=new Abc();

Abc r=new First();

t.m1();

p.m1();

r.m1();

}
Output:

D:\9-10 Am>javac First.java

D:\9-10 Am>java First

I am from First

I am from Abc

I am from Abc

Difference between overloading and overriding:

Method overloading Method overriding


Method overloading is used to increase Method overriding is used to provide the
the readability of the program. specific implementation of the method
that is already provided by its super class.
Method overloading is performed within Method overriding occurs in two
class. classes that have IS-A (inheritance)
relationship.
In case of method overloading, parameter In case of method overriding, parameter
must be different. must be same.
Method overloading is the example Method overriding is the example of run
of compile time polymorphism. time polymorphism.
n java, method overloading can't be Return type must be same or covariant in
performed by changing return type of the method overriding.
method only. Return type can be same or
different in method overloading. But you
must have to change the parameter.

Abstraction

Abstraction is a process of hiding the implementation details and showing only functionality to the user.

There are two ways to achieve abstraction in java

Abstract class (0 to 100%)

Interface (100%)

Abstract class
A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods. It
needs to be extended and its method implemented. It cannot be instantiated.

An abstract class must be declared with an abstract keyword. Otherwise it consider as concrete class.

Example:

abstract class A{

We can’t create object for abstract class. if you create an object then we get compile time error.

Example:

abstract class Abc{

public void m1()

System.out.println("i am from m1");

public static void m2()

System.out.println("I am from m2");

class First extends Abc{

public static void main(String... arg)

Abc t=new Abc();

t.m1();
}

Output:

D:\9-10 Am>javac First.java

First.java:17: error: Abc is abstract; cannot be instantiated

Abc t=new Abc();

1 error

Abstract class contains static and non-static methods.

Example:

abstract class Abc{

public void m1()

System.out.println("i am from m1");

public static void m2()

System.out.println("I am from m2");

class First extends Abc{

public static void main(String... arg)

First t=new First();


t.m1();

Abc.m2();

Output:

D:\9-10 Am>javac First.java

D:\9-10 Am>java First

i am from m1

I am from m2

Abstract Method:

A method which is declared as abstract and does not have implementation is known as an abstract method.

abstract class Abc{

public abstract void m1();

class First{

public void m1()

System.out.println("hello world");

public static void main(String... ab)

First t=new First();

t.m1();

Output:
D:\9-10 Am>javac First.java

D:\9-10 Am>java First

hello world

If there is an abstract method in a class, that class must be abstract. Otherwise we will get compile time error.

If you are extending an abstract class that has an abstract method, you must either provide the implementation of the
method or make this class abstract.

It can have abstract and non-abstract methods.

Example:

abstract class Abc{

public abstract void m1();

public void m2()

System.out.println("I am from m2");

class First extends Abc{

public void m1()

System.out.println("I am from m1");

public static void main(String... ab)

First t=new First();

t.m1();

Output:
D:\9-10 Am>javac First.java

D:\9-10 Am>java First

I am from m1

I am from m2

An abstract class can have a data member, abstract method, method body (non-abstract method), constructor, and
even main() method.

It can have final methods which will force the subclass not to change the body of the method.

Interface

An interface in Java is a blueprint of a class. It has static constants and abstract methods.

In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method body.

Java Interface also represents the IS-A relationship.

It cannot be instantiated just like the abstract class.

Since Java 8, we can have default and static methods in an interface.

Since Java 9, we can have private methods in an interface.

Why using interface:

It is used to achieve abstraction.

By interface, we can support the functionality of multiple inheritance.

It can be used to achieve loose coupling.

An interface is declared by using the interface keyword. It provides total abstraction; means all the methods in an
interface are declared with the empty body, and all the fields are public, static and final by default. A class that
implements an interface must implement all the methods declared in the interface.

Interface abc{

Java compiler adds public and abstract keywords before the interface methods and adds public ,static and final
keywords before the varibles.
Example:

interface Abc{

public void m1();

class First implements Abc{

public void m1()

System.out.println("I am from m1");

public static void main(String arg[])

First t=new First();

t.m1();

OUTPUT:

D:\9-10 Am>javac First.java

D:\9-10 Am>java First

I am from m1

if a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as multiple
inheritance.
Example:

interface Abc{

public void m1();

interface Bca{

public void m2();

class First implements Abc,Bca{

public void m1()

System.out.println("I am from m1");

public void m2()

System.out.println("I am from m2");

public static void main(String arg[])

First t=new First();

t.m1();

t.m2();

Output:

D:\9-10 Am>javac First.java

D:\9-10 Am>java First

I am from m1

I am from m2
Note:

multiple inheritance is not supported in the case of class because of ambiguity. However, it is supported in case
of an interface because there is no ambiguity

A class implements an interface, but one interface extends another interface.

Example:

interface Abc{

public void m1();

interface Bca extends Abc{

public void m2();

class First implements Abc{

public void m1()

System.out.println("I am from m1");

public void m2()

System.out.println("I am from m2");

public static void main(String arg[])

First t=new First();

t.m1();

t.m2();

}
Output:

D:\9-10 Am>javac First.java

D:\9-10 Am>java First

I am from m1

I am from m2

Marker Interface:

An empty interface is called marker interface.

Or

An interface which has no member is known as a marker or tagged interface, for example, Serializable, Cloneable,
Remote, etc. They are used to provide some essential information to the JVM so that JVM may perform some useful
operation.

Example:

Interface abc{

Difference between and abstraction and interface:

Abstract class and interface both are used to achieve abstraction where we can declare the abstract methods.
Abstract class and interface both can't be instantiated.

But there are many differences between abstract class and interface that are given below.

class Interface

1) Abstract class can have abstract and Interface can have only abstract methods.
Since Java 8, it can have default and static
non Abstract -abstract methods. methods also.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.

3) Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.

4) Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.

5) The abstract keyword is used to The interface keyword is used to declare


declare abstract class. interface.

6) An abstract class can extend another An interface can extend another Java
Java class and implement multiple Java interface only.
interfaces.

7) An abstract class can be extended An interface can be implemented using


using keyword "extends". keyword "implements".

8) A Java abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default.

Example:

interface Abc{

public void m1();

public void m2();

abstract class Bca implements Abc{

public void m1()

System.out.println("I am from m1");

public abstract void m2();

}
class First extends Bca{

public void m2()

System.out.println("I am from m2");

public static void main(String arg[])

First t=new First();

t.m1();

t.m2();

Output:

D:\9-10 Am>javac First.java

D:\9-10 Am>java First

I am from m1

I am from m2

If you don’t know implementation you choose interface.

Partial implement class is called abstract class.

Fully implemented class is called concrete class.

Encapsulation:

A process of wrapping code and data together into a single unit.

The Java Bean class is the example of a fully encapsulated class.

Advantage of Encapsulation in Java

By providing only a setter or getter method, you can make the class read-only or write-only. In other words, you can
skip the getter or setter methods.
It provides you the control over the data. Suppose you want to set the value of id which should be greater than 100
only, you can write the logic inside the setter method. You can write the logic not to store the negative numbers in the
setter methods.

It is a way to achieve data hiding in Java because other class will not be able to access the data through the private
data members.

The encapsulate class is easy to test. So, it is better for unit testing.

The standard IDE's are providing the facility to generate the getters and setters. So, it is easy and fast to create an
encapsulated class in Java.

Example:

A java program.

Wrapper classes

The wrapper class in Java provides the mechanism to convert primitive into object and object into primitive.

Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and objects into primitives
automatically. The automatic conversion of primitive into an object is known as autoboxing and vice-versa unboxing.

hange the value in Method: Java supports only call by value. So, if we pass a primitive value, it will not change the
original value. But, if we convert the primitive value in an object, it will change the original value.

Serialization: We need to convert the objects into streams to perform the serialization. If we have a primitive value, we
can convert it in objects through the wrapper classes.

Synchronization: Java synchronization works with objects in Multithreading.

java.util package: The java.util package provides the utility classes to deal with objects.

Collection Framework: Java collection framework works with objects only. All classes of the collection framework
(ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque, etc.) deal with objects
only.

Primitive Type Wrapper class

boolean Boolean

char Character

byte Byte

short Short
int Integer

long Long

float Float

double Double

Autoboxing:

The automatic conversion of primitive data type into its corresponding wrapper class is known as autoboxing.

class First{

public static void main(String arg[])

int a=30;

Integer b=Integer.valueOf(a);

Integer c=a;

System.out.println(a+" "+b+" "+c);

Output:

D:\9-10 Am>javac First.java

D:\9-10 Am>java First

30 30 30

Unboxing:

The automatic conversion of wrapper type into its corresponding primitive type is known as unboxing.

Example:

class First{

public static void main(String arg[])

{
Integer a=new Integer(30);

int b=a;

System.out.println(a+" "+b );

Output:

D:\9-10 Am>javac First.java

D:\9-10 Am>java First

30 30

Packages

A java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form, built-in package and user-defined package.

There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

The package keyword is used to create a package in java.

Example:

package abc;

public class A{

public void main(String arg[])

System.out.println("Hello world");

to run java package program

D:\java>javac -d . A.java
D:\java>java abc.A

Hello world

The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The . represents the
current folder.

access package from another package

There are three ways to access the package from outside the package.

import package.*;

import package.classname;

fully qualified name.

Using packagename.*

f you use package.* then all the classes and interfaces of this package will be accessible but not subpackages.

The import keyword is used to make the classes and interface of another package accessible to the current package.

Example:

Using packagename.classname:

Example:

Using fully qualified name:

Example:

Note: If you import a package, subpackages will not be imported.

Subpackage:

Package inside the package is called the subpackage. It should be created to categorize the package further.

Note:

The standard of defining package is domain.company.package e.g. com.javatpoint.bean or org.sssit.dao.

There can be only one public class in a java source file and it must be saved by the public class name.

Static Import:

The static import feature of Java 5 facilitate the java programmer to access any static member of a class directly. There
is no need to qualify it by the class name.
Less coding is required if you have access any static member of a class oftenly.

If you overuse the static import feature, it makes the program unreadable and unmaintainable.

Example:

import static java.lang.System.*;

class B{

public static void main(String arg[])

out.println("hello world");

Output:

D:\java>javac B.java

D:\java>java B

hello world

Difference between import and static import

The import allows the java programmer to access classes of a package without package qualification whereas the static
import feature allows accessing the static members of a class without the class qualification. The import provides
accessibility to classes and interface whereas static import provides accessibility to static members of the class.

Access Modifiers:

There are two types of modifiers in Java: access modifiers and non-access modifiers.

There are four types of Java access modifiers:

Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class.

Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the
package. If you do not specify any access level, it will be the default.

Protected: The access level of a protected modifier is within the package and outside the package through child class. If
you do not make the child class, it cannot be accessed from outside the package.

Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class,
within the package and outside the package.
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient, etc. Here, we
are going to learn the access modifiers only.

Access within within outside package outside


Modifier class package by subclass only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

Programs for access modifiers

Inner classes:

Java inner class or nested class is a class that is declared inside the class or interface.

We use inner classes to logically group classes and interfaces in one place to be more readable and maintainable.

Advantage of Java inner classes

Nested classes represent a particular type of relationship that is it can access all the members (data members and
methods) of the outer class, including private.

Nested classes are used to develop more readable and maintainable code because it logically group classes and
interfaces in one place only.

Code Optimization: It requires less code to write.


Need of Java Inner class

Sometimes users need to program a class in such a way so that no other class can access it. Therefore, it would be
better if you include it within other classes.

There are two types of nested classes non-static and static nested classes. The non-static nested classes are also known
as inner classes.

Non-static nested class (inner class)

Member inner class (OR) Regular Inner classes

Anonymous inner class

Local inner class

Static nested class

Regular Inner classes:

A non-static class that is created inside a class but outside a method is called member inner class. It is also known as
a regular inner class. It can be declared with access modifiers like public, default, private, and protected.

The java compiler creates two class files in the case of the inner class. The class file name of the inner class is
"Outer$Inner". If you want to instantiate the inner class, you must have to create the instance of the outer class. In
such a case, an instance of inner class is created inside the instance of the outer class.

We can create access inner classes members in three ways:

Example-1:

class Second

public void m1()

System.out.println("i am from outer class");

class Abc

public void m2()

System.out.println("i am from inner class");

}
}

public static void main(String arg[])

Second t=new Second();

Abc p=t.new Abc();

p.m2();

t.m1();

Example-2:

class Second

public void m1()

System.out.println("i am from outer class");

class Abc

public void m2()

System.out.println("i am from inner class");

public static void main(String arg[])

new Second().new Abc().m2();

new Second().m1();

}
Example-3:

class Second

public void m1()

Abc p=new Abc();

p.m2();

class Abc

public void m2()

System.out.println("i am from inner class");

public static void main(String arg[])

Second t=new Second();

t.m1();

Note: in regular Inner classes can’t support static declaration.

Example:

class Second
{

class Abc

public static void m2()

System.out.println("i am from inner class");

public static void main(String arg[])

Second t=new Second();

Abc p=t.new Abc();

t.m2();

Note:

We can access static content from outer class but we can’t declare static content in inner classes.

Example:

class Second

{ int a=10;

static int b=20;

class Abc

public void m2()

System.out.println(a);

System.out.println(b);

}
}

public static void main(String arg[])

Second t=new Second();

Abc p=t.new Abc();

p.m2();

Output:

D:\ABCD>javac Second.java

D:\ABCD>java Second

10

20

Note: if you declare static content in regular inner classes we will get a compile time error.

Example:

class Second

{ int a=10;

static int b=20;

class Abc

static int c=40;

public void m2()

System.out.println(a);

System.out.println(b);

System.out.println(c);

}
}

public static void main(String arg[])

Second t=new Second();

Abc p=t.new Abc();

p.m2();

Output:

D:\ABCD>javac Second.java

Second.java:6: error: Illegal static declaration in inner class Second.Abc

static int c=40;

modifier 'static' is only allowed in constant variable declarations

1 error

Example-5:

class Second{

class Abc{

public static void main(String arg[])

Output:

D:\ABCD>javac Second.java

Second.java:3: error: Illegal static declaration in inner class Second.Abc


public static void main(String arg[])

modifier 'static' is only allowed in constant variable declarations

1 error

Example:

class Second

class Abc

class Cab{

public void m3()

System.out.println("hello");

public void m2()

System.out.println("hii");

public static void main(String arg[])

Second t=new Second();

Second.Abc p=t.new Abc();

Second.Abc.Cab s=p.new Cab();

s.m3();

}
}

Method Local Inner classes:

A class i.e., created inside a method, is called local inner class in java. A local inner class has access to fields of the class
enclosing it as well as the fields of the block that it is defined within. These classes, however, can access the variables
or parameters of the block that encloses it only if they are declared as final or are effectively final. The purpose of
nested classes is to group classes that belong together, which makes your code more readable and maintainable.

Example:

class Second

public void m1()

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

class Bca{

public void m2()

System.out.println("hello world");

Bca p=new Bca();

p.m2();

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

p.m2();

;;;;;;;;;;;;;;;;;;;;;;;;;;

p.m2();

public static void main(String arg[])


{

Second t=new Second();

t.m1();

*if a local method is non-static then we can access static and not static members of outer class.

Example:

class Second

int a=20;

static int b=30;

public void m1()

class Bca{

public void m2()

System.out.println(a);

System.out.println(b);

Bca p=new Bca();

p.m2();

public static void main(String arg[])

Second t=new Second();

t.m1();
}

*if a local method is static then we can’t access static and not static members of outer class.

Example:

class Second

int a=20;

static int b=30;

public static void m1()

class Bca{

public void m2()

System.out.println(a);

System.out.println(b);

Bca p=new Bca();

p.m2();

public static void main(String arg[])

Second t=new Second();

t.m1();

}
Output:

D:\ABCD>javac Second.java

Second.java:10: error: non-static variable a cannot be referenced from a static context

System.out.println(a);

1 error

Note:

Local inner class cannot access non-final local variable till JDK 1.7. Since JDK 1.8, it is possible to access the non-final
local variable in the local inner class.

class Second

public static void m1()

final int a=20;

class Bca{

public void m2()

System.out.println(a);

Bca p=new Bca();

p.m2();

public static void main(String arg[])

Second t=new Second();

t.m1();
}

Output:

D:\ABCD>javac -source 1.4 Second.java

D:\ABCD>java Second

20

Anonymous inner class:

In simple words, a class that has no name is known as an anonymous inner class in Java. It should be used if you
have to override a method of class or interface. Java Anonymous inner class can be created in two ways:

Class (may be abstract or concrete).

Interface

Java anonymous inner class is an inner class without a name and for which only a single object is created.

Example:

class Second

public void popcorn()

System.out.println("salt");

public static void main(String arg[])

Second c1=new Second(){

public void popcorn()

System.out.println("sweet");
}

};

c1.popcorn();

Second c2=new Second();

c2.popcorn();

Internal working of above code:

A class is created, but its name is decided by the compiler, which extends the Person class and provides the
implementation of the popcorn() method.

An object of the Anonymous class is created that is referred to by 'p,' a reference variable of Person type.

Anonymous inner class example using interface:

Example:

interface abc

public void popcorn();

class Second{

public static void main(String arg[])

abc c1=new abc(){

public void popcorn()

System.out.println("sweet");

};

c1.popcorn();

}
Output:

D:\ABCD>javac Second.java

D:\ABCD>java Second

sweet

static nested class:

A static class is a class that is created inside a class, is called a static nested class in Java. It cannot access non-
static data members and methods. It can be accessed by outer class name.

It can access static data members of the outer class, including private.

The static nested class cannot access non-static (instance) data members or

Example:

class Second{

static class Abc{

public void m1()

System.out.println("i am from m1");

public void m2()

System.out.println("i am from m2");

public static void main(String arg[])

Second.Abc t=new Second.Abc();

t.m1();

Second p=new Second();


p.m2();

Output:

D:\ABCD>javac Second.java

D:\ABCD>java Second

i am from m1

i am from m2

If you have the static member inside the static nested class, you don't need to create an instance of the static nested
class.

Example:

class Second{

static class Abc{

public static void m1()

System.out.println("i am from m1");

public static void main(String arg[])

Second.Abc.m1();

Output:

D:\ABCD>javac Second.java

D:\ABCD>java Second

i am from m1

Example:
class Second{

static class Abc{

public static void main(String arg[])

System.out.println("i am from Abc");

public static void main(String arg[])

System.out.println("i am from Second");

Output:

D:\ABCD>javac Second.java

D:\ABCD>java Second

i am from Second

D:\ABCD>java Second$Abc

i am from Abc

Nested Interfaces:

Example:

interface Abc

public void m1();

interface Bca

public void m2();

}
class Third implements Abc{

public void m1()

System.out.println("i am from m1");

class First implements Abc.Bca{

public void m2()

System.out.println("i am from m2");

class Second

public static void main(String arg[])

First t=new First();

t.m2();

Third p=new Third();

p.m1();

Output:

D:\ABCD>javac Second.java

D:\ABCD>java Second

i am from m2

i am from m1

Exception Handling:

Any unwanted or un-expected event disturb the normal flow of the program is called Exception.
Ex:

1)In real time if one person going to the office at the time 9:00 Am he started in house 08:30 Am on the way the tire is
punctured we face a problem called type exception.

2)sleeping Exception, FileNotFoundException

Purpose of Exception Handling

1)Grace full termination of the program. Grace full means we should not miss anything.

2)it is highly to recommended to handle exceptions and the main object of exception Handling is gracefull termination
of the program.

Ex: typing in computer

What is Exception Handling

Defining alternative way to continue rest of the program.

Exception handling doesn’t mean repairing an exception we have to provide alternative way to continue rest of the
program normally, that concept is called exception handling.

For example our program requirement is to read the data from remote file locating at London at runtime if London file
not available to our program should not be terminated up normally, we have to provide some local file to continue rest
of the program normally the way of defining is nothing but exception handling.

Ex:

try

read data file from remote file

locating at London

catch

use local file & continue

rest of the program normally

Runtime stack Mechanism:

For every thread JVM will create a run time stack each and every method performed by the thread will be store in the
corresponding stack.

Each entry in the stack is called stack frame or Activation record.

After completing every method call the corresponding entry from stack called will be removed.

After completing all method calls the stack will become empty under the empty stack will be destroy by JVM just
before terminating in the thread.
Ex:

class Test

public static void main(String[] args)

first ();

public static void first()

Second();

public static void second()

System.out.println(“Hello”);

Inside a method if any exception occurs that method in which it is raised is responsible to create exception object by
including following information.

Name of exception
Description of exception
Location at which exception occurs stack traces
After create exception object method hand over that object to the jvm
JVM will check whether the method contains only exception if a method doesn’t contain exception handle code the
JVM terminates method and removes corresponding entry from the stack
Then JVM identifies call method and checks whether caller method doesn’t contains any handling code or not, if the
caller method doesn’t contains handling code to JVM terminates also abnormally and removes corresponding entry
from the stack. This process will be continued until main method and if the main method does not contain handling
code to JVM terminates main method abnormally and removes corresponding entry from the stack then JVM
handovers responsibility of exception handling to default exception handles which is the part of JVM default exception
handler print exception information in the following format and terminate program abnormally.
Exception in the thread “main”name of exception: description stackTrace
Note:in a program if atleast one methods terminates abnormally then the program termination is abnormal
termination.
If all methods terminated abnormally then any program termination is normal termination.

Ex:
class Test

public static void main(String[] args)

first ();

public static void first()

second();

public static void second()

System.out.println(10/0);

Error: exception in the main thread “main” Arithmetic Expression

At test.second();

At test.first();

At test.main();

Ex:

class Test

public static void main(String[] args)

first ();

public static void first()

second();

System.out.println(10/0);
}

public static void second()

System.out.println(“Hi”);

o/p:Hello

Exception thread “main” java.lang.io.Arithmetic

at test.first();

at test.main();

Exception Hierarchy

Throwable class acts as root for java exception Hierarchy.

Throwable class defines two child classes.

1) Exception
2) Error
Exception:

Most of the times exceptions are caused by our program under these are recoverable. For example if our program
requirement to read data from remote file Locating at London. At run remote file not available then we will get run
time exception file not found exception if file not found exception occurs we can provide local file and continues rest
of the program normally.

Ex:

try

read data file from remote

File locating at London

catch(file not found Exception e)

use local file & continue

rest of the program normally

Error:most of the times

Errors are not caused by our program and these are due to lack of system resources. Errors are non-recoverable
For example if out of memory error occurs being a programmer we can’t do anything and program will be terminated
abnormally.

System admin or server admin is responsible to increase heap memory

Difference between Exception and error?

Both exceptions and errors are the subclasses of a throwable class. The error implies a program that mostly arises due
to the shortage of the system resources on the other hand the exception occurs during runtime and compile time.

Abnormal termination and normal termination

If the program runs currently returns zero then go on to the next step (normal termination)

If the program detects a problem and returns a non-zero value then abort the next step(abnormal termination)

Checked and Unchecked Exception:

Note1:

Both exceptions are occurred in runtime only but not in compile time. In compile time only occurs syntatical errors.

The exception which are checked by compiler for smooth execution of the program are called checked exceptions

Ex:10th public examination:Hallticket missing exception, pen not working exception, file not found exception…

In our program if there is a chance of rising checked exception the compulsory we should handle that checked
exception(either by try catch or throws keyword) otherwise we will get compile time error.

The exceptions which are not checked by compiler whether program handling or not such type of exceptions are called
unchecked exceptions.

Ex:Arithmetic exception, bomb blast exception…

Note:

Run exception and its child classes, error and its child classes are unchecked except these are remaining checked

Fully are partially checked for only unchecked exception

Fully checked
Ex: in airport both we checked

Partially checked
Ex: shopping mall checking in mother and kid

A checked exception is said to be fully checked if and only if all its child classes are checked.

Ex: io exception, interrupted exception.

A checked exception is said to be partially checked when some of child classes are checked.

Ex:exception, throwable

Note: the only possible partial checked exceptions in java are exception throwable.

Describe the behaviour of the following exception


io exception - fully checked

Runtime - unchecked

Interrupted - checked(fully)

Error - unchecked

Throwable - checked(partially)

Arithmetic - unchecked

Null pointer - unchecked

Exception - checked(partially)

File not found - checked(fully)

Customized exception handling

Customized exception handling by using try, catch

The code which rise the exception is called risky code.


Without catch

Ex:

class test

Public static void main(String[] args)

System.out.println(“stm1”);

System.out.println(10/0);

o/p:stmt1

At & 1 by zero

With catch

class test

public static void main(String[] args)

{
System.out.println(“stmt1”);

try

System.out.println(10/0);

catch

System.out.println(10/0);

System.out.println(“stmt3”);

o/p:

stmt1

Stmt3

Ex:

try

Risky code

catch(Exception e)

Handling code

it is higly recommended to handle exception. The code which may rise an exception is called risky code and we have to
define that code inside try block and corresponding handling code we have to define inside catch block.

Ex:

try

stmt1;

Stmt2;

Stmt3;
catch(x e)

stmt4;

Stmt5;

Case1:-

if there is no exception then stmt1, stmt2, stmt3, stmt4, stmt5 are executed.

Case2:-

If an exception is raised at stmt2 corresponding catch block matched 1,4,5 normal termination.

Case3:-

If an exception raised at stmt2 and corresponding catch block not matched only then will be executed

Case4:-

if an exception raised at stmt4 or stmt5 then it is always abnormal termination.

Methods to print Exception Information:

Throwable class defines the following methods to print exception information

Method Printable format

printStackTrace() None of exception:Description StackTrace

toString() Name of exception:Description

getMessage() Description

Ex:

class Test

public static void main(String[] args)

try

{
System.out.println(10/0);

catch(ArithmeticException e)

e.printStackTrace();

System.out.println(e);

System.out.println(e.toString());

System.out.println(e.getMessage());

Note:

Internally default exception handler will be printStackTrace method to print exception information to the console

try with multiple catch blocks

The way of handling on exception is varied from exception to exception hence for every exception type it is highly
recommended to take separate catch block i,e

try with multiple catch blocks always possible and recommended to use

Ex:

try

Risky code

catch (Exception e)

perform

Ex:

try

Riskycode
}

Catch(ArithmeticException e)

perform

catch( SQLException e)

use mySQL instead of oracle database

Catch(FileNotFoundException e)

use local file instead of remote file

catch(Exception e)

default exception handler

Ex:

try

Risky code

catch(ArithmeticException e)

o/p:exception u.l.AE has already caught

Ex:

try

{
Risky code

Catch(ArithmeticException e)

Catch(Exception e)

if try with multiple catch blocks present the order of catch blocks is important we have to take child first under than
parent otherwise we will get compile time error saying exception has already caught.

Ex:

try

Risky code

catch(ArithmeticException e)

catch(ArithmeticException e)

o/p:Exception u..l.AE has already caught

final:

final is the modifier applicable for classes methods and variables. If a class declare as final then we can’t extend the
class i,e we can’t create child class for that class i,e inheritance is not possible for final class.

If a method is final then we can’t overide that method in the child class.

If a variable declared as final then we can’t perform reassignment for that variable.

finally:

finally is a block always associated with try catch block to maintain clean up code.

Ex:
try

Risky code

catch(Exception e)

Handling code

Finally

cleanup code

to speciality of finally block is it will be executed always irrespective whether exception is rised or not rised and
whether handled or not handled.

finalize:

finalize() is a method always invoked by garbage collector just before destroying an object to perform clean up
activities once finalize() completes immediately garbage collector destroys that object.

Note:finally block is responsible to perform clean up activities related to try block i,e whatever resources we opened at
the part of try block will be closed inside the finally block.

Where as finalize() is responsible to perform clean up activities related to object. i,e whatever resources
associated with object will be deallocated before destroying an object by using fianlize method.

Various possible combinations of try, catch, finally:

In try, catch, finally order is important.


Whenever we are writing try compulsory we should write either catch or finally otherwise we will get compile time
error. i,e try without catch or finally is invalid.
whenever we are writing catch block compulsory try block must be required. i,e catch without try is invalid.
whenever we are writing finally block compulsory we should write try block. Finally block without try is invalid.
inside try, catch and finally blocks we can declare try, catch and finally blocks. i,e nesting of try, catch, finally is allowed.
for try, catch and finally block {} ara mandatory.
Throw keyword:

Sometime we can create a exception object explicitly we can handover to the jvm manually for this we have to use the
throw keyword.

`throw new ArithmeticException(“% by zero”);


Handover creation creation of ArithmeticException object explicitly

Exception object

Manually

Hence the main object of throw keyword is to handover our created exception object to the jvm manually.

Hence the result of the following two programs exactly same

Ex:

class Test

public static void main(String[] args)

System.out.println(10/0);

Exception in the thread “main” j.v.AE by zero at Test.main()

In this case main method is responsible to create exception object handover to the jvm

Ex:

class Test

public static void main(String[] args)

throw new ArithmeticException(“/by zero”);

in this case programmer creating exception object explicitly and handover to the jvm manually.

Note:

best use of throw keyword is used for user define exceptions or customized exception.

Case1:

if throw e refers to null then we will get null pointer exception.

Ex:

class Test

{
static AE=new AE();

public static void main(String[] args)

throw e;

Runtime error:A.E

Ex:

class Test

static ArithmeticException e;

public static void main(String[] args)

throw e;

NullPointerException

Case2:

After throw statement we are not allowed to write any stmt directly otherwise we will get compile time error
unreachable stmt.

Ex:

class Test

public static void main(String[] args)

System.out.println(10/0);

System.out.println(“Hello”);

Reason:ArithmeticException/by zero
Ex:

class Test

public static void main(String[] args)

throw new ArithmeticException(%by zero)

System.out.println(“Hello”);

Reason:unreachable stmt

Case3:

we can use throw keyword only for throwable types. If you are trying to use for normal java objects we will get compile
time error saying incompatible type.

Ex:

class Test

public static void main(String[] args)

throw new Test();

CE:-incompatible type for use:test

Ex:

class test

public static void main(String[] args)


{

throw new Test();

Throws

In our program if there is a possibility of rising checked exception then compulsory we should handle the checked
exception otherwise we will get compile time error saying unreported exception **%; must be caught or declare to be
thrown

Ex:1

import java.io.*;

class Test

public static void main(String[] args)

print writer pw=new print writer(“abc.+ed”);

pw.println(“Hello”);

o/p: unreported exception java.io.fileNotFoundException must be caught or declare to be thrown

Ex2:

class Test

public static void main(String[] args)

try

Thread.sleep(1000);

Catch(FileNotFoundException e)
{

Ex:

class Test

public static void main(String[] args)

Thread.sleep(1000);

We can use throw keyword to deligate responsibility of exception handling to the caller (it may be another method or
jvm) then caller method is responsible to handle that exception

Ex:

class Test

public static void main(Stringargs[])throws InteruptedException

Thread.sleep(1000);

throws keyword required only for checked exceptions and usage of throws keyword for unchecked exceptions there is
no use of impact.
throws required only to convince compiler and usage of throws keyword doesn’t prevent abnormal termination of
program.
Ex:

class Test

public static void main(String[] args)throws it

dostuff();
}

public static void dostuff() throws it

domorestuff();

public static void domorestuff() it

Thread.sleep(1000);

if you write throws keyword then we get error in the compile time error

unreported exception java.io.IE;

must be caught or declare to be throws

In the above program if you remove atleast one throws stmt then the code won’t compile.

Case1:

we can use throws keyword for methods and constructors but not for classes.

Ex:

class Test throwsException

Test()throwsException

public void m1() throwsException

Case2:

we can use throws keyword for only for throwable types.if you are trying to use for normal java classes then we will
get compile time error saying incompatible types.
Ex:

class Test

public void m1()throws Test

ex:incompatible types

found:Test require

Ex:

class Test extends RuntimeException

public void m1()throws Test

Ex:

class Test

public static void main(String[] args)

throw new Exception();

CE:unreported

Ex:

class Test

public static void main(String[] args)

throw new Error();


}

RE:Exception in thread “main” error at Test.main();

Exception handling keyword summary:

Try- to maintain risky code.


Catch-to maintain exception handling code.
Finally-to maintain cleanup code.
throw-to handover usedefine exception to the jvm manually.
throw on-to deligate responsibility of exception handling to the caller.
Various possible compile time errors in exception handling:

unreported exception xxx; must be caught or declared to be thrown.


Exception xxx has already been caught
Exception xxx is never thrown in body corresponding try stmt.
Unreachable stmt.
Incompatible types
found:test

required:java.lang.throwable

try without catch or finally


catch without try
finally without try
Customized or user define Exceptions:

sometimes to meet program requirements we can define our own exceptions such type of exceptions are called
customized exceptions or user define exceptions.

Ex:TooFoundException

TooOldException

InsufficientFundsException

class TooFound extends RuntimeException

TooFoundException(String s)

}
class TooOldException extends RuntimeException

TooOldException(String s)

super(s);

class customException

public static void main(String[] args)

int age=Integer.parseint(args[0])

if(age>60)

throw new TooYoungException(“please wait sometime”);

else if(age<14)

throw newTooOldException(“please wait sometime”);

else

System.out.println(“wait details send to our mail”);

Note:

throw keyword is best suitable for user define or customized exceptions but not for predefine exceptions.
It is highly recommended to define customized exceptions as unchecked. i,e we have to extends runtime exceptions
but not exception.
Ex:

import java.io.*;

import java.io.util*;

class Abc

public static void main(String[] args)

int age;

Scanner p=new Scanner(System.in);

System.out.println(“Enter age”);

age=p.nextInt();

if(age>18)

System.out.println(“your eligible”);

else

throw new RuntimeException(“wait for sometime”);

Multithreading
Information about multithreading:-

The earlier days the computer’s memory is occupied only one program after completion of one program it is possible to
execute another program is called uni programming.

Whenever one program execution is completed then only second program execution will be started such type of
execution is called co-operative execution, this execution we are having lot of disadvantages.

Most of the times memory will be wasted.

CPU utilization will be reduced because only program allow executing at a time.

The program queue is developed on the basis co operative execution

To overcome above problem a new programming style will be introduced is called multiprogramming.

Multiprogramming means executing the more than one program at a time.

All these programs are controlled by the CPU scheduler.

CPU scheduler will allocate a particular time period for each and every program.

Executing several programs simultaneously is called multiprogramming.

In multiprogramming a program can be entered in different states.

Ready state.

Running state.

Waiting state.

Multiprogramming mainly focuses on the number of programs.

Advantages of multiprogramming:-

The main advantage of multithreading is to provide simultaneous execution of two or more parts of a application to
improve the CPU utilization.

CPU utilization will be increased.

Execution speed will be increased and response time will be decreased.

CPU resources are not wasted.

Multitasking

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU.
Multitasking can be achieved in two ways:

Process-based Multitasking (Multiprocessing)

Thread-based Multitasking (Multithreading)

Process-based Multitasking :
Executing multiple tasks executing simultaneously, where each thread independent from one to another is called
process based multitasking.

Ex: Operating system.

Thread-based Multitasking:

Executing multiple tasks executing simultaneously, where each thread dependent from one to another is called
process based multitasking.

Ex: Java program

`Thread:-

Thread is nothing but separate path of sequential execution.

The independent execution technical name is called thread.

Whenever different parts of the program executed simultaneously that each and every part is called thread.

The thread is light weight process because whenever we are creating thread it is not occupying the separate memory it
uses the same memory. Whenever the memory is shared means it is not consuming more memory.

Advantages of multi-threading:

The main advantage of multi-tasking id perform will be improved.

Weather it is process based or thread based the main objective of multitasking is to reduce response time of the
system and to improve performance.

The main important of the application area of multithreading are develop multimedia graphics, to develop animations,
to develop video games, to develop webservers and application severs etc.

When compared with old languages developing multithreaded applications in java is very easy because java provides in
built support for multithreading with rich Api.

Responsiveness.

Resource Sharing.

Economy.

Better Communication.

Utilization of multiprocessor architecture.

Minimized system resource usage.

Disadvantages of Multithreading:

It needs more careful synchronization.

It can consume a large space of stocks of blocked threads.

It needs support for thread or process.


If a parent process has several threads for proper process functioning, the child processes should also be
multithreaded because they may be required.

It imposes context switching overhead.

without Multithreading:

class A{

public void m1()

for(int i=0;i<10;i++)

System.out.println("hello");

class Second

public static void main(String arg[])

A t=new A();

t.m1();

for(int i=0;i<10;i++)

System.out.println("hii");

With multithreading:

class A extends Thread{

public void run()

for(int i=0;i<10;i++)

{
System.out.println("hello");

class Second

public static void main(String arg[])

A t=new A();

t.start();

for(int i=0;i<10;i++)

System.out.println("hii");

Thread in java:

A thread is a lightweight sub process, the smallest unit of processing. It is a separate path of execution. threads are
independent. If there occurs exception in one thread, it doesn't affect other threads. It uses a shared memory area.

How to create a thread in Java:

there are two ways to create a thread:

By extending Thread class

By implementing Runnable interface.

Thread class:

Thread class provide constructors and methods to create and perform operations on a thread. Thread class extend
Object class and implements Runnable interface.

By extending Thread class:


Example:

class A extends Thread{

public void run()

for(int i=0;i<10;i++)

System.out.println("hello");

class Second

public static void main(String arg[])

A t=new A();

t.start();

for(int i=0;i<10;i++)

System.out.println("hii");

Thread Scheduler:-

Thread scheduler is a part of the JVM. It decides thread execution.

Thread scheduler is a mental patient we are unable to predict exact behaviour of Thread Scheduler it is JVM vendor
dependent.

Thread Scheduler mainly uses two algorithms to decide Thread execution.

Premptive algorithm.
Time slicing algorithm.

We can’t expect exact behavior of the thread scheduler it is JVM vendor dependent. So we can’tsay expect output of
the multithreaded examples we can say the possible outputs.

Preemptive scheduling:-

In this highest priority task is executed first after this task enters into waiting state or dead state then only another
higher priority task come to existence.

Time Slicing Scheduling:-

A task is executed predefined slice of time and then return pool of ready tasks. The scheduler determines which task is
executed based on the priority and other factors.

Life cycle stages are:-

New

Ready

Running state

Blocked / waiting / non-running mode

Dead state

New :- MyThread t=new MyThread();

Ready :- t.start()

Running state:- If thread scheduler allocates CPU for particular thread. Thread goes to running state The Thread is
running state means the run() is executed.

Blocked State:-

If the running thread got interrupted of goes to sleeping state at that moment it goes to the blocked state.

Dead State:-If the business logic of the project is completed means run() over thread goes dead state.

Difference between t.start() and t.run():-

In the case of t.start(), Thread class start() is executed a new thread will be created that is responsible for the
execution of run() method.

But in the case of t.run() method, no new thread will be created and the run() is executed like a normal method
call by the main thread.
Note :- Here we are not overriding the run() method so thread class run method is executed which is having empty
implementation so we are not getting any output.

Note :- If we are overriding start() method then JVM is executes override start() method at this situation we are not
giving chance to the thread class start() hence n new thread will be created only one thread is available the name of
that thread is main thread.

class A implements Runnable{

public void run()

for(int i=0;i<10;i++)

System.out.println("hello");

class Second

public static void main(String arg[])

A p=new A();

Thread t=new Thread(p);

t.start();

for(int i=0;i<10;i++)

System.out.println("hii");

Getting and setting names of Thread:-

Every Thread in java having name

default name of the main thread is main


default name of user created threads starts from Thread-0.

t1 -- Thread-0

t2 -- Thread-1

t3 -- Thread-2

To set the name use setName() & to get the name use getName(),

Public final String getName()

Public final void setName(String name)

Example:-

class A extends Thread{

public void run()

for(int i=0;i<10;i++)

System.out.println("hello");

class Second

public static void main(String arg[])

A t=new A();

t.start();

t.setName("suresh");

Thread.currentThread().setName("hari");

System.out.println(t.getName());

System.out.println(Thread.currentThread().getName());

for(int i=0;i<10;i++)

{
System.out.println("hii");

Thread Priorities:-

Every Thread in java has some property. It may be default priority provided be the JVM or customized priority
provided by the programmer.

The valid range of thread priorities is 1 – 10. Where one is lowest priority and 10 is highest priority.

The default priority of main thread is 5. The priority of child thread is inherited from the parent.

Thread defines the following constants to represent some standard priorities.

Thread Scheduler will use priorities while allocating processor the thread which is having highest priority will get chance
first and the thread which is having low priority.

If two threads having the same priority then we can’t expect exact execution order it depends upon Thread Scheduler.

The thread which is having low priority has to wait until completion of high priority threads.

Three constant values for the thread priority.

MIN_PRIORITY = 1

NORM_PRIORITY = 5

MAX_PRIORITY = 10

Thread class defines the following methods to get and set priority of a Thread.

Public final int getPriority()

Public final void setPriority(int priority)

Here ‘priority’ indicates a number which is in the allowed range of 1 – 10. Otherwise we will get Runtime exception
saying “IllegalArgumentException”.

Thread priority decide when to switch from one running thread to another this process is called context switching.

class A extends Thread{

public void run()

for(int i=0;i<10;i++)
{

System.out.println("hello");

class Second

public static void main(String arg[])

A t=new A();

t.start();

t.setPriority(7);

System.out.println(t.getPriority());

System.out.println(Thread.currentThread().getPriority());

for(int i=0;i<10;i++)

System.out.println("hii");

Java.lang.Thread.yield():-

Yield() method causes to pause current executing Thread for giving the chance for waitingthreads of same
priority.

If there are no waiting threads or all threads are having low priority then the same thread willcontinue its execution
once again.

Syntax:-

Public static native void yield();

Example:

class MyThread extends Thread


{

public void run()

for(int i=0;i<10;i++)

Thread.yield();

System.out.println("child thread");

class ThreadYieldDemo

public static void main(String[] args)

MyThread t1=new MyThread(); t1.start();

for(int i=0;i<10;i++)

System.out.println("main thread");

Java.lang.Thread.join(-,-)method:-

Join method allows one thread to wait for the completion of another thread.

t.join(); ---> here t is a Thread Object whose thread is currently running.

Join() is used to stop the execution of the thread until completion of some other Thread.

If a t1 thread is executed t2.join() at that situation t1 must wait until completion of the t2 thread.

public final void join()throws InterruptedExcetion

Public final void join(long ms)throws InterruptedException

Public final void join(long ms, int ns)throws InterruptedException

Methods of Thread class:-


class MyThread extends Thread

public void run()

for (int i=0;i<5;i++)

Try

Thread.sleep(2000);

catch(InterruptedException e)

e.printStackTrace();

System.out.println(i);

class ThreadDemo

public static void main(String[] args)

MyThread t1=new MyThread();

MyThread t2=new MyThread();

MyThread t3=new MyThread(); t1.start();

try

t1.join();

catch (InterruptedException ie)


{

ie.printStackTrace();

t2.start();

Java.lang.Thread.Interrupted():-

A thread can interrupt another sleeping or waiting thread. But one thread is able to interrupted only another
sleeping or waiting thread.

To interrupt a thread use Thread class interrupt() method.

Public void interrupt()

Effect of interrupt() method call:-

class MyThread extends Thread

{ public void run()

{ try

{ for (int i=0;i<10;i++ )

System.out.println("i am sleeping ");

Thread.sleep(5000);

catch (InterruptedException ie)

System.out.println("i got interupted by interrupt() call");

class ThreadDemo

{ public static void main(String[] args)

MyThread t=new MyThread();


t.start();

t.interrupt();

No effect of interrupt() call:-

class MyThread extends Thread

public void run()

for (int i=0;i<10;i++ )

System.out.println("i am sleeping ");

class ThreadDemo

public static void main(String[] args)

MyThread t=new MyThread();

t.start();

t.interrupt();

NOTE:- The interrupt() is effected whenever our thread enters into waiting state or sleeping state and if the our thread
doesn’t enters into the waiting/sleeping state interrupted call will be wasted.

Shutdown Hook:-

Shutdown hook used to perform cleanup activities when JVM shutdown normally or abnormally.

Clean-up activities like

Resource release
Database closing

Sending alert message

So if you want to execute some code before JVM shutdown use shutdown hook

The JVM will be shutdown in fallowing cases.

When you typed ctrl+C

When we used System.exit(int)

When the system is shutdown ……etc

To add the shutdown hook to JVM use addShutdownHook(obj) method of Runtime Class.

public void addShutdownHook(java.lang.Thread);

To remove the shutdown hook from JVM use removeShutdownHook(obj) method of Runtime Class.

public boolean removeShutdownHook(java.lang.Thread);

To get the Runtime class object use static factory method getRuntime() & this method present in Runtime class

Runtime r = Runtime.getRuntime();

Factory method:- one java class method is able to return same class object or different class object is called factory
method.

Example :-

class MyThread extends Thread

public void run()

System.out.println("shoutdown hook");

class ThreadDemo

{ public static void main(String[] args)throws InterruptedException

MyThread t = new MyThread();


Runtime.getRuntime();

r.addShutdownHook(t);

for (int i=0;i<10 ;i++)

System.out.println("main thread is running"); Thread.sleep(3000);

D:\DP>java ThreadDemo main thread is running main thread is running main thread is running shoutdown hook

while running Main thread press Ctrl+C then hook thread will be executed.

Synchronization:

Synchronized keyword is the modifier applicable only for methods and blocks but not for classes and variable.

If multiple threads are trying to operate simultaneously on the same java object then there may be chance of data
inconsistency problem.

To overcome this problem we should go for synchronized keyword. if a method or block declared as synchronized then
at a time only one thread is allowed to execute. That method or block on the given object so that data inconsistence
problem will be resolved.

The main advantage of synchronized keyword is we can resolve data inconsistence problems but main disadvantage of
synchronized keyword is increase waiting of the time of threads and creates a performance problems. Hence if there is
no specific requirements there it is not recommended to use synchronized keyword.

Internally synchronization is implemented by using lock. Every object in java has a unique lock.

Whenever we are using synchronized keyword then only lock concept will come to the picture.

If a thread wants to create synchronized method on the given object first it has to get lock of the object.

Once thread go to lock then it is allowed to execute any synchronized method on that object.

Once method execution completes automatically thread release a lock.

Acquiring and releasing lock internally takes care by JVM and programmer not responsible for this activity.

While a thread executing synchronized method on the given object remaining threads are not allowed to execute any
synchronized method simultenously on the same object but remaining threads are allowed to execute non-
synchronized methods simultenously.

Lock concept is implemented based on object but not based on method.

Case-1:

if multiple threads operating on same java objects then synchronization require.


class Abc{

public synchronized void disp(String name)

for(int i=1;i<=10;i++)

System.out.print("Good morning:");

try

Thread.sleep(2000);

catch(Exception e)

System.out.println(e);

System.out.println(name);

class Bca extends Thread{

Abc t;

String name;

Bca(Abc t,String name)

this.t=t;

this.name=name;

public void run()

t.disp(name);
}

class Boost{

public static void main(String arg[])

Abc p=new Abc();

Bca t=new Bca(p,"siva");

Bca t1=new Bca(p,"sai");

t.start();

t1.start();

output:

D:\New folder>javac Boost.java

D:\New folder>java Boost

Good morning:siva

Good morning:siva

Good morning:siva

Good morning:siva

Good morning:siva

Good morning:siva

Good morning:siva

Good morning:siva

Good morning:siva

Good morning:siva

Good morning:sai

Good morning:sai

Good morning:sai

Good morning:sai

Good morning:sai
Good morning:sai

Good morning:sai

Good morning:sai

Good morning:sai

Good morning:sai

Case-II:

If multiple threads operating on multiple java objects then synchronization not require.

Example:

class Abc{

public synchronized void disp(String name)

for(int i=1;i<=10;i++)

System.out.print("Good morning:");

try

Thread.sleep(2000);

catch(Exception e)

System.out.println(e);

System.out.println(name);

class Bca extends Thread{

Abc t;

String name;
Bca(Abc t,String name)

this.t=t;

this.name=name;

public void run()

t.disp(name);

class Boost{

public static void main(String arg[])

Abc p=new Abc();

Abc p1=new Abc();

Bca t=new Bca(p,"siva");

Bca t1=new Bca(p1,"sai");

t.start();

t1.start();

Even disp() is synchronized we will get irregular output because threads are operating on different java objects.

Case-III:

If method public static synchronized disp()

Every class in java has a unique lock which is nothing but class level lcok.

If a thread wants to execute a static synchronized method then a thread required class level lock. Once thread got a
class level lock then it is allowed to execute any static synchronized method of that class. Once method execution
completes automaticllay thread release the lock.
While a thread executing static synchronized method the remaining threads are not allowed to execute any static
synchronized method of that class symulteniously. But remaining threads are allowed to execute the following
example.

Exmaple:

class Abc{

public static synchronized void disp(String name)

for(int i=1;i<=10;i++)

System.out.print("Good morning:");

try

Thread.sleep(2000);

catch(Exception e)

System.out.println(e);

System.out.println(name);

class Bca extends Thread{

Abc t;

String name;

Bca(Abc t,String name)

this.t=t;

this.name=name;

public void run()


{

t.disp(name);

class Boost{

public static void main(String arg[])

Abc p=new Abc();

Abc p1=new Abc();

Bca t=new Bca(p,"siva");

Bca t1=new Bca(p1,"sai");

t.start();

t1.start();

Synchronized block:

If very few lines of the code required to synchronization then its not recommend to declare entire method not
synchronized.

We have to enclose those few lines of the code by using synchronized block.

The main advantage of synchronized block over synchronized method it is reduce waiting time of thread and improves
performance of the system.

We can declare synchronized block as follows:

Synchronized(this)

If a thread got lock of current object then only it is allowed to execute this area.

Lock concept applicable for object types and class types but not for primitives. Hence we can’t pass primitive types as
argument to synchronized block otherwise we will get compile time error saying unexpected type found int require
refrenece.

Example:

class Abc{
public void disp(String name)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

synchronized(this)

for(int i=1;i<=10;i++)

System.out.print("Good morning:");

try

Thread.sleep(2000);

catch(Exception e)

System.out.println(e);

System.out.println(name);

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

class Bca extends Thread{

Abc t;

String name;

Bca(Abc t,String name)

this.t=t;

this.name=name;

}
public void run()

t.disp(name);

class Boost{

public static void main(String arg[])

Abc p=new Abc();

Bca t=new Bca(p,"siva");

Bca t1=new Bca(p,"sai");

t.start();

t1.start();

What is object level lock and when it is require:

Every object in java has a unique lock which is nothing but object lock.

Whenever a thread wants to execute instance synchronized method require object lock.

What is class lock:

Every class in java has a unique lock which is nothing but class lock.

Whenever a thread wants to execute static synchronized method require object lock.

What is synchronized statements:

The statements present in synchronized method and synchronized block or called synchronized statements.

Inter Thread Communication:

Two thread can communicate with each other by using wait(), notify(), notifyAll().

The thread which is expecting updation is responsible to call wait(). Then immediately the thread will entered into
waiting state.
The thread which is responsible to perform which is updation after performing updation call notify() then waiting
thread will get the notification and continue it’s execution .

Why these three methods present in object class but not in thread class.

wait(), notify(), notifyAll() present in object class but not in thread class because thread can call these methods on any
java object.

To call wait(), notify(), notifyAll() on any object, thread should be owner of that object. That means the thread should
has lock of that object.

Hence we can call these 3 methods only from synchronized area, otherwise we will get runtime exception.

Example:

class Bca{

int total=0;

public void m1()

synchronized(this)

for(int i=0;i<=100;i++)

total=total+i;

this.notify();

class Abc extends Thread{

Bca t;

Abc(Bca t)

this.t=t;

public void run()

{
t.m1();

class Boost{

public static void main(String arg[])

Bca t=new Bca();

Abc p=new Abc(t);

p.start();

synchronized(p)

try

t.wait();

catch(Exception e)

System.out.println(e);

System.out.println(t.total);

Output:

D:\New folder>javac Boost.java

D:\New folder>java Boost

5050

Dead lock:
If two threads are waiting for each other forever such type of infinity waiting is called dead lock.

Synchronized keyword is the only reason for dead lock situation. Hence while using synchronized keyword we have to
take special care.

There is no resolution techniques for dead lock. There are several prevention techniques available.

Example:

class A{

public synchronized void m1(B t)

System.out.println("m1 method executed");

try

Thread.sleep(2000);

catch(Exception e)

System.out.println(e);

t.last();

public synchronized void last()

System.out.println("A class last method will executed");

class B{

public synchronized void m2(A t)

System.out.println("m2 method executed");

try
{

Thread.sleep(2000);

catch(Exception e)

System.out.println(e);

t.last();

public synchronized void last()

System.out.println("B class last method will executed");

class Boost extends Thread{

A a=new A();

B b=new B();

public void ab()

this.start();

a.m1(b);

public void run()

b.m2(a);

public static void main(String arg[])

Boost t=new Boost();

t.ab();
}

Output:

D:\New folder>javac Boost.java

D:\New folder>java Boost

m1 method executed

m2 method executed

In the above program if you remove one synchronized keyword then the program won’t entered into dead lock hence
synchronized keyword is the only reason for dead lock situation due to this while synchronized keyword we have to
take special care.

Dead lock vs Starvation:

Long waiting of a thread where waiting never ends such type of long waiting by default it is consider as dead
lock.

Long waiting of a thread where waiting ends set an point is called Starvation.

Daemon Threads:

The thread which is executing in the background is called Deamon threads.

Example: garbage collector, single dispatcher, Attach listener.

The main purpose of daemon threads is to support a non-daemon threads(main thread).

For example if main thread runs with low memory then jvm runs garbage collector to destroy useless objects so that
number of bytes of free memory will improved with this free memory main thread can continue it’s execution.

Daemon threads having low priority but based on our requirement daemon thread can run with high priority also.

How to check thread is a daemon or not:

public boolean isDaemon();

change the nature of daemon:

public void setDaemon(boolean b)

but changing daemon nature is possible before starting of a thread only. After starting a thread if you are trying to
change daemon nature then we will get runtime exception saying IllegalThreadStateException.

Default nature of thread:

By default main thread is always non-daemon state and all for remaining threads daemon nature will be
inherited from parent to child. That is if parent thread is daemon and then automatically child thread is also daemon
and if the parent thread is non-daemon then automatically child thread is also non-daemon.
Note:

It is impossible to change daemon nature of main thread because it is already started by jvm at beginning.

Example:

class Boost{

public static void main(String arg[])

System.out.println(Thread.currentThread().isDaemon());

Output:

D:\New folder>javac Boost.java

D:\New folder>java Boost

false

Example:

class Boost{

public static void main(String arg[])

System.out.println(Thread.currentThread().isDaemon());

Thread t=new Thread();

System.out.println(t.isDaemon());

t.setDaemon(true);

System.out.println(t.isDaemon());

Output:

D:\New folder>javac Boost.java

D:\New folder>java Boost

false

false

true
Whenever last non-daemon thread terminates automatically all daemon threads will be terminated irrespective of
their position.

Example:

class Abc extends Thread{

public void run()

for(int i=0;i<10;i++)

System.out.println("child thread");

class Boost{

public static void main(String arg[])

Abc t=new Abc();

t.setDaemon(true);

t.start();

System.out.println("End of main thread");

Green thread and native os thread:

java multithreading concept implemented by following by green thread model and native os model.

The thread which is managed by completely by jvm without taking underlying os support is called green thread. Very
few operating systems like sun solories provide support for green thread model. Anyway green thread model is
deprecated and not recommend to use.

The thread which is managed by the jvm with the help of underlying os, is called native os model. All windows based
operating systems provide support for native os model.

How to stop a thread:


We can stop a thread execution by using stop() of thread class.

public void stop()

if you call start method then immediately the thread entered into dead state. Anyway stop method is deprecated
and not recommended to use.

Example:

class Abc extends Thread{

public void run()

for(int i=0;i<10;i++)

System.out.println("child thread");

class Boost{

public static void main(String arg[])

Abc t=new Abc();

t.start();

System.out.println("End of main thread");

t.stop();

How to suspend and resume of a thread:

A thread can suspend another thread by using suspend() and we can resume a suspend thread by using
resume().

public void suspend()

public void resume()

Thread group:
Based on functionality we can group threads into single unit is called thread group. i.e thread group contains a group
of threads. In addition to threads thread group can also contains sub thread groups.

Example:

class Boost{

public static void main(String arg[])

System.out.prin tln(Thread.currentThread().getThreadGroup().getName());
System.out.println(Thread.currentThread().getThreadGroup().getParent().getName());

Output:

D:\New folder>javac Boost.java

D:\New folder>java Boost

main

System

Every thread in java belongs to some group. Main thread belongs to main group. Every thread group in java is the child
group of system group either directly or indirectly hence system group acts as root for all thread groups in java.

System group contains several system level threads like

Finalizer

Reference handler

Single dispatcher

Attach listener

ThreadGroup is a java class present in java.lang package and it is direct child class of object.

Constructors:

ThreadGroup g=new ThreadGroup(String name);

Creates a new thread group with a specified a group name. The parent of this new group is the thread group of
currently executing thread.

Example:

class Boost{
public static void main(String arg[])

ThreadGroup t=new ThreadGroup("firstgroup");

System.out.println(t.getParent().getName());

Example:

D:\New folder>javac Boost.java

D:\New folder>java Boost

main

ThreadGroup g2=new ThreadGroup(threadgroup m,string name);

Creates a new thread group with the specified group name. the parent of this new thread group is specified parent
group.

Example:

class Boost{

public static void main(String arg[])

ThreadGroup t=new ThreadGroup("firstgroup");

ThreadGroup r=new ThreadGroup(t,"second");

System.out.println(t.getParent().getName());

System.out.println(r.getParent().getName());

Output:

D:\New folder>javac Boost.java

D:\New folder>java Boost

main

firstgroup

String getName(): returns name of the thread group.


Int getMaxPriority(): return max priority of thread group.

Void steMAxPriority(int p): to set maximum priority of thread group. The default max priority is 10.

Threads in the thread group that have already higher priority won’t be effected but newly added threads this max
priority is applicable.

Example:

class Boost{

public static void main(String arg[])

ThreadGroup t=new ThreadGroup("firstgroup");

Thread t1=new Thread(t,"thread1");

Thread t2=new Thread(t,"thread2");

t.setMaxPriority(3);

Thread t3=new Thread(t,"thread3");

System.out.println(t1.getPriority());

System.out.println(t2.getPriority());

System.out.println(t3.getPriority());

Output:

D:\New folder>javac Boost.java

D:\New folder>java Boost

ThreadGroup getParent(): Returns parent group of current thread.

Void list(): it prints information about threadgroup to the console.


Int activeCount(): returns number of active threads present in the thread group.

Int activeGroupCount(): it returns number of active groups present in the current thread group.

Int enumerate(Thread[] t): to copy all active threads of this group into provided thread array. In this case sub thread
group threads also will be considered.

int enumerate(ThreadGroup[] g): To copy all active sub threadgroups into threadgroup array.

Boolean isDaemon(): To check weather the thread group or daemon or not.

Void setDaemon(boolean b): to set daemon of thread.

Void interrupt():to interrupt all waiting or sleeping threads present in thread group.

Void destroy(): to destroy thread group and it’s sub thread groups.

The problems with traditional synchronized keyword:

We are not having any flexibility to try for a lock without waiting.

There is no way to specify maximum waiting time for a thread to get lock. So that thread will wait until getting the lock
which may creates performance problems which may cause dedlock.

If thread release the lock then which witing thread will get that lock we are not having any control on this.

There is no API to list out all waiting threads for a lock.

The synchronized keyword compulsory we have to use either method level or with in the method and it is not possible
use across multiple methods.

To overcome these problems sun people interduce java.util.concurrent.locks package in 1.5 version.

It also provides several enhancement to the programmer to provide more control on concurrency.

Lock(Interface):

Lock object is similar to implicit lock acquired by a thread to execute synchronized method or synchronized
block. Lock implementation provide more extensive operations then traditional implicit locks.

Important method s of lock interface:

void lock(): we can use this method two acquire a lock. If lock is already available then immeditlely current thread will
get that lock. If the lock is not available then it will until getting the lock. It is exactly same bheaviour of traditional
synchronized keyword.

boolean tryLock(): to acquire the lock with out waiting. If the lock is available then the thread acquire the lock and
return true if the lock is not available then this method return false and can continue it’s execution without waiting. In
this case thread never be entered into waiting state.

void unclock(): to call this method compulsory current thread should be owner of the lock otherwise we will get
runtime exception saying IllegalMonitorStateException.

ReentrantLock:
It means a thread can acquire same lock multiple times without any issue. Internally reentrantLock increments
threads personal count when ever we call lock method and decrements count value whenever thread class unlock
method and lock will be released whenever count reaches zero.

ReentrantLock t= new ReentrantLock();

ReentrantLock t= new ReentrantLock(boolean fairness);

Example:

import java.util.concurrent.locks.*;

class Abc{

ReentrantLock t=new ReentrantLock();

public void disp(String name)

t.lock();

for(int i=1;i<=10;i++)

System.out.print("Good morning:");

try

Thread.sleep(2000);

catch(Exception e)

System.out.println(e);

System.out.println(name);

t.unlock();

class Bca extends Thread{

Abc t;
String name;

Bca(Abc t,String name)

this.t=t;

this.name=name;

public void run()

t.disp(name);

class Boost{

public static void main(String arg[])

Abc p=new Abc();

Bca t=new Bca(p,"siva");

Bca t1=new Bca(p,"sai");

t.start();

t1.start();

If you cant write lock and unlock then threads executed simulteniously and we will get irregular output.

If you write lock and unlock then the threads will be executed one by one and we will get regular output.

Thread pools:

Creating a new thread for every job may create performance and memory problems. To overcome this we
should go for thread pool. Thread pool is already create a thread ready to our job. Java 1.5 version interduces thread
pool framework to implement thread pools. Thread pool frame work is also known as executor frame work.

We can create a threadpool as follows:


ExecutorService service =Executors.newFixedThreadPllo(3);

We can submit a runnable job by using submit():

service.submit(job) ;

We can showdown executor service by using shutdown():

service.shutdown();

Example:

import java.util.concurrent.*;

class Abc implements Runnable{

String name;

Abc(String name)

this.name=name;

public void run()

System.out.println(name+" job started by"+ Thread.currentThread().getName());

try

Thread.sleep(2000);

catch(Exception e)

System.out.println(e);

System.out.println(name+" job completed by"+ Thread.currentThread().getName());

class Boost
{

public static void main(String arg[])

Abc[] jobs={new Abc("siva"),

new Abc("sai"),

new Abc("prasanth"),

new Abc("lava"),

new Abc("ganesh")

};

ExecutorService t=Executors.newFixedThreadPool(3);

for(Abc a:jobs)

t.submit(a);

t.shutdown();

Output:

D:\New folder>javac Boost.java

D:\New folder>java Boost

sai job started bypool-1-thread-2

siva job started bypool-1-thread-1

prasanth job started bypool-1-thread-3

prasanth job completed bypool-1-thread-3

sai job completed bypool-1-thread-2

siva job completed bypool-1-thread-1

ganesh job started bypool-1-thread-2

lava job started bypool-1-thread-3

lava job completed bypool-1-thread-3

ganesh job completed bypool-1-thread-2


Java.lang package

For writing any java program weather it is simple or complex the most commonly required classes and interface
are grouped into a separate package which is nothing but java.lang package.

Why can’t import lang package:

We are not required to import java.lang package explicitly because all classes and interfaces present in lang package by
default available in to every java program.

java.lang.Object:

The most commonly required methods for every java class (weather it is pre define or customized class) are
defined in a separate class which is nothing but Object class.

Every class In java is a child class of java either directly or in directly so that Object class methods by default available
to every java class.

The object class is parent class of all the classes in java by default. In other words, it is the topmost class of java.

Methods in Object class:

Public String toString()

Public native int hashCode()

Public Boolean eqyals(Object o)

Protected native Object clone() throws CloneNotSupportedException

Protected void finalize() throws Throwable

Public final Class getCLass()

Public final void wait() throws InterruptedException

Public final native void wait(long ms) throws InterruptedException

Public final native wait(long ms,int ns) throws InterruptedException

Public native final void notify()

Public native final void notifyAll()


toString():

We can use toString() for String representation of an Object. Whenever we are trying to print object reference
internally toSTring() will be called.

If our class dosen’t contain toString() then object class toString() method will be executed.

Example:

class Boost{

String name;

int roll;

Boost(String name,int roll)

this.name=name;

this.roll=roll;

public void display()

System.out.println("Name of the student:"+name);

System.out.println("roll of the student:"+roll);

public static void main(String arg[])

Boost s1=new Boost("ravi",45);

Boost s2=new Boost("suresh",56);

System.out.println(s1);

System.out.println(s2);

}
Output:

D:\New folder>javac Boost.java

D:\New folder>java Boost

Boost@15db9742

Boost@6d06d69c

In the above example Object class toString() method got executed which is implemented as follows:

public String toString()

return getClass().getName()+”@”+Integer.toHexString(hashCode())); }

output: classname@hashcode-in-hexadecimalform

if I override toStrint():

Example:

class Boost{

String name;

int roll;

Boost(String name,int roll)

this.name=name;

this.roll=roll;

public String toString()

return name+"..........."+roll;

}
public static void main(String arg[])

Boost s1=new Boost("ravi",45);

Boost s2=new Boost("suresh",56);

System.out.println(s1);

System.out.println(s2);

Output:

D:\New folder>javac Boost.java

D:\New folder>java Boost

ravi...........45

suresh...........56

Based on our requirements we can override toString() to provide our own String representation.

For example whenever we are trying to print Boost object reference to print his name and roll we have to
override toString() as follows.

In our collections classes String class and StringBuffer and StringBuilder classes toString() is overridden for meaningful
String representation hence it is highly recommend to override toString() method in our class also.

Example:

class Boost{

public static void main(String arg[])

String a=new String("abc");

System.out.println(a);

}
Output:

D:\New folder>javac Boost.java

D:\New folder>java Boost

abc

hashcode():

for every object a unique number generated by jvm which is nothing but hashcode.

Hashcode wont’t represents address of object. Jvm will use hashcode while saving objects into hashing related
datastractures like hashtable, hashset, hasmap,etc.

The main advantage of saving objects based on hashcode is search operation will become easy.

The most power full search algorithm is hashing. If you are giving the chance to Object class hashcode() it will
generate hashcode based on address of the object. It does’t mean hashcode represents address of the object. Based
on our requirements we can override hashcode method in our classes to generate our own hashcode.

Overriding hascode() is said to be proper if and only if for every object we have to generate a unique number has
hascode.

class Student{ class Student{

public int hashCode() public int hashCode()


{ {
return 100; return roll;
} }
} }
Improper way Proper way

This is proper way of overriding


hashcode method because we are
generates a different number as
hashcode for every object.

toString() vs hashCode():

If you are giving the chance to Object class toString() it will internally calls hasCode()

If we are overriding toString() then our toString() may not call hashCode()
Case 1:

class Boost{

String name;

int roll;

Boost(String name,int roll)

this.name=name;

this.roll=roll;

public static void main(String arg[])

Boost s1=new Boost("ravi",45);

Boost s2=new Boost("suresh",56);

System.out.println(s1);

System.out.println(s2);

Output:

D:\New folder>javac Boost.java

D:\New folder>java Boost

Boost@15db9742

Boost@6d06d69c

Object➔toString()

Object➔hashCode()

Case-2:

class Boost{
int i;

Boost(int i)

this.i=i;

public int hashCode()

return i;

public static void main(String arg[])

Boost s1=new Boost(44);

Boost s2=new Boost(23);

System.out.println(s1);

System.out.println(s2);

D:\New folder>javac Boost.java

D:\New folder>java Boost

Boost@2c

Boost@17

Object➔toString()

Boost➔hashCode()

Case-3:

class Boost{

int i;

Boost(int i)

{
this.i=i;

public String toString()

return i+" ";

public int hashCode()

return i;

public static void main(String arg[])

Boost s1=new Boost(44);

Boost s2=new Boost(23);

System.out.println(s1);

System.out.println(s2);

Output:

D:\New folder>javac Boost.java

D:\New folder>java Boost

44

23

Boost➔ toString()

equals():

we can use equals() to check equality of two objects.


Example: object1.equals(object2)

If our class dose’t contains equals() then Object class equals() will be executed.

Example:

class Boost{

String name;

int roll;

Boost(String name,int roll)

this.name=name;

this.roll=roll;

public static void main(String arg[])

Boost s1=new Boost("ravi",45);

Boost s2=new Boost("suresh",56);

Boost s3=s1

System.out.println(s1.equals(s2));

System.out.println(s1.equals(s3));

output:

D:\New folder>javac Boost.java

D:\New folder>java Boost

false

true
Object class equals() method got executed which is meant for reference comparison(address comparison) that is if two
references pointing to the same object then only .equals() method returns true. Based on our requirements we can
override equals() for content comparison.

getClass():

we can use getClass() to get runtime class definition of an object.

public final Class getClass()

By using this Class class object we can access class level properties like fully qualified name of the class and methods
information and constructors information, etc.

Example:

class Boost{

public static void main(String arg[])

Boost s1=new Boost();

System.out.println(s1.getClass());

Output:

D:\New folder>javac Boost.java

D:\New folder>java Boost

class Boost

finalize():

just before destroying an object garbage collector calls finalize() to perform cleanup activities. Once finalize()
completes automatically garbage collector destroy an object.

String and StringBuffer and StringBuilder.


Wrapper class:

The main objective of wrapper classes are:

To wrap primitive into Object form so that we can handle primitives also just like objects.

To define several utility methods which are required for the primitives.

Constructors:

Almost all wrapper classes contains two constructors one can take corresponding primitive as argument and
other can take string as argument.

Example:

Integer I=new Integer(10);

Integer I=new Integer(“67”);

If the string argument not representing a number then we will get runtime exception saying
NumberFormateException.

Example:

Integer I=new Integer(“Abc”);

Float class contains three constructors with float, double, String arguments.

Float f=new Float(10.5f);

Float f=new Float(“10.5f”);

Float f=new Float(10.5);

Float f=new Float(“10.5”);

Wrapper classes Corresponding constructor arguments


Byte byte or String
Short short or string
Integer int or String
Long long or String
Float float or String or double
Double double or String
Character char
Boolean Boolean or String

Character class contains only one constructor which can take char argument.
Character ch=new Character (‘a’);

Character ch=new Character (“a”); ➔invalid compile time error coming

Boolean class contains two constructors one can take primitive as argument and other can take String argument. If you
pass Boolean as primitive argument the only allowed values are true or false where case is important and content is
also important.

Example:

Boolean B=new Boolean(true);

Boolean B=new Boolean(false);

Boolean B=new Boolean(True); ➔Invalid

Boolean B=new Boolean(False); ➔Invalid

If you are passing String type as argument then case and content both are not important. If the content is case
insensitive String of “true” then it is treated as true otherwise it is treated as false.

Example:

Boolean b=new Boolean("true");-------->true

Boolean b=new Boolean("True");-------->true

Boolean b=new Boolean("TRUE");-------->true

Boolean b=new Boolean("siva");-------->false

Boolean b=new Boolean("jayanth");-------->false

Boolean b=new Boolean("sudha");-------->false

NOTE:

In all wrapper classes toString() is overridden to return content directly. In all wrapper classes .equlas()
overridden for content comparison.

Example:

class Abc{

public static void main(String arg[])

Boolean a=new Boolean("abc");

Boolean b=new Boolean("bca");

System.out.println(a.equals(b));

}
}

Output:

C:\Users\User\OneDrive\Documents>javac Abc.java

C:\Users\User\OneDrive\Documents>java Abc

true

utility methods:

valueOf()

xxxValue()

parseXxx()

toString()

valueOf():

We can use valueOf() methods to create wrapper object for the given primitive or String.

Form1:

Every Wrapper class except character class contains a static valueOf() to create wrapper object for the given
String.

Public static wrapper valueOf(String s)

Example:

Integer i=Integer.valueOf(“10”);

Double d=Double.valueOf(“10.5”);

Boolean b=Boolean.valueOf(“true”);

Form2:

Public static wrapper valueOf(String s, int radix)

Example:

Integer i=Interger.valueOf(“100”,2);

System.out.println(i); //4

Integer i=Interger.valueOf(“101”,4);

System.out.println(i); //17

Form2:
Every wrapper class including character class contains a static valueOf() to create a wrapper object for the given
primitive.

Public static wrapper valueOf(primitive a)

Example:

Integer i=Integer.valueOf(10);

Character ch=Character.valueOf(‘a’);

Boolean b=Boolean.valueOf(true);

XxxValue():

We can use Xxxvalue() to get primitive for the given wrapper object.

Every number type wrapper class(Byte, Short, Integer, Long, Float, Double) the following six methods to get primitive
for the given wrapper object.

Public byte byteValue()

Public short shortValue()

Public int intValue()

Public long longValue()

Public float floatValue()

Public double doubleValue()

Example:

class Abc{

public static void main(String arg[])

Integer I=new Integer(130);

System.out.println(I.byteValue());

System.out.println(I.shortValue());

System.out.println(I.intValue());

System.out.println(I.longValue());

System.out.println(I.floatValue());

System.out.println(I.doubleValue());

}
Output:

C:\Users\User\OneDrive\Documents>javac Abc.java

C:\Users\User\OneDrive\Documents>java Abc

-126

130

130

130

130.0

130.0

charValue():

character class contains charValue() to get char primitive for the given character object.

public char charValue()

Example:

class Abc{

public static void main(String arg[])

Character ch=new Character(‘c’);

Char c=ch.charValue();

System.out.println(c);

Output:

C:\Users\User\OneDrive\Documents>javac Abc.java

C:\Users\User\OneDrive\Documents>java Abc

booleanValue():

Boolean class contains booleanValue() to get char primitive for the given boolean object.

public boolean booleanValue()

Example:
class Abc{

public static void main(String arg[])

Boolean ch=new Boolean(‘abc’);

boolean c=ch.booleanValue();

System.out.println(c);

Output:

C:\Users\User\OneDrive\Documents>javac Abc.java

C:\Users\User\OneDrive\Documents>java Abc

false

note:

in total 38 xxxvalue() methods are possible.

parseXxx():

we can use parseXxx() to convert String to primitive.

Form1:

Every wrapper class except character class contains the following paseXxx() to find primitive for given string
object.

Public static primitive parseXxx(String s)

Example:

int i=Integer.parseInt(“10”);

double d=Doubel.parseDouble(“10.5”);

boolean p=Boolean.parseBoolean(“true”);

toString():

we can use toString() to convert wrapper object or primitive to string.

Form1:

Every wrapper class contains the following toString() to convert wrapper object String type.

Public String toString();


It is the overriding version of object class toString().

Whenever we are trying to print wrapper object reference internally this toString() method will be called.

Example:

Integer i=new Integer(10);

String s=i.toString();

System.out.println(s); //10

Every wrapper class including character class contains the following static toString() method to convert primitive to
String.

Public static String toString(primitive p)

Example:

String s=Integer.toString(10);

String s1=Boolean.toString(true);

String s2=Character.toString(‘a’);

Void:

It is a final class and it is the direct child class of object. It does not contain any methods and it contains only one
variable Void.Type.

In general we can use Void class in reflections to check whether the method return type is void or not.

Example:

If(getmethod(m1).getReturnType()==Void Type)

Void is the class representation of void keyword in java.

Autoboxing and Autounboxing:

================================

clone():

The process of creating exactly duplicate object is called cloning. The main purpose of cloning is to maintain
backup copy and to preserve state of an object. We can perform cloning by using clone() of Object class.

protected native Object clone() throws CloneNotSupportedException

Example:
class Abc implements Cloneable{

int i=10;

int j=20;

public static void main(String arg[])throws CloneNotSupportedException

Abc t=new Abc();

Abc t2=(Abc)t.clone();

t.i=45;

t.j=67;

System.out.println(t.i+" "+t.j);

Output:

C:\Users\User\OneDrive\Documents>javac Abc.java

C:\Users\User\OneDrive\Documents>java Abc

45 67

We can perform cloning only for cloneable objects. An object is said to be cloneable if and only if the corresponding
class implements cloneable interface. Cloneable interface present in java.lang package and it does not contain any
methods and it is a marker interface. If you are trying to perform cloning for non cloneable objects then we will get
runtime exception saying CloneNotSupportedException.

Shallow cloning vs Deep cloning:

Shallow cloning:

The process of creating bitwise copy of an object is called shallow cloning. If the main object contains primitive
variables then exactly duplicate copies will be created in the cloned object. If the main object contain any reference
variable then corresponding object won’t be created just duplicate reference variable will be created pointing to old
contained object. Object class clone method meant for shallow cloning.

Example:

class Bca{

int j;

Bca(int j)

{
this.j=j;

class Cab implements Cloneable{

Bca t;

int i=10;

Cab(Bca t,int b)

this.t=t;

this.i=i;

public Object clone() throws CloneNotSupportedException

return super.clone();

class Abc{

public static void main(String arg[])throws CloneNotSupportedException

Bca t=new Bca(50);

Cab p=new Cab(t,60);

System.out.println(p.i+" "+p.t.j);

Cab p1=(Cab)p.clone();

p1.i=888;

p1.t.j=999;

System.out.println(p.i+" "+p.t.j);

}
Output:

C:\Users\User\OneDrive\Documents>javac Abc.java

C:\Users\User\OneDrive\Documents>java Abc

10 50

10 999

In shallow cloning cloned object reference if you perform any change to the contained object then those changes will
be reflected to the main object.

To overcome this problem we should go for deep cloning.

Deep cloning:

The process of creating exactly duplicate independent copy including contained object is called deep cloning. In
deep cloning main object contain then in the cloned object duplicate copies will be created. If the main object
contained any reference variable then corresponding contained objects also will be created in the cloned copy.

By default object class clone method meant for shallow cloning but we can implement deep cloning explicitly by
overriding clone() in our class.

Example:

class Bca{

int j;

Bca(int j)

this.j=j;

class Cab implements Cloneable{

Bca t;

int i=10;

Cab(Bca t,int b)

this.t=t;

this.i=i;

public Object clone() throws CloneNotSupportedException


{

Bca b=new Bca(t.j);

Cab c=new Cab(b,i);

return c;

class Abc{

public static void main(String arg[])throws CloneNotSupportedException

Bca t=new Bca(50);

Cab p=new Cab(t,60);

System.out.println(p.i+" "+p.t.j);

Cab p1=(Cab)p.clone();

p1.i=888;

p1.t.j=999;

System.out.println(p.i+" "+p.t.j);

Output:

C:\Users\User\OneDrive\Documents>javac Abc.java

C:\Users\User\OneDrive\Documents>java Abc

10 50

10 50

By using clonead object reference if we perform any change to the contained object then those won’t be reflected to
the main object.

Which cloning is best:

If object contains only primitive variables then shallow cloning is the best choice.

If object contains reference variables then deep cloning is the best choice.

String and StringBuffer and StringBuilder

String:
Generally, String is a sequence of characters. But in Java, string is an object that represents a sequence of
characters. The java.lang.String class is used to create a string object.

There are two ways to create String object:

By string literal

By new keyword

String Literal

Java String literal is created by using double quotes. For Example:

String s=”abc”;

Each time you create a string literal, the JVM checks the "string constant pool" first. If the string already exists in the
pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a new string instance is
created and placed in the pool. For example:

Note: String objects are stored in a special memory area is called String constant pool.

By new keyword

String t=new String(“abc”);

In such case, JVM will create a new string object in normal (non-pool) heap memory, and the literal "abc" will be
placed in the string constant pool. The variable s will refer to the object in a heap (non-pool).

Example:

class Boost{

public static void main(String arg[])

String s1="welcome";

String s2=new String("welcome");

System.out.println(s1);

System.out.println(s2);

Output:

D:\New folder>javac Boost.java

D:\New folder>java Boost

welcome

welcome
In Java, String objects are immutable. Immutable simply means unmodifiable or unchangeable. Once String object is
created its data or state can't be changed but a new String object is created.

Example:

class Boost{

public static void main(String arg[])

String s1="abc";

String s2=new String("welcome");

s2.concat(s1);

System.out.println(s2);

Output:

D:\New folder>javac Boost.java

D:\New folder>java Boost

Welcome

If we are changes in string object then new object created so strings are immutable.

The reason behind the String class being final is because no one can override the methods of the String class. So that it
can provide the same features to the new String objects as well as to the old ones.

Following are some features of String which makes String objects immutable.

Class loader

Thread safe

Security

Heap space

Difference between == and equals() methods in string:

In strings == is always checks reference comparison and equlas() always checks content comparison. Because string is
child class for object class, in object class == checks reference comparison and equals() checks reference comparison ,
but coming to String class equals() methos override and it will checks content comparison in string class.
Example:

class Boost{

public static void main(String arg[])

String s1=new String("welcome");

String s2=new String("welcome");

System.out.println(s1==s2);

System.out.println(s1.equals(s2));

Example:

D:\New folder>javac Boost.java

D:\New folder>java Boost

false

true

whenever we using equlas() method in Strings then content is checks at String constant pool. Whenever we used in
== it checks at heap memory. In java every String object created a new memory area in heap memory.

Methods in String:

length():

it returns string length.

Public int length()

Example:

class Boost{

public static void main(String arg[])

String s1=new String("welcome");

System.out.println(s1.length());

}
}

Output:

D:\New folder>javac Boost.java

D:\New folder>java Boost

charAt():

it returns a char value at the given index number.

Public char charAt(int index)

Example:

class Boost{

public static void main(String arg[])

String s1=new String("welcome");

System.out.println(s1.charAt(3));

Output:

D:\New folder>javac Boost.java

D:\New folder>java Boost

Accessing First and last character by using the charAt():

Example:

class Boost{

public static void main(String arg[])

String s1=new String("welcome");


System.out.println("first character:"+s1.charAt(3));

System.out.println("last caharacter:"+s1.charAt(s1.length()-1));

Output:

D:\New folder>javac Boost.java

D:\New folder>java Boost

first character:c

last caharacter:e

comareTo():

this method compares two strings.

Public int comapreTo(String)

Example:

class Boost{

public static void main(String arg[])

String s1=new String("welcome");

String s2=new String("welcome");

System.out.println(s1.compareTo(s2));

Output:

D:\New folder>javac Boost.java

D:\New folder>java Boost

Note: if two strings are equals then it gives 0.


substring(): it returns a part of the string.

public String substring(int startindex)

public String substring(int startindex,int endindex)

Example:

class Boost{

public static void main(String arg[])

String s1="welcome to our college";

System.out.println(s1.substring(3));

System.out.println(s1.substring(1,10));

Output:

D:\New folder>javac Boost.java

D:\New folder>java Boost

come to our college

elcome to

contains():

it returns true or false after a matching the sequence of char value.

public boolean contains(char sequence)

example:

class Boost{

public static void main(String arg[])

String s1="welcome to our college";

System.out.println(s1.contains("college"));

}
Output:

D:\New folder>javac Boost.java

D:\New folder>java Boost

true

join(): it returns joined string.

Public static String join(charSequence delimeter, charSequence)

Example:

class Boost{

public static void main(String arg[])

String s1="welcome";

String s2=String.join(" ",s1,"to our college");

System.out.println(s2);

Output:

D:\New folder>javac Boost.java

D:\New folder>java Boost

welcome to our college

equals(): it returns true or false.

Example:

class Boost{

public static void main(String arg[])

String s1="welcome";

String s2="welcome";

System.out.println(s1.equals(s2));

}
}

Output:

D:\New folder>javac Boost.java

D:\New folder>java Boost

True

equalsIgnoreCase(): it compares another string. It dosen’t check case.

Example:

class Boost{

public static void main(String arg[])

String s1="welcome";

String s2="Welcome";

System.out.println(s1.equalsIgnoreCase(s2));

Output:

D:\New folder>javac Boost.java

D:\New folder>java Boost

True

isEmpty(): it checks if string is empty or not.

Example:

class Boost{

public static void main(String arg[])

String s1="";

System.out.println(s1.isEmpty());
}

Output:

D:\New folder>javac Boost.java

D:\New folder>java Boost

true

concat():

it concatenates the specified string


Example:

class Boost{

public static void main(String arg[])

String s1="welcome";

String s2=" to our college";

String s3=s1.concat(s2);

System.out.println(s3);

Output:

D:\New folder>javac Boost.java

D:\New folder>java Boost

welcome to our college

replace():

it replace all occurrences of the specified char value.

Example:

class Boost{

public static void main(String arg[])

String s1="Welcome to our college";

System.out.println(s1.replace(" ",""));
}

Output:

D:\New folder>javac Boost.java

D:\New folder>java Boost

Welcometoourcollege

split(): it returns a split string matching regex.

Example:

class Boost{

public static void main(String arg[])

String s1="Welcome to our college";

String[] s2=s1.split("\\s");

for(String s3:s2)

System.out.println(s3);

Output:

D:\New folder>javac Boost.java

D:\New folder>java Boost

Welcome

to

our

college

intern():

it returns interned string.


Example:

class Boost{

public static void main(String arg[])

String s1=new String("welcome").intern();

String s2=new String("welcome").intern();

System.out.println(s1==s2);

Output:

D:\New folder>javac Boost.java

D:\New folder>java Boost

true

indexOf():

it returns the specified char value index.

Example:

class Boost{

public static void main(String arg[])

String s1=new String("welcome");

System.out.println(s1.indexOf('e'));

Output:

D:\New folder>javac Boost.java

D:\New folder>java Boost

1
toLowerCase():

it returns a string in lower case.

Example:

class Boost{

public static void main(String arg[])

String s1=new String("WELCOME");

System.out.println(s1.toLowerCase());

Output:

D:\New folder>javac Boost.java

D:\New folder>java Boost

welcome

toUpperCase():

it returns a string to uppercase

class Boost{

public static void main(String arg[])

String s1=new String("welcome");

System.out.println(s1.toUpperCase());

Outptut:

D:\New folder>javac Boost.java

D:\New folder>java Boost

WELCOME
trim():

it removes beginning and ending spaces of this string.

Example:

class Boost{

public static void main(String arg[])

String s1=new String(" welcome to our college");

System.out.println(s1);

System.out.println(s1.trim());

Output:

D:\New folder>javac Boost.java

D:\New folder>java Boost

welcome to our college

welcome to our college

StringBuffer:

Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer class in Java is
the same as String class except it is mutable i.e. it can be changed. Java StringBuffer class is thread-safe i.e. multiple
threads cannot access it simultaneously. So it is safe and will result in an order.

1) StringBuffer Class append() Method :

The append() method concatenates the given argument with this String.

EXAMPLE:

class Second

public static void main(String arg[])

StringBuffer t=new StringBuffer("Hello");


t.append("Java");

System.out.println(t);

Output:

E:\stringbuffer>javac Second.java

E:\stringbuffer>java Second

HelloJava

2) StringBuffer insert() Method :

The insert() method inserts the given String with this string at the given position.

EXAMPLE:

class Second

public static void main(String args[]){

StringBuffer t=new StringBuffer("Hello ");

t.insert(1,"Java");

System.out.println(t);

Output:

E:\stringbuffer>javac Second.java

E:\stringbuffer>java Second

HJavaello

3) StringBuffer replace() Method :

The replace() method replaces the given String from the specified beginIndex and endIndex.

EXAMPLE:
class Second

public static void main(String args[])

StringBuffer s=new StringBuffer("Hello");

s.replace(1,3,"Java");

System.out.println(s);

Output:

E:\stringbuffer>javac Second.java

E:\stringbuffer>java Second

HJavalo

4) StringBuffer delete() Method :

The delete() method of the StringBuffer class deletes the String from the specified beginIndex to endIndex.

EXAMPLE:

class Second {

public static void main(String args[]){

StringBuffer s=new StringBuffer("Hello");

s.delete(1,3);

System.out.println(s);

Output:

E:\stringbuffer>javac Second.java

E:\stringbuffer>java Second
Hlo

5) StringBuffer reverse() Method:

The reverse() method of the StringBuilder class reverses the current String.

EXAMPLE:

class Second

public static void main(String args[])

StringBuffer s=new StringBuffer("Hello");

s.reverse();

System.out.println(s);

Output:

E:\stringbuffer>javac Second.java

E:\stringbuffer>java Second

olleH

6) StringBuffer capacity() Method :

The capacity() method of the StringBuffer class returns the current capacity of the buffer. The default capacity of the
buffer is 16. If the number of character increases from its current capacity, it increases the capacity by
(oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.

EXAMPLE:

class Stecond

public static void main(String args[])

StringBuffer t=new StringBuffer();

System.out.println(t.capacity());

t.append("Hello");

System.out.println(t.capacity());
t.append("java is my favourite language");

System.out.println(t.capacity());

Output:

E:\stringbuffer>javac Second.java

E:\stringbuffer>java Second

olleH

7) StringBuffer ensureCapacity() method :

The ensureCapacity() method of the StringBuffer class ensures that the given capacity is the minimum to the current
capacity. If it is greater than the current capacity, it increases the capacity by (oldcapacity*2)+2.

For example if your current capacity is 16, it will be (16*2)+2=34.

EXAMPLE:

class Second

public static void main(String args[])

StringBuffer t=new StringBuffer();

System.out.println(t.capacity());

t.append("Hello world");

System.out.println(t.capacity());

t.append("java is my favourite language");

System.out.println(t.capacity());

Output:

E:\stringbuffer>javac Second.java

E:\stringbuffer>java Second
16

16

34

Java StringBuilder

Java StringBuilder class is used to create mutable (modifiable) String. The Java StringBuilder class is same as
StringBuffer class except that it is non-synchronized. It is available since JDK 1.5.

1) StringBuilder append() method :

The StringBuilder append() method concatenates the given argument with this String.

EXAMPLE:

class Second

public static void main(String args[])

StringBuilder s=new StringBuilder("Hello welcome to ");

s.append("Java");

System.out.println(s);

Output:

E:\stringbuffer>javac Second.java

E:\stringbuffer>java Second

Hello welcome to Java

2) StringBuilder insert() method :

The StringBuilder insert() method inserts the given string with this string at the given position.

EXAMPLE:

class Second

public static void main(String args[]){


StringBuilder b=new StringBuilder("Hello ");

b.insert(1,"Java");

System.out.println(b);

Output:

E:\stringbuffer>javac Second.java

E:\stringbuffer>java Second

HJavaello

3) StringBuilder replace() method :

The StringBuilder replace() method replaces the given string from the specified beginIndex and endIndex.

EXAMPLE:

class Second{

public static void main(String args[]){

StringBuilder s=new StringBuilder("Hello");

s.replace(1,3,"Java");

System.out.println(s);

Output:

E:\stringbuffer>javac Second.java

E:\stringbuffer>java Second

HJavalo

4) StringBuilder delete() method :

The delete() method of StringBuilder class deletes the string from the specified beginIndex to endIndex.

EXAMPLE:

class Second{

public static void main(String args[]){


StringBuilder t=new StringBuilder("Hello");

t.delete(1,3);

System.out.println(t);

Output:

E:\stringbuffer>javac Second.java

E:\stringbuffer>java Second

Hlo

5) StringBuilder reverse() method :

The reverse() method of StringBuilder class reverses the current string.

EXAMPLE:

class Second{

public static void main(String args[]){

StringBuilder s=new StringBuilder("Hello");

s.reverse();

System.out.println(s);

Output:

E:\stringbuffer>javac Second.java

E:\stringbuffer>java Second

olleH

6) StringBuilder capacity() method :

The capacity() method of StringBuilder class returns the current capacity of the Builder. The default capacity of the
Builder is 16. If the number of character increases from its current capacity, it increases the capacity by
(oldcapacity*2)+2.

For example if your current capacity is 16, it will be (16*2)+2=34.


EXAMPLE:

class Second{

public static void main(String args[]){

StringBuilder s=new StringBuilder();

System.out.println(s.capacity());

s.append("Hello");

System.out.println(s.capacity());

s.append("Java is my favourite language");

System.out.println(s.capacity());

Output:

E:\stringbuffer>javac Second.java

E:\stringbuffer>java Second

16

16

34

7) StringBuilder ensureCapacity() method :

The ensureCapacity() method of StringBuilder class ensures that the given capacity is the minimum to the current
capacity. If it is greater than the current capacity, it increases the capacity by (oldcapacity*2)+2.

For example if your current capacity is 16, it will be (16*2)+2=34.

Example:

class Second{

public static void main(String args[]){

StringBuilder s=new StringBuilder();

System.out.println(s.capacity());

s.append("Hello");

System.out.println(s.capacity());
s.append("Java is my favourite language");

System.out.println(s.capacity());

s.ensureCapacity(10);

System.out.println(s.capacity());

s.ensureCapacity(50);

System.out.println(s.capacity());

Output:

E:\stringbuffer>javac Second.java

E:\stringbuffer>java Second

16

16

34

34

70

Difference between String and StringBuffer and StringBuilder:

String StringBuffer StringBuilder


Immutable Mutable mutable
Slow and more memory Fast and less memory Fast and less memory
Overrides equals() Can’t overrdies equals() -----
Uses string constant pool Uses heap memory Uses heap memory
Thread safe Thread safe No-thread safe
Synchronized Non-synchronized
Since java 1.0 Since java 1.5

You might also like