Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

Java

Uploaded by

Sambit Swain
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Java

Uploaded by

Sambit Swain
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 133

Java Notes

We cannot store integer in byte but if we can contain byte into another byte value, here’s the
example.
class HelloWorld {

public static void main(String[ ] args) {

byte b = 10;

b = (byte) (b+1);

System.out.println(b);

Arithematic operator

String concatenation

 If we are using + operator between 2 operands where one of the operands of the type
string the as the result both operands will merge with eachother.
 The result of a string concatenation is also a string.

Example:-

"a" + b ="ab"

"a" + "b" = "ab"

 Lemme write another program

class HelloWorld {

public static void main(String[] args) {

int a = 10;

int b = 2;

int sum = a +b;


System.out.println("The sum of a & b is " + sum); }

} output- The sum of a & b is 12

Example-2

class HelloWorld {

public static void main(String[] args) {

String a = "abc";

int b = 10;

int c = 20;

int d = 30;

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

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

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

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

output- abc102030

10abc2030

30abc30

60abc

 + Operator is the only overloaded operator in java because in some case it acts as an
addition operator and in other case it as as a concatenation operator.

Example-
 If we are using any arithematic operator between 2 variables x and y then the resultant
type will always be max(int, type of x, type of y).
 b = b + 1 (we are considering b as x and 1 as y, b stands for byte and 1 stands as for int
so if we put the formula then, we get max(int, type of x and type of y) as int contains
more memory so the output will be in Int)

 byte + byte = int.


 byte + short = int.
 short + short = int.
 int + long = long.
 Long + float = float
 Int + float = float
 Long + double = double
 Float + double = double

Relational operator

Relational operator is applicable for every primitive data type except boolean

 System.out.println(10 < 20)// true


 System.out.println(‘a’> 97.0)//false
 System.out.println(true> false)// compiletime error
 System.out.println(10<20 <30)// ERROR
 System.out.println(“abc123” > “abc”)// Compilation Error

Assignment Operator (=)

 It is used to assign values to variables.


 There are three types of assignment operator.
 Simple Assignment operator (int x = 10;)
 Chained Assigned Operator (int a,b,c,d; -- a=b=c=d=10;)

 Compound Assignment operator ( int x=10; x +=20; -> x = x+20;. Output will be
30)
Problem-1
Int a,b,c,d;
a=b-=c*=d/=2;
 System.out.println(a+""+b+""+c+""+d);
 output- -160,-180,200,10.
Equality Operator

 Equality operator is applicable for every primitive data type including


Boolean.
 Equality operator is applicable for non-primitive data types.
 For two object references r1 and r, r1 == r2, returns true if both references are
pointing towards same object and r1 == r2, returns false if both references are
pointing towards different objects.

System.out.println(10 == 20); // False


System.out.println(‘a’ == 97.0); //True
System.out.println(false == false); //True

class Test {
public static void main(String[] args) {
Test t1 = new Test();
Test t2 = new Test();
Test t3 = t1;
Test t4 = null;
System.out.println(t1 == t2); //False
System.out.println(t2 == t3);// False
System.out.println(t3 == t1); // False
System.out.println(t1 == null);// False
System.out.println(t4 == null); // True

}
}
Bitwise Operator (& | ^)

a & b  It returns true if both arguments are true.

System.out.println( true & true); // true


System.out.println( true & false); // false
System.out.println( False & true); // false
System.out.println( False & False); // true

A | b -> it returns true if any of the arguments are true


System.out.println( true | true); // true
System.out.println( true | false); // true
System.out.println( False | true); // true
System.out.println( False | False); // false

A ^ B -> it returns true if both arguments are different

System.out.println( true & true); // false


System.out.println( true & false); // true
System.out.println( False & true); // true
System.out.println( False & False); // false

LOGICAL OPERATOR

 a & & b will be executed if a is true.


 a || b --- b will be executed if a is false.

Difference between logical and bitwise operator

 In bitwise, Both arguments will be executed


 In logical, the execution of second argument is optional.
 In bitwise, it is applicable for both Boolean and integer.
 In logical, it is only applicable for Boolean.

Ternary operator( ? : )

Condition ? statement1 : statement2 ;

Int x = ( 10 < 20) ? ((30 > 40) ? 50 :60)) = ((70<80) 90 : 100)); //output-60.

Condition

a) True
b) False
 If condition is true then it will execute statement1.
 If condition is false then it will execute statement 2.

Flow control
 The order in which all the statements are executed is known as flow control and run time
is known as flow control.

 Flow control are of 3 types


1. Selection Statement
a) if-else switch
2. Logical or Iterative Statement
b) For loop
c) While loop
d) Do-while loop
3. Transfer Statement
a) break
b) continue
c) return

Selection Statement
If-else

Syntax
If (condition) // true/false
{
Statement1; // if true
}
else {
statement2; // else false
}

 Else part is optional


EXAMPLE-1

class A {
public static void main(String[] args) {
if (true){
System.out.println("hi"); // true
}
if (false){
System.out.println("hi") // nothing
}

}
}

Example-2

class A {
public static void main(String[] args) {
if (true){
System.out.println("hi"); }
System.out.println("hiiii");
else {
System.out.println("heyy");
}

}
} // output will be compilation error because there is system.out.println in between
if and else. The condition says there should not be any other elements is between if
and else.

 If we have only one statement inside if then no need to give curly braces.
class A {
public static void main(String[] args) {
if (true)
System.out.println("hi");
else
System.out.println("ryoiki");
}
}
 If we are not providing any curly braces then only one statement is allowed, and
that statement should not be of declaritive type.
 If(true); It is valid but has no use, it only declaires that it needed to stop there.

If else nested
class A
{
public static void main(String[] args) {
int age = 23;
if (age>=18 && age <23)
system.out.println("Focus on studies");
else if (age>27 && age<=32)
system.out.println("Get married");
else
System.out.println("no use of marriage");
}
}

Switch
switch(x)
{
case 1:
statement1:
break:
case 2:
statement2:
break;

default:
default statement;
break;
}
Allowed arguments
1.4v
Byte
Short
Int
Char
1.5v
Byte
Short
Integer
Character
Enum
1.7v
String

Switch(x)
{
Case 10:
System.out.println(10);
Break;
Case 20:
System.out.println(20);
Break;
Default:
System.out,println(“default”);
Break;
}
 It is optional to mention case and default in switch.
 switch(x){
}
 If we are writing any statement inside switch it has to be under some case or default.
 Curly braces are mandatory here.
 Case label should be of constant expression. Example – case 10; but it can’t be case y.
because it contains variable which is not supposed to be there.

class HelloWorld {
public static void main(String[] args) {
int a = 10;
int b = 20;
switch(a)
{
case 10:
System.out.println(10);
break;
case 20:
System.out.println(20);
break;
default:
System.out.println("def");
break;
}
}
}

 Case level should be In the range of switch argument .

class HelloWorld {
public static void main(String[] args) {

byte b = 10;
switch(b)
{
case 10:
System.out.println(100);
break;
case 1000:
System.out.println(125);
break;

default:
System.out.println("def");
break;
}
}
}
Output will be compilation error, as we converting byte to int.
 Duplicate case label is not allowed.

class HelloWorld {
public static void main(String[] args) {
int x = 97;
int y = 98;
switch(x){
case 97:
System.out.println(97);
break;
case 98:
System.out.println(98);
break;
case'a':
System.out.println(99);
break;
default:
System.out.println("def");
break;
}
}
}
 If any case matches from that case onwards all the statements will be executed until
break or end of the switch, it is known as fall through inside switch.
class HelloWorld {
public static void main(String[] args) {

int x= 0;
int x= 1;
int x= 2;
int x= 3;

switch(x){
case 0:
System.out.println(0);

case 1:
System.out.println(1);
break;
case 2:
System.out.println(2);

default:
System.out.println("default");
break;

}
}
}
Default
 It is optional.
 We can write default case atmost once.
 It is not mandatory to write the default case as the last case.

Looping statement/iterative statement


For loop
 When we know the exact number of iteration then we should go for For loop.

 For (initialization (1) ; condition (2); updation (4) ){


Statement (3);
}

 class HelloWorld {
public static void main(String[] args) {

for(int i = 0; i < 3; i++){


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

}
}

Initialization part

 This part is executed only once.


 Int I = 0; string s = “abc”;
 We can declare any number of variables in the initialization part but it should be
of same type.
 We can write printing statement in the initialization part.
 If we are not providing any condition in the condition part then compiler always
place true;

class HelloWorld {
public static void main(String[] args) {
int i = 0;
for(System.out.println("hii");i < 3; i++){
System.out.println("bye");
}

}
}
Output
Hii,bye,bye,bye.
Problem
for(int i = 0; ;i++){
System.out.println("bye");
}
Output – infinity bye, happened cuz we have not given any condition so the
compiler placed it true;
Updation part
 All the three parts of for loop are optional and independent of each other.

public static void main(String[] args) {


for( int i=0 ;i < 3 ;System.out.println("hi")){
System.out.println("Hello, World!");
i++;
}
 Output will be – hello world, hi, hello wold,hi,hello world,hi

 Write a program to print from 0-10 .

 Write a program to find a sum of 2 numbers


Scanner class
Whenever we want input from the user then we should go for scanner class.This class is
presented in java.util.package.

Methods
Integer input – nextInt(),nextByte(), nextShort(),nextLong();
Decimal input – nextFloat(),nextDouble();
Boolean Input – nextBoolean()
String input – next(),nextLine()
Char input – nextLine(), charAt(0);

Creating object of Scanner class

Scanner sc = new Scanner(System.in);


Int x = sc.nextInt();

For string
public static void main(String[] args) {

System.out.println("Enter a string");
Scanner s = new Scanner(System.in);
String x = s.nextLine();
System.out.println(x);
s.close();
}
Write a program to find all the even and odd numbers from 0 to n numbers .
Write a program to find the sum of all the even and odd numbers from 0 to n
Write a program to check whether a number is prime or not.
Write a program to display all the prime numbers from 0 to n numbers
Write a program to find the sum of all prime numbers from 0 to n.

Primitive type casting


Type casting is the process of converting one type of data value into another type of data
type.
 It is otherwise known as primitive type casting.
 This process of conversion is applicable for all the primitive data types except
Boolean.
1. Implicit type casting
2. Explicit type casting
Implicit type casting

 Whenever we are storing smaller data values into bigger data type then that process is
known as implicit type casting.
 Implicit type casting will be done automatically by the compiler.
 There will be no loss of data.
 The other names for implicit type casting are

1. Upcasting
2. widening

class A{
public static void main(String[] args) {
int x = 100;
System.out.println(x);
double d = x;
System.out.println(d);

}
}

class A{
public static void main(String[] args) {

char x = 'a';
System.out.println(x);
double d = x;
System.out.println(d);
}
}
//Output will be 97.0

Explicit type Casting


Example
class A {
public static void main(String[] args) {
int x = 10;
byte b = (byte) x;
System.out.println(b);
}
}
Output will be 10.

 Programmer is responsible for explicit type casting.


 Whenever we are assigning a bigger data type value to a smaller data type variable
explicit type casting will be perform.
 It is also known as downcasting or narrowing.
 There maybe some loss of information.

OOP’S CONCEPT
METHOD
 Method is the set or block of code which is used to perform a particular task.
Syntax for method
Modifiers returnType methodName (parameter/arguments)
{
//body
}
Method Name
 Method name always starts with lower case.
 Example- mam(), concat(), append().
 If a method name contains more than one word then method name always starts with
lower case but every inner word should start with uppercase known as camel’s rule.
 Execution starts from the main method and ends from the main method.
 There are two types of methods in java.

1-static method.
A method which is represented by static modifier is known as static method.

2-non-static method.
A method which is declared static known as non-static method.

If we want to print the codes present inside m1 method then we need to call that method.

Calling a method
It means go to that method, execute the codes present inside that method and come back.
Calling a static method
We can call a static method by the following ways.
1.directly
2.by object
3.by class name

Method argument
 It is just like an input to a method.
 Arguments of a method is optional.
 There are two types of method argument
1.primitive data type
Public void m1(int x)
{
}
2.Non primitive data type
Public void m1(string x)
{
}
Calling a method with primitive data type as an argument
class Test{
public static void m1(int x) {
System.out.println(x);
System.out.println("hii");
}

public static void main(String [] args){


m1(10);
}
}

class Test{
public static void m1(int x) {
System.out.println(x);
System.out.println("hii");
}
public static void m2(double d) {
System.out.println(d);
System.out.println("it's a double");
}
public static void m3(boolean b) {
System.out.println(b);
System.out.println("it's a boolean value");
}

public static void main(String [] args){


m1(10);
m2(10.5);
m3(true);
}
}
output will be – 10,hii, 10.5, it’s a double, true, it’s a Boolean value.

Calling a method with non primitive type as an argument

 We can call method with non primitive type as an argument by the following 2
ways
1.By passing of the same type as an argument
2.By using null as an argument
class Test{
public static void m1(String s) {
System.out.println("hii");
}
public static void main(String [] args){
m1("hey");
m1(new String());//possible ways for non primitive data types
m1(null);//possible ways for non primitive data types

}
}
Output- hii, hii,hii.

For object
class Test{
public static void m1(Test s) {
System.out.println("hii");
}
public static void main(String [] args){
m1(new Test());
m1(null);
}
}
Return type of a method

 It is just like an output to a method.


 There are three types of return type.
1.Void
2.Primitive
3.Non-primitve.

Void
If a method has return type as void then it doesn’t return any value when called.
class Test{
public static void m1() {
System.out.println("hii");
}
public static void main(String [] args){
m1();

}
}

Primitive return type


 If a method has any return type except void then it is mandatory to write a return
statement inside that method. If return statement is not there then it will show missing
return statement.

class Test {
public static int m1() {
System.out.println("hii");
return 10;
}

public static void main(String[] args) {


m1(); //output will be hii

}
}
Example
class A {
public static void main(String[] args) {
int x = 130;
byte b = (byte) x;
System.out.println(b);
m1(); //by directly

A t = new A ();
t.m1();//by object

A.m1(); //by className

public static void m1() {

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

Calling a non static method


We can call a non static method with the help of object.
class A {
public static void main(String[] args) {
int x = 130;
byte b = (byte) x;
System.out.println(b);

A t = new A ();
t.m1();//by object

public void m1() {

System.out.println("domain");
}
}
class A {
public static void main(String[] args) {

System.out.println("main starts");

m1();
System.out.println("main ends");

public static void m1() {

System.out.println("m1 starts");
m2();
System.out.println("m1 ends");
}
public static void m2(){
System.out.println("m2 starts");
System.out.println("m2 ends");
}
}

Output will be

Printing the return value of a method

We can print return value of a method in the following ways.

1.By storing in a variable


class Demo{
public static void main(String[] args) {
int x = m1();
System.out.println(x);
}
public static int m1() {
System.out.println("m1 method");
return 10;
}
} output will be- m1 method, 10;

2.directly
class Demo{
public static void main(String[] args) {

System.out.println(m1());
}
public static int m1() {
System.out.println("m1 method");
return 10;
}
} output will be – m1 method, 10.

By non-primitive
class Demo{
public static void main(String[] args) {

System.out.println(m1());
}
public static String m1() {
System.out.println("m1 method");
Return "hey";
}
}
Output will be – m1 method and hey.

If a method has non primitive data type then it returns null or object of that data type.
class Demo{
public static void main(String[] args) {

System.out.println(m1());
}
public static Test m1() {
System.out.println("m1 method");
return null;
}
}

After return statement we cannot print any other statement.

Method signature
public void m1(int x) { // where method name(m1) and type of argument(int x) is the method
signature.

 Method signature consists of method name and type of argument


 2 methods with same method signature is now allowed within a class.

Inheritance(Is-A- Relationship)
 Acquiring properties of one class by another class is known as inheritance.
 Where property means Variables and methods.
 This process involves minimum two classes.
 Inheritance is represented by extends keyword.
 The main advantage of inheritance is code reusability.
1.Parent class / super class/ Base class
2.Child Class / derived class / sub class

class Atom {
public void m1() {
System.out.println("hii");
}
}

class Bomb extends Atom {


public void m1() {
System.out.println("hello");
}

public static void main(String[] args) {

}
}

Parent Class
The class whose property is acquired is known as Parent class.
Child Class
The class who acquires the property is known as child class.

 Object class is the super most class in java means every class in java extends object
class either directly or indirectly.

 If a class doesn’t extends any other class then that class is said to be direct child of
object
Class A{ direct child class of object class
}
Types of inheritance
1.Single Inheritance
2.Multiple Inheritance
3.multilevel inheritance
4.Hierarchial Inheritance
5.Hybrid Inheritance.
Single Inheritance
 In single inheritance, there’s one parent and one children which extends the parent
class.

Multilevel inheritance

When a class is derived/child class of a class which itself is derived from another
class ,is known as Multi-Level Inheritance.

Hierarchial Inheritance
 In Hierarchial inheritance there’s one parents class and multiple child classes
which extends the parent class.
Multiple inheritance

When one class extends more than one class then that type of inheritance is known as multiple
inheritance.

It is not allowed in java BECAUSE OF DIAMOND PROBLEM.

Class A{}

Class B{}

Class C extends A,B{

Why it’s not possible

Class A

Public void m1()

{
sopln(“a”)

Class B

Public void m1(){


Sopln(“b”)

Class c extends A,b

Psvm()m{
c c = new c();

c.m1();

Cyclic Inheritance is not allowed in Java.

Method overloading

Creating multiple methods with same name but with different arguments known as method
overloading.
m1(int x )
m1(string s )
m1(boolean b )
m1(double d )

class A {
public void m1(float f){
System.out.println("hi");
}
public void m1(double d){
System.out.println("bye");
}
public static void main(String[] args) {
A a1 = new A();
a1.m1('a');
}
} output will be hi

class programming {
public static void main(String[] args) {
m1(10,10.5);
m1(10.5,10);

}
public static void m1(int i, double d){
System.out.println("hi");
}
public static void m1(double d,int i){
System.out.println("bye");
}
} output will be hi,bye

If there’s a relation between the arguments then the priority will be given to the child class.

Var arg method

A method which can be called by passing any number of arguments is known as var args.
public static void m1(int...x)// known as var arg method
We can call var arg method by passing any number of arguments including 0.
class A{
public static void main(String[] args) {
m1(5);
}
public static void m1(int...x){
System.out.println("var arg method");
}
}

Internally var arg method is converted into one dimensional array, wherever there is one
dimensional array it can be replaced with var arg method but vice versa is not true.
public static void main(String... args) { // we can use var args instead of []array.

Var arg method always get the least priority.

Method over-riding

Changing the implementation of parent class method in a child class according to the
requirement of child is known as method over riding.

Public void m1(int x)--- this is known as declaration.

Known as initialization

}
class A{
public static void m1(){

}
}
class B extends A{
public static void m1(){

}
}

Rules for overriding

 Method signature(things inside the argument) must be same.


class A{
public static void m1( int x){
System.out.println("sweet");
}
}
class B extends A{
public static void m2( int x){
System.out.println("spicy");
}
}
// it is not over riding because there are different methods even tho arguments are
same.

 We can’t change the return type of method overriding, from 1.5v onwards co variant
concept came into picture.
 If the method is overrriden then it will call the sub classs method again and again.

Difference between method overloading and method overriding


In method overriding the method name and argument have to be same, while in method
overloading the method names need to be same but the arguments should be different.

Co variant concept
 According to this concept we can change the return type of method overriding.
 This concept is not valid for primitive data types.
 Co variant concept is applicable for non primitive data types but with some
restrictions.
 Parent class method return type should be parent class of child class method
return type.

class A{
public Object m2(){
return null;
}
}
class B extends A{
public String m2(){
return null;
}
} // it is possible but vice versa is not possible

package
 Package is the collection of classes and interfaces.
 Import packagename.classname;

Modifiers

 Modifiers are the reserved keywords using which a programmer can decide accessing
area or functionality of a class, method, variable or block.
 In Java, modifiers are keywords that alter the behavior or attributes of a class, method,
variable or block.

There are two types of modifier

1.Access Modifier

Access modifiers determine the visibility of classes, methods, and variables.

It is of 4 types - public, protected,default,private.

Public

It is an access modifier which is applicable for class, method and variable.

If a class is public then we can access it within the package and outside the package
too but we have to make sure that we must import the class.

If a method is public then we can access it within the class, outside the class, within
the package and outside the package too.

If a variable is public then we can access it within the class, outside the class, within
the package, and outside the package too.

Protected modifier

If a method is declared as protected then we can access that method within a class,
outside a class, within same package as well as outside the package but only in child
class means only possible in inheritance.
Protected void m1(){

Default Modifier

If a method is default then we can only access within the same package but not
outside the package.

Void m1(){

Private modifier

If a method is declared as private then we can access that method within a class but
not outside the class.

Scope of access modifier

Public>Protected>Default>private

While coming from parent to child class the scope of access modifier should increase
but shouldn’t decrease.

P.C(parent class) method modifier  public protected default private

C.C( class class) method modifierpublic-public, protected- public,protected,


default- public,protected,default, private- It can’t be overridden.

Private method can’t be overridden.

2.Non access modifier

1.Final

It is a modifier which is applicable for variables, methods and classes.

Final variable

If a variable is declared as final we can’t changed the value of an variable.


class Demo{
static final int x = 10;
public static void main(String[] args) {
System.out.println(x);
}
}

Final method

If a method is declared as final, we can’t override that method because it’s


implementation is fixed.

We can’t override final method.


class Demo{
public final void m1(){

}
}
class Test extends Demo{
public void m1(){

}
}

Final class

If a class is declared as final, we can’t inherit that class that is we can’t create the
child class of that class.

All the methods present inside final class are by default final, variables may not be
final.
final class Demo{

}
class Test extends Demo{

Abstract Modifier

It is applicable for method and classes but not for variables.

Abstract method

An abstract method which is a method which is declared but not implemented.


public void m1()//declaration
{
//implementation
}

public void m1()//abstract method

If a method is abstract then we have to declare the class as an abstract.


public void Test()
{
abstarct void m1();
}

Child class is responsible for providing the implementation of abstract methods present in
parent class.
abstarct class experiment
{
abstarct void m1();
}
class B extends experiment{
public void m1(){
//implemented
}
}

Abstract Class

If we are not allowed to create an object of an class is said to be abstract class.


abstract class experiment
{
public static void main(String[] args) {
experiment e = new experiment(); //will give error
}
}

Abstract class can contain both abstract methods as well as concrete methods
abstract class experiment
{
abstract void m1(); // abstract method
public void m2(){
//concrete method
}
}

Abstract class can contain zero number of abstract methods.


abstract class experiment
{
public void m2(){

}
}

Calling non-static of abstract class


abstract class Test{
public void m1(){
System.out.println("Hi");
}
}
class Demo extends Test{
public static void main(String[] args) {
Demo d1 = new Demo();
d1.m1();
} output will be “hii”
}

If child class not providing implementation for all the abstract method present in the parent
class then we have to declare child class as an abstract.
abstract class A{
abstract void m1();
public void m2(){
System.out.println("hii");
}
}
class B extends A{
public void m1(){
System.out.println("bye");
}
public static void main(String[] args) {
B b1 = new B();
b1.m1(); //bye
b1.m2();//hii
}
}

Static

It is the non access modifier which is applicable for methods and variable only.

Method hiding

Whenever we are declaring a static method in the child class which is already present in the
parent class where we will keep the method declaration same but by changing the
implementation is known as the process of method hiding.
class Tommy {
public static void m1(){
System.out.println("hii");
}
}
class VDY extends Tommy{
public static void m1(){
System.out.println("bye");
}
public static void main(String[] args) {
Tommy t = new Tommy();
t.m1(); // hii
VDY v = new VDY();
v.m1();// bye
Tommy m = new VDY();
m.m1();// hii the difference is here
}
}

In method hiding the method resolution takes place on the basis of object reference side and
compiler is responsible for the method resolution.

It is otherwise known as compile time polymorphism

CONSTRUCTOR
 WHENEVER WE CREATE AN OBJECT SOME PIECE OF CODE WILL BE EXECUTED
AUTOMATICALLY TO PERFORM INITIALIAZATION OF AN OBJECT, THAT PIECE OF
CODE IS NOTHING BUT CONSTRUCTOR.
 Constructor is a special type of method which will be executed everytime whenever we
create an object to perform initialization of an object.

Rules for writing constructor


1. Constructor name and class name must be same.

class eprogram {
Test(){
System.out.println("constructor");
}
public static void main(string[] args){

}
} // complie time error
//note- if we are creating a constructor with the name different from class name
then we will get compile error saying invalid method declaration

2.Return type concept is not applicable for constructor even void also.

If we provide return type to a constructor the compiler or jvm will not give any error and it will
be treated as a normal method.
class A{
void A(){
//IT IS NOT A CONSTRUCTOR IT IS A METHOD
}
}

class A {
A(){
System.out.println("const");
}
void A(){
System.out.println("method");
}
public static void main(String[] args) {
new A().A(); //OUT PUT WILL BE CONST AND THEN METHOD
}
}

3.All access modifier is applicable for constructor except non access modifier.
Q: What happens if a constructor is declared as private??

Ans: if we declare constructor as private then we cannot access constructor outside the class or
we restrict object creation inside any other class.

class Demo{
public static void main(String[] args) {
Test t = new Test();
}
}
class Test{
private Test(){

}
}

There are 2 types of constructor

1.No argument constructor(constructor without any argument)


class A{
A(){

}
}

2.Parametrized constructor(constructor with parameter or argument)


class A{
A(int x){

}
}

Case 1

The first statement inside constructor should be either super() (call to super) or this(), if we are
not writing any of these, compiler will place super() as the first statement.
class Demo{
Demo(){
System.out.println("hii");
}
}

Case-2

We can’t write super() or this() simultaneously


class Demo{
Demo(){
super();
this();
} // will give compile time error for writing both statements
}
Case-3

If we try to write super() anywhere except constructor then we will get compile error.
class Demo{
public static void m1(){
super();
System.out.println("hii"); //CE
}
}

Default Constructor

 Compiler generates default constructor.


 If there is no constructor inside a class then compiler generates default constructor.
 Every class in java contains constructor either defaultly or given/assigned constructor
given by programmer.
class A{
A(){
Super();
// default constructor and it is not visible
}

Note- every default constructor is a no argument constructor but every no argument


constructor is not default constructor.
}
 The default constructor will have the same access modifier which a class have is that
public and default.

Difference

This,super
 These are keywords.
 These are used to refer current class or super class non static variable respectively.
 These can be used anywhere expect static area.
 These can be used any no time

this() , super()

 These are constructor calls


 These are used to call current class or parent class constructor respectively.
 These can be used only inside a constructor as the first statement.
 These can be used only once.

class Demo{
int x = 10;
public static void main(String[] args) {
Test t = new Test();
t.m1();
}
}
class Test extends Demo{
int x = 100;
public void m1(){
System.out.println(this.x);//100
System.out.println(super.x);//10
}
}

Constructor overloading

Creating multiple constructor with same name but different arguments is known as constructor
overloading.
class A{
A(){
System.out.println("NO ARG CONST");
}
A(int x){
System.out.println("int arg const");
}
A(boolean b){
System.out.println("boolean arg const");
}
public static void main(String[] args) {
new A();//no arg const
new A(10);//int arg const
new A(true);//boolean arg const
}
}

Constructor chaining

Calling one constructor from another constructor is known as constructor chaining.

We can achieve constructor chaining by the help of call to super() and call to this().
class A{
A(){
this(10);
System.out.println("NO ARG CONST");
}
A(int x){
this(true);
System.out.println("int arg const");
}
A(boolean b){
System.out.println("boolean arg const");
}
public static void main(String[] args) {
new A(); // boolean arg const, int arg const, no arg const

}
}

Super
class A{
A(int x){

System.out.println("NO ARG CONST");


}
}
class B extends A{
B(){
super(10);
System.out.println("bye");
}
public static void main(String[] args) {
new B();
} //no arg const , bye
}

class A{
A(){

System.out.println("NO ARG CONST");


}
}
class B extends A{
B(){
System.out.println("bye");
}
public static void main(String[] args) {
new B();
} // no arg const , bye - no arg will print first due to the default super() INSIDE
presnt there.
}

Q- CAN WE OVERRIDE CONSTRUCTOR

ANS. No we can’t override a constructor neither we can inherit it and the main reason for this
is it will get confused thinking whether it is a method or constructor.
class A{
A(){

}
}
class B extends A{
A(){
//CE
}
}

Some stuffs that looks normal but ain’t normal


class A{
A(){

}
}
class B extends A{
B(){
super(); // both B and A constructors are defaultly there
}
}
class A{
A(int x){
}
}
class B extends A{
B(){
super(); // CE
}
}

Reason why multiple inheritance is not allowed with the view of constructor
class A{

}
class B{

}
class C extends A,B{
C(){
super(); // the jvm will get confused
}
}

class Student {
String name;

public static void main(String[] args) {


Student s1 = new Student();
Student s2 = new Student();
System.out.println(s1.name);// null
System.out.println(s2.name);// null jvm will provide default value for string as it
is a non primitive data type and it is not even initialized
}
}
After initialization
class Student {
String name; // declaration

public static void main(String[] args) {


Student s1 = new Student();
Student s2 = new Student();
s1.name="Tushar"; // initialization
s2.name="Sahoo";
System.out.println(s1.name);
System.out.println(s2.name);
}
} output will be – Tushar,Sahoo
Initialization in constructor
class Student {
String name;
Student(String name1){
name = name1;
}
public static void main(String[] args) {
Student s1 = new Student("abc");
Student s2 = new Student("xyz");
s1.name = "abc";
s2.name = "xyz";

System.out.println(s1.name);
System.out.println(s2.name);
} // abc,xyz
}

class Student {
String name;
int id;
Student(String name, int id){
this.name= name;
this.id = id;
}

public static void main(String[] args) {


Student s1 = new Student("abc",10);
Student s2 = new Student("xyz", 20);

System.out.println(s1.name +"" +s1.id);


System.out.println(s2.name +"" +s2.id);

} // abc 10, xyz20


}

Copy constructor

Creating an object from the existing object is known as copy constructor.

Factory method

It is a method which is called by a class name and when called it should return the object of
that class.
class Student{
public static void main(String[] args) {
Runtime r = Runtime.getRuntime();
Runtime r1 = Runtime.getRuntime();
System.out.println(r == r1);//true because there is no new object is created
}
}
Singleton class

For any java class if we are allowed to create only one object then that class is said to be
singleton class.

Example- Runtime class, ActionSevlet class

We can create our own singleton class by using the following ways

1.By declaring constructor as private

2. By using factory method


class Test{
Static Test t;
private Test(){

}
public static Test getTest(){
if(t == null) {
t = new Test();
}
return t;
}
public static void main(String[] args) {
Test t1= Test.getTest();
Test t2= Test.getTest();
}
}

Interface

 It is a media between user and device.


 One class extends another class.
 One class implements another interface.

Class B implements I{
}

 One interface extends another interface.


Interface 1i extends 12{
}

 One class can’t extends more than one class

Class A extends B,C

{
}

Class A implements I1,I2,I3

 One class can extends another class and can implement any of interfaces simultaneously.

Class A extends B implements I1,I2,I3

Note- we can’t create object of interface.

 We can’t create object of interface.

Interface Demo{
Public static void main(…..){
Demo d = new Demo();
}
}

Interface variables
interface A{
int x = 10;
}
//-->public : we can access it from anywhere
//---> final : we can't change the value of variable
//--> static: It can't be local because variables of interface is by default public
//--> it can't be non static because we can't create object of interfce

Case1:
Final variable of interface must be initialized at the time of declaration.
interface A{
int x;//ce cuz it need to be initialized as we used final variable
}

Final variable value cannot be changed.


interface A{
int x = 10;
}
class B implements A{
public static void main(String[] args) {
x = 20;
System.out.println(x);// ce cuz final variable can't be changed
}
}

interface A{
int x = 10;
}
class C implements A{
public static void main(String[] args) {
int x = 20;
System.out.println(x);// 20
}
}

We can access interface variables with the help of interface name.

Interface method

All the methods present inside interface are by default public and abstract
interface A{
void m1(); // by default public and abstarct are there
public void m2(); // by default abstarct is there
abstract void m3(); // by default public is there
public abstract void m4(); //true
}

interface A{
void m1();
void m2();
}
class B implements A{
public void m1(){
System.out.println("hii");
}
public void m2(){
System.out.println("bye");
}
public static void main(String[] args) {
B b = new B();
b.m1();
b.m2();
}
}

To overcome the drawbacks of multiple inheritance, interface came into picture.


interface A{
void m1();
}
interface B{
void m2();
}
class C implements A,B{ //overcoming the multiple inheritance by implementing
public void m1(){
System.out.println("hii");
}
public void m2(){
System.out.println("bye");
}
}

Case1

If 2 interfaces containing methods with same signature and same return type then in
implementation class, we need to provide implementation for only once.
interface A{
void m1();
}
interface B{
void m1();
}
class C implements A,B{ // this is possible
public void m1(){
System.out.println("hii");
}

interface A{
void m1();
}
interface B{
void m1();
}
class C implements A,B{ // but this ain't possible in the same class
public void m1(){
System.out.println("hii");
}
public void m1(){
System.out.println("hii");
}

Case-2

If two interfaces containing methods with same return type but different signature then in
implementation class we need to provide implementation for both methods separately and
these methods are known as overloaded methods.
interface A{
void m1();
}
interface B{
void m1(int x);
}
class C implements A,B{
public void m1(){

}
public void m1(){

}
}

If 2interfaces containing methods with same signature but different return type then it is
impossible to provide implementation.
interface A{
void m1();
}
interface B{
int m1();
}
class C implements A,B{
public void m1(){
}
public int m1() {
return 10; //CE
}
}

From 1.8v default and static method were allowed inside interface.
class Demo implements A{
public static void main(String[] args) {
Demo d = new Demo();
d.m1();
A a1 = new Demo();
a1.m1(); // both are possible outputs and output will be default method
which will be printed twice
}
}

interface A{
default void m1(){
System.out.println("default method");
}
}

We can access static method inside an interface by interface name.

In 1.9 version private methods are also introduced inside interface.


class Demo implements A{
public static void main(String[] args) {
Demo d = new Demo();
d.m2(); // output will be private method

}
}

interface A{
default void m2(){
this.m1();
}
private void m1(){
System.out.println("it is a private method");
}
}

Q- We can create constructor in every java class including abstract class but not inside
interface.
We cannot create constructor inside interface because as the by default the variable in interface
is final, we can’t over ride it and can’t reinitialize it.

Static control flow

Static block is a block which will be executed automatically before the execution of main
method.
class A{
static{
System.out.println("static block");
}
public static void main(String[] args) {
System.out.println("main block");
}
}
// static block, main block

If there is more than one static block is present then execution will start from top to
bottom.
class A {
static {
System.out.println("static block");
}

public static void main(String[] args) {


System.out.println("main block");
}

static {
System.out.println("hey");
}
}
// static block, hey ,main block

Q- Can we print any statement to the console without using main method.

Rules

1. Identification of static members from top to bottom (1-6)


2. Execution of static variable assignment and static blocks from top to bottom .
3. Execution of main method.
class A{
static int i = 10;
static {
m1();
System.out.println("fsb");
}
public static void main(String[] args) {
m1();
System.out.println("main");
}

public static void m1(){


System.out.println(j);
}
static{
System.out.println("ssb");
}
static int j = 20; // 0 fsb ssb 20 main
}

Instance or non static block

Instance block is the block which will be executed whenever we create an object.
class Test{
{
System.out.println("Hiii");
}
public static void main(String[] args) {
Test t = new Test(); // Hiii, main
System.out.println("main");
}
}
By the help of object, we can call the instance or non-static block.

If more than one instance block is present then instance block will be executed from top to
bottom.
class Test{
Test(){
System.out.println("Hiii");
}
public static void main(String[] args) {
Test t = new Test(); // hii there, Hiii, main
System.out.println("main");

// instance block will get executed first and then constructor

}
{
System.out.println("hi there");
}
}

If constructor and instance block is present then first instance block will be executed.
class A{
int i = 10;
{
m1();
System.out.println("fib");
}
A(){
System.out.println("const");
}
public static void main(String[] args) {
A a1 = new A();
System.out.println("main");
A a2 = new A();
}
public void m1(){
System.out.println(j); // 0,fib,sib,const,main,0,fib,sib,const,main 0
}
{
System.out.println("sib");
}
int j = 20;
}

class A{
static{
System.out.println("fsb");
}

{
System.out.println("fib");
}
A(){
System.out.println("const");
}
public static void main(String[] args) { // fsb,ssb,fib,sib,const,main,fib,sib,const
A a1 = new A();
System.out.println("MAIN");
A a2 = new A();
}
static{
System.out.println("ssb");
}
{
System.out.println("sib");
}
}

Object type Casting

Converting from one type of object into another type of object is known as object type
casting.

Parent class reference can be used to hold it’s child class object(up casting).
object 0 = new String();

Runnable r = new Thread();


//Runnable ---> Interface
//Thread --->Implementation class
Interface reference can be used to hold it’s implementation class object.
A b = (c) d;
// A---> Object name/ interface name
// b --> Object Reference
// c --> Class name
// d ---> oBJECT REFERENCE
}

Step – 1(Compile time checking 1)

There must be some relation between C and A , otherwise we will get CE saying incompatible
types.
String s = new String("abc");
StringBuffer sb = (StringBuffer)s; //CE

Object 0 = new String();


StringBuffer sb = (StringBuffer)o; //possible

Step – 2(Compile time checking 2)

‘C’ must be either same as ‘A’ or child class of ‘A’ otherwise we will get CE saying
incompatible types.
object o = new String();
String sb = (StringBuffer)o;
Step – 3(Runtime checking)

Runtime object of ‘d’ must be either same or child class of ‘c’ otherwise we will get Runtime
exception saying ClassCastException.
Integer i = new Integer(10);
Number n = (Number)i; //possible scenario

Q- while object type casting whether a new object is created or not.

While object type casting no new object is created and the existing object will get a new
reference.
class Objtype {
void m1() {
System.out.println("a");
}
}
class E extends Objtype {
void m2() {
System.out.println("B");
}

public static void main(String[] args) {


Objtype e = new E();
//output will be a
((Objtype)e).m1();
}
}
Data Hiding
class Objtype {
int x = 777;
}
class B extends Objtype{
int x = 888;
}
class C extends B{
int x = 999;
C c1 = new C();
System.out.println(((Objtype)(B)c1.x))

Hiding our internal data in such a way that outside person should not access it, this is known as
data hiding.
Main advantage of data hiding is security.

We can achieve data hiding by declaring variable as private.

class test{
private int x = 10;
public static void main(String[] args) {

}
}

We can access private variables outside the class with the help of getter and setter method.

Getter is used to get the value of a private variable and it is also known as accessor method.

Settor method is used to set the value of a private variable and it is known as mutator method.

Example
class A{
private int id;
public void setid(int id1){
this.id = id1;
}
public int getid(){
return id;
}
public static void main(String[] args) {
A a1 = new A();
a1.setid(101);
System.out.println(a1.getid()); //output will be 101
}
}
//declared the setter’s return type as void in setter so that it won’t return any value and
in getter we declared return statement so that it will return the value.

class A{
private int id;
public void setid(int id1){
this.id = id1;
}
public int getid(){
return id;
}
}

class B {
public static void main(String[] args) {
A a1 = new A();
a1.setid(101);
System.out.println(a1.getid()); //output will be 101
}
}
example
class abstractclass{
private double salary; //data hiding
getSalary() {

}
setSalary() {
}
}

Abstraction

Hiding our internal implementation and providing functionality to the user is known as
abstraction.

How we are gonna achieve abstraction?

We can achieve abstraction by the help of abstract class and interface.

Advantages of abstraction

 Security
 Easy to use

Encapsulation
Wrapping or binding of data and the corresponding function in a single unit is known as
encapsulation.

Datavariables
Function Method

Variable + methods = encapsulation

Every java class containing variable and methods, known as encapsulated class.
Types of encapsulation

Polymorphism
One name with many forms is known as polymorphism.
Poly Many morph forms
There are two types of polymorphism:
1.compile time polymorphism /static polymorphism/ early bonding
Consists of – method overloading, method hiding
2.Runtime polymorphism /dynamic polymorphism /late bonding
Consists of – method overriding.

Java.lang package
Topics we gonna cover inside java.lang package
Object class
Methods of object class
1.toString()
2.hashcode
3.equals()
4.finalize()
5..clone()
String class
StringBuffer
StringBuilder
Wrapper classes
Autoboxing and AutoUnboxing.
 Every package is imported except java.lang package because by default it is
available in all java classes.

Object class
It is the supermost class in java because every class in java extends object
class either directly or indirectly.

A class is said to be direct child class of object class if it doesnn’t extend any
other class.

A class is said to be indirect child class of object class if it extends another


class.

Methods of object class


toString()
hashcode()
equals()
finalize()
clone()
getClass()
wait()
wait(long ms)
wait(long ms, int ns)
notify()
notifyAll()

toString()
It is used to convert any object into string.
It’s the string representation of any object.
Syntax
public String toString(){

program
package com.abc;
public class Test {
public static void main(String[] args) {
Test t = new Test();
String str = t.toString();
System.out.println(s1);
System.out.println(t.toString());
}
}

Whenever we try to print object reference, internally toString() will be called.

// package com.abc;
public class program {
public static void main(String[] args) {
program t = new program();
System.out.println(t); //package@3c679bde

} //same output as the upper prorgam


}

Whenever object class toString() method is called , output will always be in the
form of address.
class program{
String name;
program(String name){
this.name = name;
}
public static void main(String[] args) {
program p = new program("tushar");
System.out.println(p);//program@3c679bde
}
}

Whenever we want required output then we need to override toString() method in


our class.
class program{
String name;
program(String name){
this.name = name;
}
public String toString(){
return name; //output will be tushar
}
public static void main(String[] args) {
program p = new program("tushar");
System.out.println(p);
}
}

This is way to print the value rather than the address.


class program{
int roll;
program(int roll){
this.roll = roll;
}
public String toString(){
return roll+" ";
}
public static void main(String[] args) {
program p = new program(12);
System.out.println(p); // 12

}
}

In string class, StringBuffer class, StringBuilder class, all wrapper classes and
collection classes, toString() is overridden to given the required output.

Hashcode
A unique number is generated by jvm for each and every object that number is known as
hashcode.

It is used for searching operarion.

We can generate our own hashcode by overriding hashcode() in our class.

Syntax

Public int hashcode()

class Test{
public static void main(String[] args) {
Test t = new Test();
System.out.println(t.hashCode());// 1013423070
Test t2 = new Test();
System.out.println(t2.hashCode());// 428746855
}
}

Overriding hashcode
class program{
int roll;
program(int roll){
this.roll = roll;
}
public String toString(){
return roll+" ";
}
public int hashCode(){ //overriding hashcode
return roll;
}
public static void main(String[] args) {
program p = new program(12);
System.out.println(p); // 12
System.out.println(p.hashCode()); //12

}
}

Converting hashcode to hexadecimal


class program {
int roll;

program(int roll) {
this.roll = roll;
}

public int hashCode() { // overriding hashcode


return roll;
}

public static void main(String[] args) {


program p = new program(10);
System.out.println(p); // package@a , 10 will store in hexadecimal and then it will
convert it into hexadecimal
}
}
equals()

It is used to compare the objects.

It compares both the reference as well as content of the object.

Obect class equals() is always used to compare the reference of the object.

If we want to compare the content of the objects then we need to override equals().

Syntax

Public boolean equals(object 0)

To check content
class program {
int roll;

program(int roll) {
this.roll = roll;
}
public boolean equals(Object o){
int name1 = this.roll;
program s = (program)o;
int name2 = s.roll;
if(name1.equals(name2)){
return true;
}
else{
return false;
}
}
public static void main(String[] args) {
program p = new program(10);
program p1 = new program(10); //true

}
}

Shortest way to get the result


class program {
String roll;

program(String roll) {
this.roll = roll;
}
public boolean equals(program pp){
return this.roll.equals(pp.roll);
}
public static void main(String[] args) {
program p = new program("abc");
program p1 = new program("abc");
System.out.println(p.equals(p1)); //true

}
}

Finalize method

It is a method which is called by a garbage collector to destroy useless object.


An object without any reference is known as useless object.

WAYS TO MAKE AN OBJECT USELESS

1.

Test t1 = new Test()

Test t2 = new Test()

t1= null; eligible for garbage collector

t2= null;

If an object is no longer required then assign null to it’s reference variable then that object will
become useless, this process Is known as nullifying the reference variable.

2.

If an object is no longer required then assign a new object to it’s reference variable then the old
object will become useless , this process is known as re assigning the reference variable.

t1 = new Test();  1 object is eligible for garbage collector

t2 = t1; Now 2 objects are eligible for garbage collector or G.C

Object created inside a method

It is also known as island of isolation.


class A{
public static void m1(){
A a = new A(); // 2 objects are eligible for garbage collector because these are local
variables of m1 but after local block these will be useless, so these will be eligible for
garbage collector
A b = new A();
}
public static void main(String[] args) {
m1();
}
}

If there is more than on thread then you can’t guess the output, it can be anything, depends
upon the thread.

finalization
class A{
public static void main(String[] args) {
A a = new A();
a = null;
System.gc();
System.out.println("The end");
}
public void finalize(){
System.out.println("end of finalize method"); // the end and end of finalize method
}
}

by String class
class A{
public static void main(String[] args) {
String s = new String();

s = null;
System.gc();
System.out.println("The end");
}
public void finalize(){
System.out.println("end of finalize method"); // the end and end of finalize
}
}

If we call finalize method on particular class object then the corresponding class finalize
method will be executed.

String class finalize() has empty implementation.

If we will call the finalize method , then it will not able to destroy the useless object but
when we use the garbage collector it is going to destroy the useless objects.

We can call finalize() explicitly .

When we call finalize(), useless objects are not destroyed, it is only destroyed when
garbage collector calls finalize().

program
class Test{
public static void main(String[] args) {
Test t = new Test();
t.finalize();
t.finalize();
t =null;
System.gc();
System.out.println("end of main");

}
public void finalize(){
System.out.println("finalize method");
//output will be -finalize method will be printed twice , then end of main and again
finalize method
}
}

Java.lang.Stringclass

It is a sequence of characters and represented by “ “.

It is a predefined class name present in java.lang.package.

To perform any string operation java has provided us with the


following classes.

1.String class

2. stringBuffer class

3. stringBuilder class

String is immutable(not changeable or whose value can’t be changed)


class Test{
public static void main(String[] args) {
String s = new String("abc");
s.concat("def");
System.out.println(s);//abc
}
}

If we are trying to make any changes then a new object will be


created with that changes and it will have no reference variable.
class Test{
public static void main(String[] args) {
String s = new String("abc");
s = s.concat("def");
System.out.println(s);//abcdef, by storing in the reference variable we can manually
change the output
}
}

Case-2

In string class, equals method is overridden to do content


comparison.
class Test{
public static void main(String[] args) {
String s = new String("abc");
String s1= new String("abc");
System.out.println(s.equals(s1));
//Here we'll get true because equals method is overridden.
}
}

Case-3

There are 2 ways to create object of string class.

In SCP area

Whenever we create an object with the help of string literals then


only one object is created in scp(string constant pull) area and that
object will have the reference.
String s1 ="abc";
System.out.println(s1); // abc, string literals

Garbage collector can’t destroy the useless objects present inside


SCP area because it is restricted only to heap area.

In heap area

Whenever we create an object with the help of new keyword then two
object will be created in heap area, another in scp and that object
will have the reference in heap area.
String s = new String("abc");
System.out.println(s); // abc, by the helpof new keyword

rules
Object creation in scp area is optional , before creating new object
in SCP area first jvm goes scp area and checks whether an object with
the same content is present or not, if present no new object will be
created , if not then only a new object will be created.

Duplicate objects can’t be created inside of SCP area.


class Test{
public static void main(String[] args) {
String s = new String("abc");
String s2 = new String("abc");
String s3 = "abc";
String s4 = "abc";
System.out.println(s == s2);// false
System.out.println(s3 == s4);//true
}
}

class Test{
public static void main(String[] args) {
String s = new String("spring");
s.concat("fall");
s = s+"winter";
String s2 = s.concat("summer");
System.out.println(s);// springwinter
System.out.println(s2);//springwinter
}
}

Clone method

It is used to create duplicate of an object .

A class object can only be duplicated if that class is cloneable type


means that class should implement cloneable interface.

Clone always throws clone not supported exception.

Cloneable()
class Test implements cloneable{
int x = 10;
public static void main(String[] args) {
Test t = new Test();
System.out.println(t.x);
Test t1 = (Test)t.clone();
System.out.println(t1.x);
System.out.println(t == t1);
}

} //10, 10

String class constructor

1.String s = new String();

2. String s = new String (String literals)

Ex – String s = new String (“abc”);

3.String s = new String (String Buffer sb);

class Test{
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("abc");
String s = new String(sb);
System.out.println(s);
} //abc

4.String s= new String (char[]ch)


class Test{
public static void main(String[] args) {
char[] ch {'a','b','c'};
String s = new String (ch);
System.out.println(s);
} // abc

5.String s = new String(byte[]b)


class Test{
public static void main(String[] args) {
byte[]b = {100,101,102};
String s = new String(b);
System.out.println(s);
} // def

1.public charAt (int index)

It returns the character present at specified index.


class Test {
public static void main(String[] args) {
String s = "abcdef";
System.out.println(s.charAt(0));//a
System.out.println(s.charAt(3));//d

2.public String concat(String s);

3.Public Boolean equals (Object 0);

4. Public boolean equlasIgnoreCase(String s);


class Test {
public static void main(String[] args) {
String s = "abc";
System.out.println(s.equals("abc"));//TRUE
System.out.println(s.equals("ABC"));//FALSE
System.out.println(s.equalsIgnoreCase("ABC"));//TRUE

5.public string substring(int begin);

6.public String substring(int begin, int end);


class Test {
public static void main(String[] args) {
String s = "abcdef";
System.out.println(s.substring(2)); //cdef
System.out.println(s.substring(2,5));//cde
System.out.println(s.substring(2,2)); //none

7.public int length();


class Test {
public static void main(String[] args) {
String s = "abcdef";
System.out.println(s.length()); //6

8.public String replace(char old, char new);


class Test {
public static void main(String[] args) {
String s = "ababababababa";
System.out.println(s.replace('a', 'b')); //bbbbbbbbb
System.out.println(s.replace('b', 'a')); //aaaaaaaaa
System.out.println(s.replace("ab", "z")); //zzzzzza
}

8.public string touppercase() and tolowercase();


class Test {
public static void main(String[] args) {
String s = "abababCAababa";
System.out.println(s.toUpperCase()); // ABABABABCAABABA
System.out.println(s.toLowerCase());//abababcaabab
}

9. public string trim().


It removes the blank space from the beginning and form the end but
not from the middle.
class Test {
public static void main(String[] args) {
String s = " Ryoiki Tenkai";
System.out.println(s.trim()); //ryoiki tenkai

10. public indexOf ()

Returns the index of specified chosen characters.


class Test {
public static void main(String[] args) {
String s="abcdeaf";
System.out.println(s.indexOf("d"));//3
System.out.println(s.indexOf("z")); //-1
System.out.println(s.lastIndexOf('a')); //5
System.out.println(s.indexOf("cd")); //2
System.out.println(s.indexOf('c','d')); //-1
System.out.println(s.lastIndexOf('a', 4));//0

11.compareTo()
class Test {
public static void main(String[] args) {
System.out.println("a".compareTo("b")); //-1
System.out.println("a".compareTo("a")); //0
System.out.println("A".compareTo("a")); //-32

It returns +ve number if a comes before b.

Returns –ve if b comes before a.


Returns 0 is a is same as b.

foreach
class program {
public static void main(String[] args) {
String s = "abcd";
System.out.println(s);
char[]ch = s.toCharArray();
for(char x :ch){
System.out.println(x);// abcd
}

}
}

Split()

It splits the string on the basis of a particular separator.

It is used to convert any string into substring on the basis of some


separator, it’s return type is string[].
class program {
public static void main(String[] args) {
String s = "Hey there";
String[] s1 = s.split("");
for (String x:s1){
System.out.println(x); // hey there, but will be in different different lines
}

Q.write a program to to find the no of character present inside a


string without using length().
public class program {

public static void main(String[] args) {


int length=0;

String s = "Tushar";
for (char c1 : s.toCharArray())
length++;
System.out.println("Length of String is : "+length);

}
}
Q2. Wap to find the no of words present inside a string.
public class program {

public static void main(String[] args) {


int length=0;

String s = "Tushar";
// String[] s1 = s.split("");
for (String x : s.split("x")) {

length++;
}

System.out.println("Length of String is : "+length);

}
}

Q3. Write a program to print the words of a string which is of even


length
public class program {

public static void main(String[] args) {

String s = "Tushar sahoo Ryoiki tenkai";


String[] s1 = s.split(" ");
for( int i = 0; i < s1.length; i++){
String s2 = s1[i];
String[] s3 = s2.split("");
if(s3.length % 2 == 0){
System.out.println(s2);
}

}
System.out.println("Length of String is : " );

}
}

How to modify the immutable


class Test {
private int x;

Test(int x) {
this.x = x;

public Test modify(int x1) {


if (this.x == x1) {
return this;
} else {
return new Test(x1);
}

public static void main(String[] args) {


Test t1 = new Test(10);
Test t2 = t1.modify(10);
Test t3 = t1.modify(20);
System.out.println(t1 == t2); // output will be true
System.out.println(t1 == t2);

}
}

Final vs immutability

Final modifier is applicable for variables

Immutability concept is applicable for object.

If a reference variable is final, we can make some changes in the


object but we can’t reassign a new object to that reference variable.
class Test {
public static void main(String[] args) {
final StringBuffer sb = new StringBuffer();
sb.append("def");
System.out.println(sb); //def
// sb = new StringBuffer("xyz"); this is not possible
}
}

StrinBuffer

If the content will change frequently then never go for string object
because for every change it will create a new object internally.

To handle this type of requirement we should go for StringBuffer


Object.

The main advantage of stringbuffer over string is we can make changes


in some object.
class Test {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
System.out.println(sb.capacity());
sb.append("1234567891234567");
System.out.println(sb); //16
sb.append("abcd");
System.out.println(sb.capacity());//34
}
}

2.stringBuffer sb-new StringBuffer(int initialCapacity)


class Test {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer(24); // by assigning 24 , it will only take 24
spACE FOr characters
System.out.println(sb.capacity());
sb.append("1234567891234567");
System.out.println(sb); //16
sb.append("abcd");
System.out.println(sb.capacity());//34
}
}
3.StringBuffer sb- new StringBuffer(String s);

Capacity = s.length()+16;
class Test {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("abcd");
System.out.println(sb.capacity()); //20

}
}

Method of stringBuffer

1.public int length()  returns the number of characters present.

2. Public int capacity()  Returns the total number of characters it


can hold.

3. public char charAt (int index);

4.public void setCharAt(int index, char ch);

5.public stringBuffer delete( int begin, int end);


class Test {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("abcd");
System.out.println(sb.delete(2, 3)); //abd

}
}

6.Public stringBuffer deleteCharAt (int index);

7.Public stringBuffer reverse();


class Test {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("abcd");
System.out.println(sb.reverse());//dcba

}
}
Note - Every method is present inside stringBuffer is synchronized
means at a time only one thread allowed to operate stringBuffer
object.

StringBuilder

It is exactly same as stringBuffer (in methods in constructor) except


that stringBuilder is non-synchronized.

Wrapper classes

Wrapping primitive data values into object is known as wrapper class.

Primitive data type

byte, short, int, long, float, double, boolean, char

Wrapper class

Byte, Short, Integer, Long, Float, Double, Boolean, Character

Wrapper classes are immutable.

Constructors

Nearly all wrapper classes contains 2 types of constructor.

1. With primitive type as an argument.


2. String type as an argument.

Int program
class Test {
public static void main(String[] args) {
Integer i = new Integer(10); // even tho it allows string but we still can't print
characters except numbers as parameter.
System.err.println(i); //float also takes up double as an argument, character only
takes up character/primitive as an constructor.

}
}

Boolean
If we are passing primitive type as an argument to the Boolean class
object, the only allowed arguments are true and false. Here it is
case sensitive.

allowed

Boolean b = new Boolean(false)

Boolean b = new Boolean(true) // this is true

If it is other than true then it is going to give false.

If we are passing string type as an argument to the Boolean class


object then except true everything will be treated as false and here
it is case insensitive.
class Test{
public static void main(String[] args) {
Boolean b1 = new Boolean("yes");
Boolean b2 = new Boolean("no");
System.out.println(b1.equals(b2)); //true
}
}

Utility methods(methods of wrapper classes)

1.valueOf()

2.xxxvalue()

3.parseXxxx()

4.toString()

1.valueOf()

This method is used to create wrapper class from the given primitive
and string.

It is used to convert any primitive data type into it’s corresponding


wrapper class object.

Form-1
Public static wrapper valueOf (String s)

This form is present in every wrapper class except character class


class Test{
public static void main(String[] args) {
Interger I = Integer.valueOf("10");
Double d = Double.valueOf("10.5");
Boolean b = Boolean.valueOf("abc");
System.out.println(I);
}
}

Form-2

Public static wrapper valueOf(primitive p)

This form is present in every Wrapper classes including character


class.
class program{
public static void main(String[] args) {
Integer I = Integer.valueOf(10);
Double d = Double.valueOf(10.5);
Boolean b = Boolean.valueOf(abc);
System.out.println(I);
}
}

2.XXXAValue

We can use this method to convert wrapper class object into it’s
corresponding primitive.
class program{
public static void main(String[] args) {
Integer I = new Integer(130);
System.out.println(I.byteValue());//-126
System.out.println(I.shortValue());//130
System.out.println(I.intValue());//130
System.out.println(I.longValue());//130
System.out.println(I.floatValue());//130.0
System.out.println(I.doubleValue());//130.0

}
}
charValue()

This method is present in character class.

booleanValue()  present in Boolean class.


class program{
public static void main(String[] args) {
Character c = new Character('a');
char ch = c.charValue();
System.out.println(ch); //a
Boolean b = new Boolean(true);
boolean b1= b.booleanValue();
System.out.println(b1); //true

}
}

class program{
public static void main(String[] args) {
Character c = new Character('a');
char ch = c.charValue();
System.out.println(ch); //a
Boolean b = new Boolean(true);
boolean b1= b.booleanValue();
System.out.println(b1); //true

}
}

3.parseXxx()

This method is used to convert String into wrapper class object

Autoboxing

Automatic conversion of primitive data type into it’s corresponding


wrapper class object by compiler is known as autoboxing.

Integer x = 10;

Internally autoboxing concept is implemented by using valueOf().

Autounboxing
Automatic conversion of wrapper class object into it’s corresponding
to primitive data type by compiler is known as autounboxing.
Internally, autounboxing concept is implemented by using XxxValue().

Integer I = new Integer(10);

Int x = I;
class program{
static Integer I = 10;//autoboxing
public static void main(String[] args) {
int i = I;//autounboxing
m1(i); //boxing
}
public static void m1(Integer K){
int x = k; //unboxing
System.out.println(x);
}

Whenever we perform auto-unboxing on null reference, it will always


get null pointer exception.
class program{
static Integer I;// VALUE HERE IS NULL
public static void main(String[] args) {
int i = I;//ERROR SAYING, NULL POINTER EXCEPTION DUE TO CONVERTING INTO AUTOUNBOXING

class HelloWorld {
public static void main(String[] args) {
Integer x = 10;
Integer y = x;
x++;
System.out.println(x); //11
System.out.println(y);//10
}
}
Multi dimensional array

Arrays of Array

It saves memory, it only takes up the required space needed.

S1 65 35 100 60
S2 42 60
S3 70 60 80
S4 10
S5 20

To declare 2 dimesnsional array

int [][]x = new int[3][2];

here [3] is the base size(first array size) and it will look like
this.

X [0,1,2];

Int[2]it will act as sub array of array.

To give the fixed value to an sub array we have to mention the value
in sub-array but if we don’t do then it will take the required sub
array length that it requires.

int [][]x = new int[3][2];// fixed sub array

int [][]x = new int[3][];// sub array length which is not fixed.

x0 = new int [3][]

x[0][0] = new int[1];

x[0][1] = new int [2]

x[0][2] = new int [3]

x1 = new int[2][2]

Q- write a program to check the out put of

Int []x = new int [3];


Sopln(x);

Sopln(x[0]);
class program{
public static void main(String[] args) {
int[]x = new int[3];
System.out.println(x); // it will give the address
System.out.println(x[0]); //0
}
}

Q-write a program to check the value of


int[][]x = new int[3][2];

System.out.println(x);// address

System.out.println(x[0]); // address
System.out.println(x[0][0]); //0

Whenever we create an array all it’s element is by default


initialized.

If we are not satisfied with those default values then we can replace
with our customized value.

Defaultly

class program{
public static void main(String[] args) {
int[]x = new int[3];
System.out.println(x[0]); // 0
System.out.println(x[1]);//0
System.out.println(x[2]);//0
}
}

By assigning
class program{
public static void main(String[] args) {
int[]x = new int[3]; // known as creation
x[0] = 10;
x[1] = 20; // known as initialization
x[2] = 30;
System.out.println(x[0]); // 10
System.out.println(x[1]);//20
System.out.println(x[2]);//30
}
}

To perform both declaration ,creation and initialization in a single


line

int [] x= {10,20,30};

To perform both declaration ,creation and initialization in a 2


dimensional array

int [][] a = {{10,20,30},{ 40,50}};

length vs length()

length

it is a final variable and applicable only for Array.

It represents size of an array.


class program {
public static void main(String[] args) {
int [] x = new int[3];
System.out.println(x.length); // will give length
System.out.println(x.length()); // Ce
}
}

length()

It is a final method applicable for string.

Return the number of characters present in a string.


class program {
public static void main(String[] args) {
String s = "Ryoiki tenkai";
System.out.println(s.length()); //13
System.out.println(s.length); //CE
}
}

class program {
public static void main(String[] args) {
String[] s = {"a","aa","aaa"};
System.out.println(s.length); //3
System.out.println(s.length()); //CE
System.out.println(s[0].length);//CE
System.out.println(s[0].length());//1
}
}

Anonymous Array

Sometimes we can create an array without any name known as anonymous


array.
new int []{10,20,30,}; //valid

new int [][]{{10,20,30,},{40,50}}; //valid

example
class HelloWorld {
public static void main(String[] args) {
System.out.println(sum(new int[] {10,20,30}));
}
public static int sum(int [] x){
int total = 0;
for (int y:x)

total += y;
return total; // output will be 60

}
}
IN CASE OF PRIMITIVE ARRAYS AS ARRAY ELEMENENTS ANY TYPE IS ALLOWED
WHICH CAN BE PROMOTED TO DECLARED TYPE.
class HelloWorld {
public static void main(String[] args) {
int [] x = new int[5];
x[0]= 10; //valid
x[1] ='a'; //valid

byte b = 20;
x[2] = b; // valid

short s = 30;
x[3] = s; // valid

x[4] = 10L // not valid

}
}

In case of object type arrays as array elements we can provide either


declared type objects or it’s child class object.
class HelloWorld {
public static void main(String[] args) {

object[] a = new object[5];


a[0] = new object();
a[1] = new String("abc");
a[2] = new Integer(10);
}

class HelloWorld {
public static void main(String[] args) {

Number [] n = new Number[5];


n[0] = new Integer(10);
n[1] = new Double(10.5);
n[2] = new String("abc"); // not valid
}
}

Element level promotion are not applicable at array object level.

We can’t convert char array into an int array.

Case – 2

In case of object type array, child type array can be assigned to


parent type array.
String [] s = {"a","b","c"};
object[] o = s;

class HelloWorld {
public static void main(String[] args) {

int [] a ={10,20,30};
int []b ={40,50};
a = b;
System.out.println(a[0]); //output will be 40
}
}

cConclusion- here a will point to b, hence the first value inside be


is 40 and when we gonna print a[0] , it’ll print 40 as the output.
class HelloWorld {
public static void main(String[] args) {
int [][] a = new int[2][];
a [0] = new int [2][3];// not possible
a[0] = 10; //ce
a[0] = new int[3];// possible
}
}
Find the number of useless object
class HelloWorld {
public static void main(String[] args) {
int [] [] a = new int[2][];
a[0] = new int [2][3];
a[0] = 10;
a[0] = new int[3]; // output will be 6
}
}

Exception

An unwanted, unexpected event that disturbs the normal flow of the


program is known as exception.

The main objective of exception handling is normal termination.

Exception Handling

Providing an alternative way is the concept of exception handling.

Runtime stack mechanism

For every thread jvm will create separate stack at the time of thread
creation.

All method calls performed by that thread will be stored in that


stack each entry stack is known as “ activation record” or “ stack
frame”.

After completing every method call jvm removes the corresponding


entry from the stack after completing all method calls jvm destroys
the empty stack and terminates the program.
class A{
public static void main(String[] args) {
m1();
}
public static void m1(){
m2();
}
public static void m2(){
System.out.println("hii");
}
}

Default exception handling in java

Exception has three parts – 1. Name, 2. Description, 3. Location.


If the jvm won’t able to find the code for exception then the jvm
will hand it over to the default exception handling (Dec)

Exception hierarchy

Q- What is the difference between error and exception.


Ans- Error is a problem in java application.

There are two types of errors in java.

 Compile time errors


 Runtime errors

 Compile time error


These are problems identified by the compiler at compilation
time.
In general, There ARE 3 TYPES of compile time error.

1.Lexical Error
MIStakes in keywords

Int I = 10;  valid


nit I = 10; invalid

2.syntax error
Grammatical Mistakes or syntactical mistakes.

Ex- int I = 10;  valid


I int = 10; invalid

3.semantic error
Providing operators in between in compatible types.

Ex- int I = 10;


Int j = 20;
Int k = i+j;  valid

Ex- int I = 10;


Boolean b = true;
Char c = I +b ; invalid

Note- Some other are generated by compiler when we violate JAVA


rules and regulations in java applications.
Ex- Unreachable statements, Variable might not have been
initialization, possible loss of precision.
Runtime errors
These are the problems for which we are unable to provide
solutions programmatically and these errors are not identified
by the compiler and these errors are occurred at runtime.

Ex – Insufficient main memory


Unavailability of Io componets
Stack overflow

Exception are caused by our program and it’s recoverable.

Errors are not caused by our program and these are due to lack of
resources and these are non recoverable.

There are 2 types of exceptions

1. Checked exception
2. Unchecked exception

Checked exception are those exceptions which are checked by


compiler.

Unchecked exceptions are not checked by compiler.

Whether it is checked or unchecked both exceptions occur at


runtime.

RuntimeException and it’s child classes, error and it’s child


classes are unchecked exception except these all are checked
exception.

Customized Exception Handling


Try
The statement which may rise an exception is known as risky code
and this code must be written inside of try block.
Try block doesn’t handle the exception, it just highlight the
code which may rise an exception.
Catch block is used to handle the exception.
Without try block we can’t write catch block.

Without try catch block

class HelloWorld {
public static void main(String[] args) {
System.out.println("Hi");
System.out.println(10/0);
System.out.println("bye"); //output will be only Hii
}
}

With try & catch block

class A{
public static void main(String[] args) {
System.out.println("HII");
try{
System.out.println(10/0); // risky code should be inside of try block
}
catch(ArithmeticException e){

}
System.out.println("BYE"); // Hii and bye will be the output, we can also put any
required statement inside of catch block
}
}

Flow control in try catch

Note
Case-1 (if there is no exception)
If there is no exception in try block then catch block will be
ignored.

class A{
public static void main(String[] args) {
try{
System.out.println("1");
System.out.println("2");
System.out.println("3");
}
catch(ArithmeticException e){

}
System.out.println("BYE"); //output will be 1,2,3,bye
}
}

Case-2 (if an exception rises at statement 2 and not handled)

class A{
public static void main(String[] args) {

try{
System.out.println("1");
System.out.println(10/0);
System.out.println("3");
}
catch(ArithmeticException e){

}
//output will be 1
}
}

Case-3 (If an exception rises at statement 2 and handled)

class A{
public static void main(String[] args) {

try{
System.out.println("1");
System.out.println(10/0);
System.out.println("3");
}
catch(ArithmeticException e){
System.out.println("rYOIKI");
}
//1, RYOIKI
}
}
Note
If there is an exception rises in try block then rest of try
block won’t be executed irrespective of whether exception in
handled or not.

Case-4
If an exception rises at statement-4

class A{
public static void main(String[] args) {

try{
System.out.println("1");
System.out.println("2");
System.out.println("3");
}
catch(ArithmeticException e){
System.out.println("4");
}
//1,2,3
}
}
CATCH block will be ignored.

Methods to print exception information

Throwable class provides the following methods to print exception


information.

1.printStackTrace()

2. toString()

3. getMessage()

Example

class A {
public static void main(String[] args) {

try {
System.out.println(10 / 0);
} catch (Exception e) {
e.printStackTrace(); // will show the Name, description and Location
System.out.println(e.toString()); // will show the name and description
System.out.println(e.getMessage()); //only the description will be shown
}

}
}

Try with multiple catch block

Try with multiple catch block is allowed but order of catch block is
important.

It should be from child to parent but not from parent to child.

Child – parent relationship


class A {
public static void main(String[] args) {

try {
System.out.println(10 / 0);
} catch (ArithmeticException e) {
System.out.println("hii");
} catch (Exception e) {
System.out.println("bye");
}
//Output will be -hii
}
}

Parent-child relationship
class A {
public static void main(String[] args) {

try {
System.out.println(10 / 0);
} catch (Exception e) {
System.out.println("hii");
} catch (ArithmeticException e) {
System.out.println("bye");
}
// unreachable
}
}

Finally Block

It is a block which will be executed every time irrespective of


whether an exception rises or not or whether an exception is being
handled or not.

Case-1

If no exception rises
class A {
public static void main(String[] args) {

try {
System.out.println("try");
} catch (ArithmeticException e) {
System.out.println("catch");
} finally {
System.out.println("finally");
}
//Output will be -hii, finally. catch block will be ignored
}
}

Case-2

If an exception rises and handled


class A {
public static void main(String[] args) {

try {
System.out.println("try");
System.out.println(10/0);
} catch (ArithmeticException e) {
System.out.println("catch");
} finally {
System.out.println("finally");
}
//Output will be -hii,catch, finally
}
}

Case-3

If an exception rises but not handled


class A {
public static void main(String[] args) {

try {
System.out.println("try");
System.out.println(10/0);
} catch (NullPointerException e) {
System.out.println("catch");
} finally {
System.out.println("finally");
}
//Output will be -hii,finally, exception
}
}

Return vs finally

If return statement is present inside try catch, finally block then


priority will be given to finally block.

Before the execution of return statement present inside try block


first it goes to finally block and then comes back.
class A {
public static void main(String[] args) {
System.out.println(m1());

public static int m1() {


try {
return 777;
} catch (Exception e) {
return 888;
} finally {
return 999; //output will be 999
}
}
}
class A {
public static void main(String[] args) {
System.out.println(m1());

public static int m1() {


try {
System.out.println("try");
System.out.println(10/0);

} catch (NullPointerExceptionException e) {
System.out.println("CATCH");
} finally {
System.out.println("FINALLY"); // TRY, FINALLY , ERROR
}
}
}

There is only one situation where finally block won’t be executed


that is wehenever we are using system.exit(0);
class A {
public static void main(String[] args) {

try {
System.out.println("try");
System.out.println(10/0);

} catch (ArithmeticException e) {
System.out.println("CATCH");
System.exit(0); //TRY, CATCH
} finally {
System.out.println("FINALLY");
}
}
}

Final vs finally vs finalize()

final

Final is a modifier which is applicable for variables, methods and


classes.
If a variable is declared as final then we can’t change that value of
that variable =.

If a method is declared as final then we can’t override that method.

If a class is declared as final then we can’t inherit it.

Finally

Finally is a block which is always associated with try block and it


will be executed irrespective of whether an exception is rising or
not, whether exception is being handled or not.

Finally block is a block which will be executed to perform code clean


up activity.

Finalize()

finalize is a method which is always invoked by garbage collector to


perform clean up activities.

Throw keyword

It is used to create exception object intentionally.

It is used to create customized exception object.

It is used to handover exception object to jvm.


class A {
public static void main(String[] args) {
throw new ArithmeticException(" / by zero");
}
}

Why should we create object of exception?


class A {
static ArithmeticException e;
public static void main(String[] args) {
throw e; // null pointer exception
}
}

Enhances the security.

Throws keyword

It is the second way of handling the exception.

Throws keyword can only handle checked exception.


class program{
public static void main(String[] args) throws InterruptedException {
System.out.println("hiii");
Thread.sleep(3000);
System.out.println("bye");
}
}

It will delay the second output by 3 seconds.

If we want to use our user defined class as an exception class then


we have to make our user defined class as the child class of
throwable or it’s type.
class program{
public static void main(String[] args) throws ArithmeticException {
System.out.println(10/0); //ce
}
}

class program extends Exception{

public static void main(String[] args) throws ArithmeticException {


System.out.println(10/0);
}
}

Drawbacks of array
1. Fixed in size
2. It contains only homogenous elements
3. No in built functions to perform operations to overcome this
problems collection framework came into picture.
Advantage of collection framework
1. Growable in nature
2. It contains heterogenous elements
3. It has inbuilt functions

Collection

Whenever we want to represent a group of individual objects as a


single entity then we should go for collection.
It is consists of interfaces

 List
 Set
 Queue

Methods of collection interfrace


1.boolean add(Object o)
It is used to add elements.
It returns true if successfully added and returns false if not
added successfully.

How to add elements


import java.util.ArrayList;
class A {

public static void main(String[] args) {


ArrayList i = new ArrayList();
i.add("aa");
i.add(10);
i.add(true);
System.out.println(i); //[a,10,true] output
}
}

Boolean addAll(collection c)
It adds a group of elements at a time.
import java.util.ArrayList;
class A {

public static void main(String[] args) {


ArrayList i = new ArrayList();
i.add("aa");
i.add(10);
i.add(true);
System.out.println(i); //[a,10,true] output
ArrayList ii = new ArrayList();
ii.add("hii");
ii.add("bye");
ii.addAll(i);
System.out.println(ii); // to concat or add all

}
}

3.boolean remove(object o)
import java.util.ArrayList;
class A {

public static void main(String[] args) {


ArrayList i = new ArrayList();
i.add("aa");
i.add(10);
i.add(true);
i.remove("aa");// it will remove "aa"
System.out.println(i); //[10,true] output

}
}
Boolean removeAll(collection c)
It will remove all the elements.

5.boolean retainAll(collection c)

removes all the elements except present in c.


import java.util.ArrayList;

class A {

public static void main(String[] args) {


ArrayList i = new ArrayList();
i.add("aa");
i.add(10);
i.add(true);
ArrayList l = new ArrayList();
l.add("hii");
l.add("bye");
l.addAll(i);
l.retainAll(i);
System.out.println(l);// aa,10,true , it will remove all the elements of l

}
}

6.void clear()
Removes all the elements

7.boolean contains()
import java.util.ArrayList;

class A {

public static void main(String[] args) {


ArrayList i = new ArrayList();
i.add("aa");
i.add(10);
i.add(true);
System.out.println(i.contains("aa"));// true will be the output as contains matched
the content

}
}
8.boolean containsAll(collection c);

9.Boolean isEmpty()
import java.util.ArrayList;

class A {

public static void main(String[] args) {


ArrayList i = new ArrayList();
i.add("aa");
i.add(10);
i.add(true);
System.out.println(i.isEmpty());// false as it is not empty
i.clear();
System.out.println(i.isEmpty());//true as it is empty

}
}

10.int size()
Says about number of elements is present.
Import java.util.ArrayList;

class A {

public static void main(String[] args) {


ArrayList I = new ArrayList();
i.add(“aa”);
i.add(10);
i.add(true);
System.out.println(i.size()); //3, given the size

}
}

11. toArray()
Converts it into array
import java.util.ArrayList;
class A {

public static void main(String[] args) {


ArrayList i = new ArrayList();
i.add("aa");
i.add(10);
i.add(true);
Object [] a = i.toArray();
for (Object x : a) {
System.out.println(x); //aa,10,true
}

}
}

12.Iterator iterator();
Cursor of java.

List
If we want to represent a group of individual objects as a
single entity where duplicates are allowed and insertion order
is preserved then we should go for list. index plays important
role in list.
List is the child interface of collection.

1. Duplicate – inserting same element more than one time.


Duplicate case can be differentiate with the help of index.

2. Insertion order is preserved – the order in which elements are


inserted in the same order we will get output.
Insertion operation is also preserved with respect to index.

List interface methods


1.boolean add(int index, object o);

To add an element at a specified index.


import java.util.ArrayList;

class program{
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add(10);
l.add("aaa");
l.add("bbb");
l.add("ccc");
l.add(2,"ddd");
System.out.println(l); //[10,aaa,ddd,bbb,ccc]
}
}

3.object get(int index)


import java.util.ArrayList;

class program{
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add(10);
l.add("aaa");
l.add("bbb");
l.add("ccc");
l.add(2,"ddd");
System.out.println(l.get(3)); //[bbb]
}
}

4.Object remove(int index);

It removes the element present at specified index.


import java.util.ArrayList;

class program{
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add(10);
l.add("aaa");
l.add("bbb");
l.add("ccc");
l.remove(1);
System.out.println(l); //[10,bbb,ccc]
}
}

5.Object set(int index, object new);

import java.util.ArrayList;

class program{
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add(10);
l.add("aaa");
l.add("bbb");
l.add("ccc");
l.set(1,"hi");
System.out.println(l); //[10,hi,bbb,ccc]
}
}

Replaces the element by new object.

6.int indexOf(object o);

import java.util.ArrayList;

class program {
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add(10);
l.add("aaa");
l.add("bbb");
l.add("ccc");

System.out.println(l.indexOf("aaa")); // 1

}
}
Returns the index of an object.

ArrayList

The underlying data structure is resizable array or growable array.


Duplicates are allowed.

Insertion order is preserved.

Null insertion is possible.

It implements Serializable, cloneable, and randomaccess interface.

Heterogenous elements are allowed.

Constructor

Arraylist l = new ArrayList();

The initial capacity of ArrayList is 10 but if we insert more element


then the new capacity will be , new capacity = (initial capacity *
3/2)+1;

While creating new arrayList it also takes extra unnecessary


space, so to overcome that we have .

AL l = new AL(int inticap);


AL l = new AL(25);

3.AL l = new AL(collection C);

import java.util.ArrayList;

class program {
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add(10);
l.add("aaa");
l.add("bbb");
l.add("ccc");
System.out.println(l);
ArrayList li = new ArrayList(l);
li.add(10);
li.add(20);
System.out.println(li); //[10,aaa,bbb,ccc,10,20]
}
}
To check whether it is Serializable, Clonebale and RandomAccess
import java.io.Serializable;
import java.util.ArrayList;
import java.util.RandomAccess;

class oos{
public static void main(String[] args) {
ArrayList l = new ArrayList();
System.out.println(l instanceof Serializable); // true
System.out.println(l instanceof Cloneable); //true
System.out.println(l instanceof RandomAccess); //true
}
}

Every method present inside ArrayList is non-synchronized.

Getting the synchronized version of ArrayList

Collections class defines the following methods to make array list


synchronized .

Public static List synchronizedList(list i);

Difference between collection and collections is that collection is


an interface and collections is the class.

ArrayList I = new ArrayList();

List li = Collections.synchronizedList(I);

Inon synchronized

li  synchronized

ArrayList is best suitable if our frequent operation is retrieval


operation and it is the worst choice if our frequent operation is
insertion or deletion due to internal shifting.

Linked list

To overcome the drawback of ArrayList , linked list came into play.

The underlying data structure is double LinkedList.


The drawback of LinkedList is that the data retrieval is hard

If we get null then it means the node ends there only.

The first part/ starting part of a node is known as head and the last
part is known a tail.

public class Node{


int value;
Node next;
}

class hi{
Node head;
Node tail;
int size;
Node createLL(int data){
Node node = new node();
node.value = data;
node.next=null;
head = node;
tail=node;
size = 1;

Duplicates are allowed.

Insertion order is presered.

Null insertion is possible.

It implements Serializable, cloneable, but not RandomAccess

LinkedList methods

1.void addFirst(Object o);

2.void addLast(Object o);

3.Object getFirst();

4. Object getLast();

5.Object removeFirst();

6.Object removeLast();

Note - we can apply these methods on LinkedList only.


import java.util.LinkedList;

class program{
public static void main(String[] args) {

LinkedList i = new LinkedList();


i.add(10);
i.add("aaa");
i.add("bbb");
i.add(true);
System.out.println(i);
i.addFirst("hii");
System.out.println(i);

}
}

Vector

The underlying data structure is resizable array.

Duplicates are allowed.

Insertion order is preserved.

Hetrogenous elements are allowed.

Null insertion is possible.

It implements Serializable, cloneable and RandomAccess.

Note – Every method is present inside vector is synchronized.

Constructor

Vector v = new Vector();

Default capacity = 10;

New capacity = initial capacity * 2;

1.vector v = new Vector(int initial capacity);

2. Vector v = new Vector(collection c);


import java.util.Vector;

class program{
public static void main(String[] args) {
Vector v = new Vector();
System.out.println(v.capacity());
for(int i = 0; i<10;i++){
v.add(i);
}
System.out.println(v);
System.out.println(v.capacity());
v.add("aaa");
System.out.println(v.capacity());
}
}

Methods of vector
1. To add elements we have addElements (Object o)
2. To remove object we have removeElement(Object o);
3. To remove all the present object we have removeAllElement();
4. To remove object particular object then we have
removeElementAt(int index);
5. To get the object, we have
elementAt(int index);
firstElement();
lastElement();

6.other methods

Size();

Capacity();

Enumeration elements();
import java.util.*;

class oos2{
public static void main(String[] args) {

Vector v = new Vector();

System.out.println(v.size());

System.out.println(v.capacity());

v.addElement("Hello");

v.addElement (100.3345);

v.addElement (null);

v.addElement (12300);

v.addElement('a');

v.add("home");

System.out.println(v);

System.out.println(v.removeElement(12300));

System.out.println(v);
v.removeElementAt(0);

System.out.println(v);

System.out.println(v.elementAt (1));

System.out.println(v.firstElement());

System.out.println(v.lastElement());

System.out.println(v.size());

System.out.println(v.capacity());

v.removeAllElements();

System.out.println();
}
}

Stack

It is the child class of vector.

Whenever we want to go for LIFO(last in first out) order execution


then we will go for stack.

Constructor

1. Stack s = new Stack();


Methods

1.Object push(Object o);

To add object in the stack

2. Object pop();

This method will be used to remove the top most object from the
stack.

3.Object peek();

This method will return the top most element from the stack without
removing .

4.boolean empty();
This method will return true if the stack is empty otherwise false.

5.Int search(object o);

this method will return the offset of the element if available


otherwise it will return -1.

Jvm will check through offset value.


import java.util.Stack;
class oos2 {
public static void main(String[] args) {
Stack s = new Stack();
s.push("hi");
s.push("bye");
s.push("sleep");
s.push("night");
s.push("ryoiki");
s.push("tenkai");
System.out.println(s.peek()); // will return tenkai
System.out.println(s.pop()); // will remove tenaki
System.out.println(s.empty()); // false
System.out.println(s.search("night")); // 2 , it will return the offset value

}
}

Cursor of java

There are 3 cursors presents in java.

1.Enumeration

2.iterator

3.listIterator

Q- why we will use cursor

Ans- if we want to get object one by one from any collection’s


implemented class then we will go for cursors of java.

*These all are interfaces.

Enumeration
If we want to get object one by one from any legacy class
(Vector and stack) then we will go for enumeration.

Declaration of elements()

Public enumeration elements();

Vector v = new vector();

Method of enumeration

It have only 2 methods

1.public boolean hasMoreElement();

2. public object nextElement();


import java.util.Enumeration;
import java.util.Stack;
import java.util.Vector;
class oos2 {
public static void main(String[] args) {
Vector v = new Vector();
for (int i = 1;i<=10;i++){
v.add(i);

}
System.out.println(v); // 1,2,3,4,5,6,7,8,9,10
Enumeration e = v.elements();
while(e.hasMoreElements()){
Integer i = (Integer)e.nextElement();
if(i %2 ==0){
System.out.println(i); // 2,4,6,8,10
}
}
}
}
Limitations of enumeration
1. Enumeration can be used to fetch one by one from the legacy class only.
2. In the enumeration we can perform only one activity that is read only
operation and we can’t perform operations like remove operation, this
iterator come into concept.

Iterator

By using iterator we can get object one by one from any collections implemented
class object.

In iterator we can perform remove operation too.

It is known as the universal cursor

By using the below format we can get object one by one any collection
implemented class object.

Syntax

Public Iterator iterator();

ArrayList I = new ArrayList();

Iterator i = new iterator();

Methods

1. Public Boolean hasNext();


2. Public Object next();
3. Public void remove();
4. Public void remove();
5. import java.util.ArrayList;
6.
7. import java.util.Iterator;
8.
9. class cls6 {
10. public static void main(String[] args) {
11. ArrayList l =new ArrayList();
12.
13. for(int i = 10; i<= 20; i++){
14. l.add(i);
15.
16. }
17. System.out.println(l);
18. Iterator i = l.iterator();
19. while(i.hasNext()){
20. Integer a = (Integer) i.next();
21. if(a%2 == 0){
22. i.remove();
23. }
24. }
25. System.out.println(l);
26. }
27.}

Limitations of Iterator

By using iterator we can get, remove the object but we can’t perform the
operations like add or replace for this list iterator came into the
concept.
 Both enumeration and iterator are unidirectional cursor which means it can
only move only in forward direction.
List iterator
It is the child interface of iterator.
If we want to get object one by one from any list interface implemented
class then we can go for list iterator.
It is only applicable for list interface.
This cursor is known as bi-directional cursor which means it can move in
both forward and backward direction.
If we want to get object one by one by using list Iterator then we will use
the below format.
Syantax
public ListIterator listIterator();
ArrayList i = new ArrayList();
ListIterator I = l.listIterator();
Methods
1.public Boolean hasNext();
2. public Object next();
3. public Boolean hasPrevious();
4. public void remove();
5. public void set(Object o);
6. public void add(Object new);

import java.util.ArrayList;
import java.util.ListIterator;

public class cls6{


public static void main(String args[]){
ArrayList l = new ArrayList();
for(int i = 10;i<=20;i++){
l.add(i);
}
System.out.println(l);
ListIterator i = l.listIterator();
while(i.hasNext()){
Integer a = (Integer)i.next();
if(a==10||a==15){
i.set("Champa");
}
else if (a==16){
i.add("Chameli");
}
}
System.out.println(l);
}
}

Set interface
If we want to represent a group of individual object as a single entity
where duplicates are not allowed and insertion order is not preserved then
we will go for set interface.

hasSet
the underlined data structure is hashtable.
Insertion order is not preserved.
Duplicates are not allowed.
Heterogenous elements can be inserted.
Null insertion is possible but only once.
If we try to insert duplicate elements then we will not get any kind of
compile time error or runtime exception.
Set don’t have any methods it will use the methods of collection interface.

Constructor
1. HashSet h = new HashSet();

It will create an empty HashSet object with default initial capacity of 16


and default fill ratio of 0.75.

2. HashSet h = new HashSet(int initialCapacity);

It will create an empty HashSet object with the given Capacity and a fill
ratio of 0.75.
3. HashSet h = new HashSet(int initialCapacity, float fillratio);
4. HashSet h = new HashSet(Collection c);

It will create or establish a relationship between HashSet and other


Collection class.

import java.util.HashSet;
public class cls6{
public static void main(String[] args) {
HashSet h = new HashSet();
h.add("Tushar");
h.add("Sahoo");
System.out.println(h);
}
}

LinkedHashSet

The underlinked data structure of linkedhashset is a combination of hashset


and linkedlist.

It is the child class of hashset.

It is exactly same as the hashset except the following differences.

LinkedHasSet

Underlinked data structure is hash table and double linked list.

Insertion order Is preserved.

Introduced in 1.4 version.

Program

import java.util.LinkedHashMap;
import java.util.LinkedHashSet;

public class A {
public static void main(String[] args) {
LinkedHashSet i = new LinkedHashSet();
i.add("Hello");
i.add("hii");
i.add("12");
i.add('a');
i.add("null");
i.add(false);
System.out.println(i); // hello,hii,12,a,null,false
}
}
Hashset

Underlinked data structure is hash table.

Insertion order is not preserved.

Introduced in 1.2 version.

SortedSet

It is the child interface of set.

If we want to represent group of individual object as a single entity where


duplicates are not allowed and all the elements are inserted according to
some sorting order then we will go for sorted set.

Methods specified for SortedSet

1.object first();

2.Object last();

3. SortedSet headset(Object o);

It will return the elements which are less than o.

4 SortedSet tailSet(Object o);

It will return the elements which are greater than >= o.

5. SortedSet subset (Object o1, Object o2);

It will return the elements which are >= o1 and <o2.


TreeSet

1. The underlying data structure is balanced tree.


2. Duplicates are not allowed.
3. All the elements will be inserted according some sorted order that is
default natural sorting order (ascending order).
4. Heterogenous elements are not allowed.
5. Null insertion is not possible.

If we try to insert, it will get NullPointerException.

If we try to insert heterogenous elements then we will get


ClassCastException.

Constructor of TreeSet

1. TreeSet t = new TreeSet();

It will create an empty TreeSet Object where all the elements will be
inserted according to default natural sorting order (Ascending order).

2. TreeSet t = new TreeSet(Collection C);

import java.util.TreeSet;

public class main1{


public static void main(String[] args) {
TreeSet t = new TreeSet();
t.add(20);
t.add(5);
t.add(10);
t.add(15);
t.add(20);
t.add(30);
System.out.println(t); // output will be in ascending order
}
}

import java.util.TreeSet;

public class main1{


public static void main(String[] args) {
TreeSet t = new TreeSet();
t.add(null); // null pointer exception

System.out.println(t);
}
}

In the above program we will get runtime exception saying


NullPointerException

because in treeset null insertion is not possible and we know that while
performing any operation with null we will get NPE(NullPointerException

).

import java.util.TreeSet;

public class main1{


public static void main(String[] args) {
TreeSet t = new TreeSet();
t.add(5);
t.add(10);
t.add("holi"); // classCastException, which means we can't compare string with
Integer
t.add(5);

System.out.println(t);
}
}

As we know that in TreeSet all the elements will be inserted by using some
sorting order which means the objects will be compared with each other. And
we also know that for comparison we need same type of object(same class
type).

If we try to insert hetrogenous element then we will get


classCastException.

Map

If we want to represent a group of individual object as a key-value pair


then we should go for map interface.

Both key and value are objects.


Duplicate keys are not allowed but values can be duplicated.

Each pair of key value is known as one entry.

Note

Map interface is not a child of interface of collection, hence we can’t apply


/use collection interface methods here.

Methods of map interface

1. Object put(Object key, Object Value);

It will work like add() in map Interface.

2. Void putAll(Map m);

It will work like addAll() in map interface.

3. Object get(Object key);


4. Object remove(Object key);
5. Boolean containsKey(Object key);
6. Boolean containsValue(object value);
7. Boolean isEmpty();
8. int size();
9. Void clear();
hashMap

1. The underlying data structure is HashTable.


2. Duplicate key are not allowed but values can be duplicated.
3. Insertion order is not preserved but all the elements/entries are done on
the basis of HashCode of the “ Key Object”.
4. Heterogeneous objects are allowed both for key and value.
5. The best suited operation is searching operation.

Program

Object put

import java.util.HashMap;

public class mai{


public static void main(String[] args) {
HashMap h = new HashMap();
h.put(101,"sunday");
h.put(null, 12345);
h.put('a', 11.234);
h.put(false,'a');
h.put("dog", "cat");
System.out.println(h); // {null = 12345, a = 11.234, 101 = sunday, false = a, dog =
cat}
}
}

Combination of all the methods

import java.util.HashMap;

public class mai {


public static void main(String[] args) {
HashMap h = new HashMap();
h.put(101, "sunday");
h.put(null, 12345);
h.put('a', 11.234);
h.put(false, 'a');
h.put("dog", "cat");
System.out.println(h); // {null = 12345, a = 11.234, 101 = sunday, false = a, dog =
cat}
System.out.println(h.get("dog")); // cat
System.out.println(h.remove('a')); // 11.234 will be removed along with 'a' cuz it's
having the value for 'a'
System.out.println(h);
System.out.println(h.containsKey(false)); //true
System.out.println(h.containsValue("cat")); //true
System.out.println(h.isEmpty()); //it will give false as it is not empty.
System.out.println(h.size());// the given size is 4 as it already removed one key
value pair
h.clear(); // it will remove all the added methods and will make it empty
System.out.println(h);
}
}

We can also put data in separate obejct’s reference

HashMap h1 = new HashMap();


h1.put(20, 20);
h1.put(50, 50);
h1.put(100, 100);
System.out.println(h1);
h.putAll(h1);
System.out.println(h); // {50 = 50, 20 = 20, 100 = 100}

Constructors of HashMap

1. HashMap h = new HashMap();

It will create an empty HashMap object with default initial capacity of 16 and
default fill ratio of 0.75.

2. HashMap h = new HashMap(int initial capacity);


3. HashMap h = new HashMap(int initial capacity, float fillRatio);
4. HashMap h = new HashMap(Collection c);

LinkedHashMap

It is exactly same as HashMap except the following differences.

HashMap

1. The underlying data structure is hashtable.


2. Insertion order is not preserved.
3. It was introduced in the version 1.2 version.

LinkedHashMap

1. The underlying data structure is the combination of HashTable and


LinkedList.
2. Insertion order is preserved.
3. It was introduced in the version 1.4 version.
import java.util.LinkedHashMap;

public class mai{


public static void main(String[] args) {
LinkedHashMap h = new LinkedHashMap();
h.put(101, "sunday");
h.put(null, 12345);
h.put('a', 11.234);
h.put(false, 'a');
h.put(false, "12");
System.out.println(h); // {101 = sunday, null = 12345,a = 11.234, false =12},
if there is duplicate key then the values will be overridden, here we have 2 false so
which is why 12 will override ‘a’.

}
}

Indentity HashMap

It is exactly same as hashMap except the following differences

HashMap

In the case of HashMap JVM will always use equals() to identify duplicate
keys.

indentityHashMap

In the case of IdentityHashMap jvm will always use equality(==) operator to


identify duplicate keys.

WeakHashMap

It is exactly same as HashMap except the following differences

HashMap
In the case of normal HashMap an object isn’t eligible for GC if it became
useless, means no reference pointing towards it.

WeakHashMap

In the case of WeakHashMap if an object doesn’t have any reference pointing


towards it then it is eligible for GC because GC dominates over WeakHashMap.
SortedMap

1. It is the child interface of Map.


2. If we want to represent a group of key-value pair according to some sorting
order of keys, then we should go for sortedMap.
3. Sorting is only possible based on the keys and not values.

Method

1. Object firstKey();
2. Object lastKey();
3. SortedMap headMap(Object key);
4. SortedMap tailMap(Object key);
5. SortedMap subMap(Object key1, Object key);

TreeMap

1. It is the implemented class of SortedMap.


2. The underlying data structure is Red-Black Tree.
3. Duplicates keys aren’t allowed but values can be duplicated.
4. Insertion order is not preserved.
5. Null insertion for keys are not allowed but for the values there is no
restrictions.

Constructor

1. TreeMap m = new TreeMap();


2. TreeMaP M = new TreeMap(Map m);
3.

import java.util.TreeMap;

public class mai {


public static void main(String[] args) {
TreeMap t = new TreeMap();
t.put(101, "sunday");
t.put(1, 12345);
t.put(23, 11.234);
t.put(5, "12");
System.out.println(t); // {1=12345, 5=12, 23=11.234, 101 = sunday}

}
}
import java.util.TreeMap;

public class mai {


public static void main(String[] args) {
TreeMap t = new TreeMap();
t.put(101, "sunday");
t.put(1, 12345);
t.put(23, 11.234);
t.put(5, "12");
System.out.println(t);
System.out.println(t.firstKey()); // 1
System.out.println(t.lastKey()); //101
System.out.println(t.headMap(23)); // {1=12345, 5=12}
System.out.println(t.tailMap(23)); //{23 = 11.234, 101= sunday}
System.out.println(t.subMap(5, 12));//{5 = 12}
System.out.println(t.descendingMap()); //{101 = sunday, 23 = 11.234, 5 = 12, 1 =
12345}

}
}

Generix

It is a concept present in collection framework using which we can make our


collection framework’s implemented class object homogenous.

Possible way

import java.util.ArrayList;
public class mai {
public static void main(String[] args) {
ArrayList<String> i = new ArrayList(); // if we are using generix 0f string type then
it will show error if we try to insert anything except String Type
i.add("hii"); // hii, it is possible

}
}

Will not take any other input if we tryna insert different tpe of data type
except the given one in generix

import java.util.ArrayList;

public class mai {


public static void main(String[] args) {
ArrayList<String> i = new ArrayList(); // if we are using generix 0f string type
then it will show error if we try to insert anything except String Type
i.add("hii"); // hii, it is possible
i.add(123); // will show error as it is not compatable to string type

}
}

You might also like