0% found this document useful (0 votes)
5 views225 pages

All in One Java Notes

This document provides comprehensive notes on Java, covering its introduction, versions (J2SE, J2EE, J2ME), syntax, literals, variables, identifiers, keywords, data types, type conversions, operations, and operators. It details the characteristics and examples of each concept, including primitive and non-primitive data types, as well as type conversion methods. The document serves as a foundational guide for understanding Java programming and its various components.

Uploaded by

sy0205476
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views225 pages

All in One Java Notes

This document provides comprehensive notes on Java, covering its introduction, versions (J2SE, J2EE, J2ME), syntax, literals, variables, identifiers, keywords, data types, type conversions, operations, and operators. It details the characteristics and examples of each concept, including primitive and non-primitive data types, as well as type conversion methods. The document serves as a foundational guide for understanding Java programming and its various components.

Uploaded by

sy0205476
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 225

ALL-IN-ONE: JAVA NOTES

java Introduction
1.java is a popular programming language.
2.Father of java is James’s gosling.
3.Java 1st version (1.0) was introduced by Sun microsystem in 1996.
4.At present java was owned by oracle corporation.

java was technically divided into 3 parts:


1. j2se
2. j2ee
3. j2me

1. j2se
1.j2se stands for java 2 standard edition.
2.In j2se we will learn java fundamentals.
3.By using j2se we will develop standalone/desktop/window-based App

2. j2ee
1.j2ee stands for java 2 enterprise edition.
2.In j2ee we will learn server-side programming.
3.By using j2ee we will develop enterprise/distributed app.

3. j2me
1.j2me stands for java 2 micro edition.
2.In j2me we will learn micro side programming.
3.By using j2me we will develop mobile based App

___________________________________________________________
Basic java program syntax

INPUT:
class ClassName
{
public static void main(String[] args)
{
statements
}
}
class Demo
{
public static void main(String[] args)
{
System.out.println("welcome to java");
}
}
OUTPUT:
welcome to java
___________________________________________________________

Literals
1.Literals are input values.
2.Literals are divided into 6 types:
1.Integer Literals========================>-12,0,12...
2.Floating Point Literals=================>-1.2f,1.0f,2.5f...
3.Character Literals======================>'a','z','1',...
4.String Literals=========================>"Excelr","Trainer"...
5.Boolean Literals========================>true, false
6.Object Literals=========================>null

Variables
1.A variable is a container.
2.The purpose of variable is to store operand(value,variable,expression).

3.variable declaration
datatype varname;==========>variable declaration
varname=value==============>assigning
int a;
a=5;

4.variable Initialization
datatype varname=value;
int a=2;

5.int a=5=======>value
6.int b=a========>variable
7.int c=6+3======>expression

Rules
1.A variable must be a alphabet (lowercase)(a-z), UpperCase(A-Z), Digit(0-9) and special symbols (_,$).
2.A variable 1st letter must not starts with digit(0-9).
3.A variable does not allow special symbols except(_ $).
4.Keywords must not use as variables.
5.Variable size is unlimited but according to industry standards do not use variable size more than 16 digits.
6.Variable is case sensitive.
7.true and false are not keywords but do not use as variables.

Examples
 int abcB12_$=10; ======>valid
 int 1ba=10; ==========>invalid
 int a*5=10; ==========>invalid
 int a@b=9 ;===========>invalid
 int _ab=10; ===========>valid

Identifiers
1.Identifier is a one type of variable.
2.The purpose of identifier is to identify package, subpackage, class, interface, method....

package
1.package must be written in lowercase.
2.A package before there is no dot(.) then that is called package.
3.A package before there is dot(.) then that is called subpackage.

class
A class 1st letter must start with capital from each word onwards.

interface
An interface 1st letter must start with capital from each word onwards.

Method
A method 1st letter must start with capital from second word onwards and ends with ().
Examples
 java.lang=====>java(package) lang(sub package)
 java.io=======>java(package) io(sub package)
 java.util.Arrays==>java(package) util(subpackage) Arrays(class)
 LinkedList======>class
 lastIndexOf()===>method
 List============>interface
 Set=============>interface
 Map=============>interface
 Comparator======>interface
 Comparable=====>interface

Keywords
1.Keywords are set of reserved words.
2.Reserved words will have particular functionality.
3.At present there are 50 keywords in java including assert, strictfp, enum.
4.Keywords must be written in lowercase.
5.goto and const are not using in java.
6.true and false are not keywords but do not use as variables.

Examples
byte, short, int, long, float, double, char, Boolean, if, else, else if, for, while, do, break, continue, public private,
protected, switch, static, final, this, super, abstract, transient, synchronized, volatile, extends implements, return,
void...

Datatypes
Datatype determines what type of value we can store.
Datatypes are divided into 2 types:
1.primitive
2.Non primitive/reference datatype

1.primitive Datatypes
Primitive datatypes are predefine datatypes.
primitive datatypes store 1 value at a time
There are 8 primitive datatypes in java.
1.byte
2.short
3.int
4.long
5.float
6.double
7.char
8.boolean

2.Non-primitive datatypes
Non-Primitive datatypes are user-define datatypes.
Non-primitive datatypes store multiple values at a time

Example:
 Arrays
 String
 class
 class
 object

1.byte
byte datatype will store both positive and negative values without decimals.
Examples:
byte a=10;
System.out.println(a); ==>10
byte a=-10;
System.out.println(a); ===>-10

byte a=1.2;
System.out.println(a); ===>error
byte a=129;
System.out.println(a); ===>error

2.short
short datatype will store both positive and negative values without decimals.

Examples:
short a=10;
System.out.println(a); ==>10
short a=-10;
System.out.println(a); ===>-10

short a=1.2;
System.out.println(a); ===>error

3.int
int datatype will store both positive and negative values without decimals.

Examples:
int a=10;
System.out.println(a); ==>10
int a=-10;
System.out.println(a); ===>-10

int a=1.2;
System.out.println(a); ===>error

4.long
long datatype will store both positive and negative values without decimals.
If we store more than max value of int in long we must ends with l or L.

Examples
long a=10;
System.out.println(a); ==>10
long a=-10;
System.out.println(a); ===>-10

long a=1.2;
System.out.println(a); ===>error

System.out.println(Byte.SIZE);

long a=21474836478;
System.out.println(a); ===>error

long a=21474836478l;
System.out.println(a); ===>21474836478
Sr.NO DATATYPE SIZE RANGE (Min to max)
1. byte 8 -128 to 127
2. short 16 -32768 TO 32767
3. int 32 -2147483648 TO 2147483647
4. long 64 -9223372036854775808 To -9223372036854775807

1.System.out.println(Byte.SIZE);
2.System.out.println(Byte.MIN_VALUE);
2.System.out.println(Byte.MAX_VALUE);

int datatype stores number format data.

Sr.NO DATA START BASE VALUE VALUES


1. Normal data No 10 0,1,2,3,4,5,6,7,8,9
2. Binary data 0b or 0B 2 0,1
3. Octal data 0 8 0,1,2,3,4,5,6,7
4. Hexadecimal data 0x 16 0,1,2,3,4,5,6,7,8,9, a, b, c, d, e, f

Examples
 int a=10; ======>Normal data
 int a=0b1010; ==>Binary data
 int a=0B1111; ===>Binary data
 int a=0b234; ====>error
 int a=0123; =====>Octal
 int a=0x123; ===>Hexadecimal

int a=0b1010;
System.out.println(a); ==============>10

int a=012;
System.out.println(a); ======>10

int a=0x12;
System.out.println(a); =========>18

int a=10;
System.out.println(a); ===========>10

String b=Integer.toBinaryString(a);
System.out.println(b); ===========>1010

int a=10;
System.out.println(a); //10

String b=Integer.toOctalString(a);
System.out.println(b); //12

int a=10;
System.out.println(a); //10
String b= Integer.toHexString(a);
System.out.println(b); //a

Floating point values


1.Floating point values stores both positive and negative values with decimal and without decimal.
2.Floating are divided into 2 types:
1. float
2. double.

1.float
1.float datatype stores both positive and negative values with decimal and without decimal.
2.float values must be ends with f or F.
3.In float datatype after decimal we can store 7 digits.

Examples
1.>float ab=1.2;====>error
System.out.println(ab);
2.>float ab=1.2f;
System.out.println(ab);===>1.2

3.>float ab=-1.2f;
System.out.println(ab);===>-1.2

4.>float ab=1f;
System.out.println(ab);===>1.0

Note:float datatype stores scientific data.


e==>exponent===>10

1. float a=3e2f;
System.out.println(a);=======>300.0

1. float a=7e2f;
System.out.println(a);========>700.0

2
3*10===========>3*100==========>300============>300.0
2
7e2f=====>7*10===>7*100======>700==========>700.0

6.double

1.double datatype stores both positive and negative values with decimal and without decimal.
2.double values must not be ends with f or F.
3.In double datatype after decimal we can store 16 digits.
4.double datatype also stores scientific data.

Examples

1.>double ab=1.2;
System.out.println(ab);====>1.2

2.>double ab=-1.2;
System.out.println(ab);===>-1.2

3.>double ab=1;
System.out.println(ab);===>1.0

S.NO DATATYPE SIZE RANGE

1. float 32 1.4E-45 TO 3.4028235E38


2. double 64 4.9E-324 TO 1.7976931348623157E308

7.char

1.char datatype store single character and enclosed with single quotes('').
2.If we store ascii value in char datatype we need not to enclose with single quotes('')

ASCII VALUES

a======>97 A=====>65 0=======>48


b======>98 B======>66 1=======>49
c======>99 C======>67 2=======>50
d======>100
......... .......
........
z======>122 Z=======>90 9=======>57

Examples

1.char ch='a';=====>valid
System.out.println(ch);===================>a

2.char ch='ab';=====>invalid
System.out.println(ch);===================>error

3.char ch=a;=====>invalid
System.out.println(ch);===================>error

4.char ch='9';
System.out.println(ch);==========>9

5.char ch='19';
System.out.println(ch);==========>error

6.char ch=97;
System.out.println(ch);=====>a

7.char ch=65;
System.out.println(ch);=====>A

8.char ch='97';
System.out.println(ch);====>error
8.boolean

1.boolean datatype is used to store true or false values.


2.boolean datatype donot store 0,1 values.

Examples

1.boolean b=true
System.out.println(b);=========>true

2.boolean b=false
System.out.println(b);=========>false

3.boolean b=0
System.out.println(b);=========>error

4.boolean b=1
System.out.println(b);=========>error

Type conversions

1.The process of converting one datatype into another datatype is called type conversion.
2.At present total 56 type conversions in java.
3.Type conversions are divided into 2 types.They are
1.widening type conversions.(19)
2.Narrowing type conversions.(23)
4.14 type conversions are not possible boolean cannot be converted into any other datatype and
any other datatype cannot be converted into boolean.

Examples

1.boolean b=true;
int a=b;
Sytem.out.println(a);==============>error

2.boolean b=true;
float a=b;
Sytem.out.println(a);==============>error

3.int a=5;
boolean b=a;
System.out.println(b);=======>error

1.widening type conversions.(19)

1.widening type conversions are implicit type conversions.


2.Widening type conversions done by system implicitly.
byte======>short,int,long,float,double==========>5
short=====>int,long,float,double================>4
int=======>long,float,double====================>3
long======>float,double=========================>2
float=====>double===============================>1
char======>int,long,float,double================>4

1. byte a=12;
short b=a;
System.out.println(b);=========>12

2. byte a=112;
int b=a;
System.out.println(b);========>112
3 int a=12;
float b=a;
System.out.println(b);========>12.0

4. char ch='a';
int b=ch;
System.out.println(b);========>97

2.Narrowing type conversions.(23)

1.Narrowing type conversions are explicit type conversions.


2.Narrowing type conversions done by programmers explicitly.

byte======>char==========================>1
short=====>byte,char=====================>2
int=======>byte,short,char================>3
long======>byte,short,int,char============>4
float=====>byte,short,int,long,char=======>5
double=====>byte,short,int,long,float,char=>6
char======>byte,short=======================>2

char ch='A';
byte bh=ch;
System.out.println(bh);=========>error

char ch='A';
byte bh=(byte)ch;
System.out.println(bh);==============>65

int a=122;
char ch=(char)a;
System.out.println(ch);==============>z

Operations

byte,short,int,char + byte,short,int,char===>int
byte,short,int,char + long=================>long
byte,short,int,long,char + float=================>float
byte,short,int,long,float,char + double=================>double
Any datatype + String==================>String

1.byte a=7;
int b=6;
System.out.println(a+b);===========>13

2.int a=6;
char b=97;
System.out.println(a+b);======>103

3.int a=6;
char b='a';
System.out.println(a+b);===>103

4.int a=6;
String s="virat";
System.out.println(a+s)====>6s

5.System.out.println(6+"virat"+7);===>6virat7

Operators

1.operator is a symbol.
2.The purpose of operators is to perform operations

+ = < && ++ << += ?


- > || -- >> -= :
* <= ! ~
/ >= &
% == |
!= ^

1.Arithmetic operators(+,-,*,/,%)

Arithmetic operators used to perform addition,subtraction,multiplication,division.

Examples

1.System.out.println(1+2);==========>3
2.System.out.println(3-2);==================>1
3.System.out.println(6*2);==================>12
4.System.out.println(6/2);=================>3(quotient)
5.System.out.println(6%2);=================>0(remainder)

Order of precedence

1.()
2./,%,*
3.+,_

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

int a=5;
int b=6;
int c=3;
System.out.println(a+b+(b+c));======================>20
}
}

int a=5;
int b=6;
int c=3;
int d=7;
System.out.println(a*b+b-d-a+c);====================>27

2.>Assignment operators(=)

Assignment operator is used to transfer rhs operands to the lhs variable.

operands

operand can be variable,value,expression

Examples

int a=5;

Here int is datatype


a is variable
= is Assignment operator
5 value

int a=5;====>value
int b=a;====>variable
int c=5+6;===>expression

3.Relational operators(<,>,<=,>=,==,!=)

Relational operators are used to compare 2 values and returns either true or false.
Examples

1.System.out.println(5>3);=============>true
2.System.out.println(5>11);============>false
3.System.out.println(5>11<2);==========>error
4.System.out.println(5<2);=============>false
5.System.out.println(5<21);=============>true
6.System.out.println(5<=6);=============>true
7.System.out.println(6<6);===============>false
8.System.out.println(6<=6);==============>true
9.System.out.println(2>=2);===============>true
10.System.out.println(2==2);===============>true
11.System.out.println(2==3);===============>false
12.System.out.println(2!=3);==============>true
13.System.out.println(2!=2);==============>false

Note:Difference b/w = and ==.


= is to assign operand to variable
== is to compare 2 operands.

4.Logical operators

Logical operators are used to compare multiple conditions and returns either true
or false.

1.&&=====>All the conditions must be satisfied


2.||======>atleast one condition must be satisfied
3.!

1.System.out.println((2>1) && (6>2));======>true


2.System.out.println((2>6) && (6>2));======>false
3.System.out.println((2>1) && (6>2) && (7>5));==>true
4.System.out.println((2>1) && (6>2) && (7>11));==>false
5.System.out.println((2>1) || (6>2) || (7>2));====>true
6.System.out.println((2>1) || (6>12) || (7>2));===>true
7.System.out.println((2>1) || (6>12) || (7>12));===>true
8.System.out.println((2>11) || (6>12) || (7>12));===>false
9.System.out.println(!(6>2));==========>false
10.System.out.println(!(6>12));=========>true

Increment/Decrement operators

1.Increment operator(++var or var++)

Increment operator is used to increment 1 value.


They are 2 types of increment operators.
1.pre increment(++var)
2.post increment(var++)

1.pre increment(++var)

In pre increment 1st incrementation and next value


In pre increment incrementation is applied to the current operation.

1.post increment(var++)

In post increment 1st value and next incrementation.


In post increment incrementation is applied to the next operation.

Examples

1. int a=5;
++a;
System.out.println(a);====>6

2. int a=5;
a++;
System.out.println(a);===>6

3. int a=5;
System.out.println(++a);===>6

4. int a=5;
System.out.println(a++);===>5

5. int a=5;
System.out.println(++a + ++a);====>13

6. int a=5;
System.out.println(a++ + ++a);

7. int a=5;
System.out.println(a++ + a++);===>11

8. int a=5;
System.out.println(a++ + ++a + a++);======>19

2.Decrement operator(--var or var--)

Decrement operator is used to Decrement 1 value.


They are 2 types of Decrement operators.
1.pre Decrement(--var)
2.post Decrement(var--)

1.pre Decrement(--var)

In pre Decrement 1st Decrementation and next value


In pre Decrement Decrementation is applied to the current operation.

1.post Decrement(var--)

In post Decrement 1st value and next Decrementation.


In post Decrement Decrementation is applied to the next operation.

Examples

int a=5;
System.out.println(a++ + --a + a++);=====>15

int a=5;
System.out.println(a-- + --a + a++);====>11

Bitwise Operators

Bitwise operators are work on binary data and returns integer value.
There are 6typesof Bitwise Operators

1.Bitwise LeftShift(<<)
2.Bitwise RightShift(>>)
3.Bitwise Complementary(~)
4.Bitwise AND(&)
5.Bitwise OR(|)
6.Bitwise XOR(^)

1.Bitwise LeftShift(<<)

b
FORMULA a*2

Examples

int a=12;
int b=3;
System.out.println(a<<b);===>96

2.Bitwise RightShift(>>)

FORMULA a
__
b
2

Examples

int a=12;
int b=3;
System.out.println(a>>b);===>1

3.Bitwise Complementary(~)

Formula ~n=-(n+1)

int a=12;

System.out.println(~a);===>-13
4.Bitwise AND(&)(multiply)

int a=9;
int b=7;
System.out.println(a&b);===>1

5.Bitwise OR(|)(addition)

int a=9;
int b=7;
System.out.println(a|b);===>15

a(9)======>1001
b(7)======>0111

1111===>15

6.Bitwise XOR(^)

If same values is there means take 0.


If Different values is there means take 1.

int a=9;
int b=7;
System.out.println(a^b);

a(9)======>1001
b(7)======>0111

11 10

7.Conditional operator

Conditional operator is a ternary operator.


Conditional operator is used to check condition and returns either true expression
or false expression.

Syntax

condition ? true expression : false expression

5>2 ? 2 : 3

true 2

5>12 ? 2 : 3

false 3

1.System.out.println(5>2?2:3);====>2
2.System.out.println(5>12?2:3);=====>3
3.System.out.println(5>12?"Excelr institute":"tcs");====>tcs

int a=5;
int b=2;
float res=5>2?1.2f:1.6f;

System.out.println(res);

int a=5;
int b=12;
String res=(a>b)?"super":(b>a)?"Excellent":"Bad";
System.out.println(res);===>Excellent

8.Compound operator

Compound operator is a combination multiple operators(Assignment and Arithmetic opera


tors)

int a=-5;
int b=-a;
System.out.println(b);========>5

int a=5;
int b=2;
a=a+b;
System.out.println(a);=====>7

int a=5;
int b=2;
a+=b;===========>a=a+b===>5+2
System.out.println(a);====>7

int a=5;
int b=2;
a-=b;===>a=a-b
System.out.println(a);==>3

int a=5;
int b=2;
a*=b;
System.out.println(a);====>10

int a=5;
int b=2;
a/=b;
System.out.println(a);==>2

int a=5;
int b=2;
a%=b;
System.out.println(a);===>1

Unary operator
The operator which will work on 1 operand

operand can be a variable,value,expression

++a
a++
++5

Binary operator

The operator which will work on 2 operands


a+b
2+3

Ternary operator

The operator which will work on 3 operands

cond?trueexp:false

(a>b)?a:b
(5>2)?5:2

Statements

Statements are divided into 4 types.They are


1.Simple Statements
2.Conditinal Statements
3.Looping Statements
4.Jumping Statements

1.Simple Statements

Simple Statements are 1 line Statements.


The purpose of simple statements to take inputs and prints output.
Simple Statements are divided into 2 types
1.input Statement
2.output Statement

int a=5;============>input Statement


=======>No output(because no output statement)

class Demo
{
public static void main(String[] args)
{
int a=5;============>input Statement
System.out.println(a);=====>out Statement========>5
}
}

2.Conditional Statements

1.Conditional Statements are used to check conditions if condition is true then it


will executes true block other wise false block.
2.Conditinal Statements are divided into 6 types.They are
1.Simple if
2.if else
3.else if
4.Multiple if
5.Nested if
6.Switch

1.Simple if

Simple if is used to check 1 condition in block.


Simple if will give output when condition true otherwise no output(con false)

Syntax

if(cond)
{
------------
Statements
------------
}

int a=5;
if(a>2)
{
System.out.println("positive num");=============>positive num
}

int a=5;
if(a>12)
{
System.out.println("positive num");================>No ouput
}

2.if else

1.if else is used to check 1 condition in 2 blocks.


2.if condition is true means if block will execute
3.if condition is false means else block will execute

Syntax

if(cond)
{
--------
-------
}
else
{
-------
-------
}

int a=5;
int b=2;
if(a>b)
{
System.out.println(a+" is big num");
}
else
{
System.out.println(a+" is not big num");

output===>5 is big num

int a=5;
int b=12;
if(a>b)
{
System.out.println(a+" is big num");
}
else
{
System.out.println(a+" is not big num");

output===>5 is not big num

3.if else if else

if else if else is used to check multiple conditions with multiple blocks.


else block is optional

syntax

if(cond)
{
}
else if(cond)
{
}
else if(cond)
{
}
------
------
else
{
}

int marks=90;
if(marks>90)
{
System.out.println("A grade");
}
else if((marks>80) && (marks<90))
{
System.out.println("B grade");
}
else if((marks>70) && (marks<80))
{
System.out.println("C grade");
}
else
{
System.out.println("Fail");
}

output====>Fail

int marks=90;
if(marks>90)
{
System.out.println("A grade");
}
else if((marks>80) && (marks<90))
{
System.out.println("B grade");
}
else if((marks>70) && (marks<80))
{
System.out.println("C grade");
}

No ouput

4.Multiple if

Multiple if is used to check multiple conditions with multiple blocks.


In Multiple if true condition will execute and else block will execute.
else is optional.

if(cond)
{
}
if(cond)
{
}
if(cond)
{
}
----
----
else
{
}

int marks=87;
if(marks>90)
{
System.out.println("A grade");
}
if((marks>80) && (marks<90))
{
System.out.println("B grade");
}
if((marks>70) && (marks<80))
{
System.out.println("C grade");
}
else
{
System.out.println("Fail");
}

output

B grade
Fail

int marks=87;
if(marks>90)
{
System.out.println("A grade");
}
if((marks>80) && (marks<90))
{
System.out.println("B grade");
}
if((marks>70) && (marks<80))
{
System.out.println("C grade");
}

Output

B grade

if(5>2)
{
System.out.println("java");
}
if(15>2)
{
System.out.println("python");
}
if(17>2)
{
System.out.println("ruby");
}

Output

java
python
ruby

if(5>2)
{
System.out.println("java");
}
else if(15>2)
{
System.out.println("python");
}
else if(17>2)
{
System.out.println("ruby");
}

Output

java

Note:In if else if multiple conditions are satisfied then 1st true block will execute
In multiple if multiple conditions are satisfied the all the block willexecute

Nested if

The process of defining 1 if in another if is called Nested if

Syntax

if(cond)
{
if(cond)
{
---
}
}

if(15>2)
{
if(6>1)
{
System.out.println("Nested if");
}
}

Output===>Nested if
if(15>2)====>1(true)
{
if(6>11)====>2(false)
{
System.out.println("Nested if");
}
else===>3
{
System.out.println("else in nested if");==>4
}
}

output:else in nested if

if(15>22)=======>1(false)
{
if(6>11)
{
System.out.println("Nested if");
}
else
{
System.out.println("else in nested if");
}
}
else====>2
{
if(12>6)====>3(true)
{
System.out.println("if in else");===>4

}
else
{
System.out.println("else in else");
}
}

Output:if in else

switch

switch is used to check universal fixed multiple conditions in multiple cases.


class Main {
public static void main(String[] args) {
int day = 3; // Example: 3 represents Wednesday

switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid day");
}
}
}

Programs on Conditional statements

1.Write a java program to check number is even or odd.

Even Number

A number is divisible by 2 and remainder must be zero.

Odd Number

A number is divisible by 2 and remainder must not be zero.


int num= 12;
if(num%2==0)
{
System.out.println("num is even"+num);
}
else
{
System.out.println("num is odd"+num);

2.Write a java program to check big number between 2 numbers.

int first=12;
int second=16;
if(first>second)
{
System.out.println(first+"is a big num");
}
else
{
System.out.println(second+"is a big num");
}

3.Write a java program to check big number among 3 numbers.

int first=12;
int second=16;
int third=11;
if((first>second) && (first>third))
{
System.out.println(first+" is a big num");
}
else if((second>first) && (second>third))
{
System.out.println(second+" is a big num");

}
else
{
System.out.println(third+" is a big num");

4.Write a java program to check big number among 4 numbers.

int first=12;
int second=16;
int third=11;
int four=17;
if((first>second) && (first>third) && (first>four))
{
System.out.println(first+" is a big num");
}
else if((second>first) && (second>third) && (second>four))
{
System.out.println(second+" is a big num");

}
else if((third>first) && (third>second) && (third>four))
{
System.out.println(third+" is a big num");

}
else
{
System.out.println(four+" is a big num");

5.Write a java program to check character lowercase or uppercase

Note:Lowercase (character>='a')&&(character<='z')
Upperercase (character>='A')&&(character<='Z')
Digit (character>='0')&&(character<='9')

char ch='B';
if((ch>='a') && (ch<='z'))
{
System.out.println(ch+"is a lowercase");
}
else
{
System.out.println(ch+"is a uppercase");

6.Write a java program to check character lowercase or uppercase or digit

char ch='v';
if((ch>='a') && (ch<='z'))
{
System.out.println(ch+"is a lowercase");
}
else if((ch>='A') && (ch<='Z'))
{
System.out.println(ch+"is a uppercase");

}
else
{
System.out.println(ch+"is a digit");

7.Write a java program to check character lowercase or uppercase or digit or special


symbol.

char ch='*';
if((ch>='a') && (ch<='z'))
{
System.out.println(ch+"is a lowercase");
}
else if((ch>='A') && (ch<='Z'))
{
System.out.println(ch+"is a uppercase");

}
else if((ch>='0') && (ch<='9'))
{
System.out.println(ch+"is a digit");

}
else
{
System.out.println(ch+"is a special symbol");

8.Write a java program to check character is vowel or consonant.

vowel======>a,e,i,o,u,A,E,I,O,U
consonants===>b,c,d,f,g,h,j,k,l,m,n,p,q,r,s,t,v,w,x,y,z
char ch='e';
if((ch=='a') ||(ch=='e')||(ch=='i')||(ch=='o')||(ch=='u'))
{
System.out.println("vowel");
}
else
{
System.out.println("consononat");

char ch='E';
if((ch=='a') ||(ch=='e')||(ch=='i')||(ch=='o')||(ch=='u')||
(ch=='A') ||(ch=='E')||(ch=='I')||(ch=='O')||(ch=='U'))
{
System.out.println("vowel");
}
else
{
System.out.println("consononat");

9.Write a java program to convert lowercase charcter into upper case.

char ch='b';
System.out.println(ch);
int val=ch-32;
System.out.println(val);
char ori=(char)val;
System.out.println(ori);

10.Write a java program to convert uppercase charcter into lowerr case.

char ch='b';
System.out.println(ch);
int val=ch+32;
System.out.println(val);
char ori=(char)val;
System.out.println(ori);

11.Write a java program to swap 2 numbers with 3rd variable.

int first=10;
int second=20;
System.out.println("Before Swapping");
System.out.println("first is"+first);
System.out.println("second is"+second);
System.out.println("===================");
System.out.println("After Swapping");
int temp=first;
System.out.println("temp is"+temp);
first=second;
System.out.println("first is"+first);
second=temp;
System.out.println("second is"+second);

12.Write a java program to swap 2 numbers without 3rd variable.


int first=10;
int second=20;
System.out.println("Before Swapping");
System.out.println("first is"+first);
System.out.println("second is"+second);
System.out.println("===================");
System.out.println("After Swapping");
first=first+second;
System.out.println(first);
second=first-second;
System.out.println(second);
first=first-second;
System.out.println(first);

int first=10;
int second=20;
System.out.println("Before Swapping");
System.out.println("first is"+first);
System.out.println("second is"+second);
System.out.println("===================");
System.out.println("After Swapping");
first=first*second;
System.out.println(first);
second=first/second;
System.out.println(second);
first=first/second;
System.out.println(first);

13.>write a java program to check year is leap or not.

Non century leap year must be divisible by 4 and not divisible by 100.(1988,1992,1996)
Century leap year must be divisible by 100(1600,2000)

int year=1996;
if (((year % 4 == 0) && (year % 100!= 0)) || (year%400 == 0))
{
System.out.println(" leap year");
}
else
{
System.out.println(" not a leap year");
}

Looping Statemets.

Loopig Statements are used to execute multiple statements until condition become false

For Loop

For loop is used to execute multiple statements until condition become false
When we know number of iterations go for for loop.
For Loop Execution

1.Initialization====>Starting value
2.Condition=========>Ending value
3.Enter into block (execute statements)
4.Updation(inc/dec)

Synatx

for(initialization;condition;inc/dec)
{
---------------------
---------------------
}
Write a java program to print 1 to 10 numbers.

for(int i=1;i<=10;i++)
{
System.out.println(i);
}

2.While Loop

while loop is used to execute multiple statements until condition become false
When we DONOT know number of iterations go for while loop.

syntax

initialization
while(cond)
{
---------------
---------------
inc/dec

int i=0;
while(i<11)
{
System.out.println(i);
i++;
}
}

3.do while loop

do while loop is used to execute multiple statements until condition become false

do while loop Execution


-------------------------
1.Iniatialization
2.Statements
3.inc/dec
4.Cond
Syntax

intialization
do
{
--------------
-------------
inc/dec
}
while(cond);

int i=5;
do
{
System.out.println(i);
i++;
}
while(i<=10);

Nested Loops

The process of defining 1 loop in another loop.

for(int j=1;j<=2;j++)=========>outer forloop


{
for(int i=1;i<=3;i++)====>inner forloop
{
System.out.println(i);
}
}

Programs on while loop

1.Write a java program to count number of digits of a number.(123)==>3

int num=123;
int cd=0;
while(num>0)
{
int rem=num%10;
cd=cd+1;

num=num/10;
}
System.out.println(cd);

2.Write a java program to print sum of digits of a number.(123)===>6

int num=123;
int sum=0;
while(num>0)
{
int rem=num%10;
sum=sum+rem;
num=num/10;
}
System.out.println(sum);

3.Write a java program to reverse a number.(123)====>321

int num=123;
int rev=0;
while(num>0)
{
int rem=num%10;
rev=(rev*10)+rem;

num=num/10;
}
System.out.println(rev);

4.Write a java program to print 5 table.

int num=5;
int i=1;
while(i<=10)
{
System.out.println(num+"*"+i+"="+num*i);
i++;
}

5.Write a java program to check number is palindrome or not.

Palindrome Number

A Number that remains same when its digits are reversed.

int num=1221;
int ori=num;
int rev=0;
while(num>0)
{
int rem=num%10;
rev=rev*10+rem;

num=num/10;
}
if(ori==rev)
{
System.out.println("palindrome");
}
else
{
System.out.println("Not palindrome");

6.Write a java program to check number is Armstrong or not


Armstrong Number

Sum of nth power of each digit of a number and that is equal to the original number.

int num=153;
int ori=num;
int sum=0;
while(num>0)
{
int rem=num%10;
sum=sum+(rem*rem*rem);

num=num/10;
}
if(ori==sum)
{
System.out.println("Armstrong");
}
else
{
System.out.println("Not Armstrong");

class Armstrong
{
public static void main(String[] args)
{
int num=153;
int t1=num;
int len=0;
while(t1>0)
{
len=len+1;
t1=t1/10;

}
System.out.println(len);
int t2=num;
int sum=0;
while(t2>0)
{
int mul=1;
int rem=t2%10;
for(int i=1;i<=len;i++)
{
mul=mul*rem;
}
sum=sum+mul;
}
if(sum==num)
{
System.out.println("Armstrong");
}
else
{
System.out.println("Not Armstrong");

int num=1634;
int temp=num;
int sum=0;
int count=0;
while(temp>0)
{
temp=temp/10;
count=count+1;
}
temp=num;
while(temp>0)
{
int rem=temp%10;
sum+=(Math.pow(rem,count));
temp=temp/10;
}

if(num==sum)
{
System.out.println("Armstrong");
}
else
{
System.out.println("Not Armstrong");

7.>Write a java program to check number is strong or not.

Strong Number

Sum of factorial of a digit is equal to the given number is called strong number.

int n=145;
int sum=0;
int ori=n;
while(ori>0)
{
int rem=ori%10;
int f=1;
for(int i=1;i<=rem;i++)
{
f=f*i;
}
sum=sum+f;
ori=ori/10;
}
if(n==sum)
{
System.out.println("Strong");
}
else
{
System.out.println("Not Strong");
}

8.>Write a java program to print sum of squares of a digit of a number.

int n=123;
int sum=0;
while(n>0)
{
int rem=n%10;
sum=sum+(rem*rem);
n=n/10;
}
System.out.println(sum);===>14

9.>Write a java program to print sum of cubes of a digit of a number.

int n=123;
int sum=0;
while(n>0)
{
int rem=n%10;
sum=sum+(rem*rem*rem);
n=n/10;
}
System.out.println(sum);===>14

10.>Write a java program to print sum of first and last digits of a number.
int n=45678;
int last=n%10;
while(n>=10)
{
n=n/10;
}
System.out.println(last+n);=======>12

Programs on forloop

1.>Write a java program to print factors of number.

Factor

A number that divides a given number exactly the remainder is zero is called factor.

int n=6;
for(int i=1;i<=n;i++)
{
if(n%i==0)
{
System.out.println(i);
}
}
2.>Write a java program to print factorial of number.

Factorial of Number
Factorial of Number is a product of 1 to given number.

int n=7;
int factorial=1;
for(int i=1;i<=n;i++)
{

factorial=factorial*i;

}
System.out.println(factorial);

3.>Write a java program to check number is prime or not.

Prime Number

A Number which is divisible by 1 and itself(count must be 2)

int n=9;
int count=0;
for(int i=1;i<=n;i++)
{
if(n%i==0)
{
count=count+1;
}
}
if(count==2)
{
System.out.println("prime");
}
else
{
System.out.println("Not prime");

4.>write a java program to check number is perfect or not.

Perfect Number

Sum of the factors is equal to the number excluding given number.

int n=6;
int ori=n;
int sum=0;
for(int i=1;i<n;i++)
{
if(n%i==0)
{
sum=sum+i;
}
}
if(sum==ori)
{
System.out.println("perfect");
}
else
{
System.out.println("Not perfect");

5.>Write a java program to print fibonacci series.

Fibonacci Series

The sum of 1st and 2nd and then 2nd number will become 1st and sum will become 2nd.

int first=0;
int second=1;
System.out.println(first);
System.out.println(second);
for(int i=2;i<=10;i++)
{
int sum=first+second;
System.out.println(sum);
first=second;
second=sum;
}

6.>Write a java program to print 1 to 10 prime numbers.


for(int i=1;i<=10;i++)
{
int c=0;
for(int j=1;j<=i;j++)
{
if(i%j==0)
{
c=c+1;
}
}
if(c==2)
{
System.out.println(i);
}
}

7.>Write a java program to print 1 to 100 perfect numbers.


for(int i=1;i<=100;i++)
{
int sum=0;
for(int j=1;j<i;j++)
{
if(i%j==0)
{
sum=sum+j;
}
}
if(sum==i)
{
System.out.println(i);
}
}

pattern programs

1>Square

*****
*****
*****
*****
*****

for(int i=1;i<=5;i++)
{
for(int j=1;j<=5;j++)
{
System.out.print("*");
}
System.out.println();
}

2.Incrementing Traingle

*
**
***
****
*****

for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print("*");
}
System.out.println();
}

3.>Decrementing Traingle

*****
****
***
**
*

for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
System.out.print("*");
}
System.out.println();
}
1
12
123
1234
12345

for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(j);

}
System.out.println();
}

1
22
333
4444
55555

for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(i);

}
System.out.println();
}
1
23
456
78910
1112131415

int c=1;
for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(c);
c++;
}
System.out.println();
}

1
21
321
4321
54321
for(int i=1;i<=5;i++)
{
for(int j=i;j>=1;j--)
{
System.out.print(j);
}
System.out.println();
}
5
54
543
5432
54321
for(int i=5;i>=1;i--)
{
for(int j=5;j>=i;j--)
{
System.out.print(j);
}
System.out.println();
}

5
44
333
2222
11111

for(int i=5;i>=1;i--)
{
for(int j=5;j>=i;j--)
{
System.out.print(i);
}
System.out.println();
}

5
45
345
2345
12345

for(int i=5;i>=1;i--)
{
for(int j=i;j<=5;j++)
{
System.out.print(j);
}
System.out.println();
}

12345
2345
345
45
5
for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
System.out.print(j);
}
System.out.println();
}

11111
2222
333
44
5
for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
System.out.print(i);
}
System.out.println();
}

*
**
***
****
*****

for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
System.out.print(" ");
}
for(int k=1;k<=i;k++)
{
System.out.print("*");
}
System.out.println();

}
1
12
123
1234
12345

for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
System.out.print(" ");
}
for(int k=1;k<=i;k++)
{
System.out.print(k);
}
System.out.println();
}

1
22
333
4444
55555
for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
System.out.print(" ");
}
for(int k=1;k<=i;k++)
{
System.out.print(i);
}
System.out.println();
}
1
21
321
4321
54321

for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
System.out.print(" ");
}
for(int k=i;k>=1;k--)
{
System.out.print(k);
}
System.out.println();
}

12345*
2345**
345***
45****
5*****

for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
System.out.print(j);
}
for(int k=1;k<=i;k++)
{
System.out.print("*");
}
System.out.println();
}
123451
234512
345123
451234
512345

for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
System.out.print(j);
}
for(int k=1;k<=i;k++)
{
System.out.print(i);
}
System.out.println();
}

*
***
*****
*******
*********

for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
System.out.print(" ");
}
for(int k=1;k<i;k++)
{
System.out.print("*");
}
for(int r=1;r<=i;r++)
{
System.out.print("*");
}
System.out.println();

*
1**
12***
123****
1234*****

for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
System.out.print(" ");
}
for(int k=1;k<i;k++)
{
System.out.print(k);
}
for(int r=1;r<=i;r++)
{
System.out.print("*");
}
System.out.println();

1
*12
**123
***1234
****12345

for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
System.out.print(" ");
}
for(int k=1;k<i;k++)
{
System.out.print("*");
}
for(int r=1;r<=i;r++)
{
System.out.print(r);
}
System.out.println();

1
112
12123
1231234
123412345

for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
System.out.print(" ");
}
for(int k=1;k<i;k++)
{
System.out.print("*");
}
for(int r=1;r<=i;r++)
{
System.out.print(r);
}
System.out.println();

1
222
33333
4444444
555555555

for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
System.out.print(" ");
}
for(int k=1;k<i;k++)
{
System.out.print(i);
}
for(int r=1;r<=i;r++)
{
System.out.print(i);
}
System.out.println();

*********
*******
*****
***
*

for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(" ");
}
for(int k=i;k<5;k++)
{
System.out.print("*");
}
for(int r=i;r<=5;r++)
{
System.out.print("*");
}
System.out.println();
}

1234*****
234****
34***
4**
*

for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(" ");
}
for(int k=i;k<5;k++)
{
System.out.print(k);
}
for(int r=i;r<=5;r++)
{
System.out.print("*");
}
System.out.println();
}
****12345
***2345
**345
*45
5

for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(" ");
}
for(int k=i;k<5;k++)
{
System.out.print("*");
}
for(int r=i;r<=5;r++)
{
System.out.print(r);
}
System.out.println();
}

123412345
2342345
34345
445
5
for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(" ");
}
for(int k=i;k<5;k++)
{
System.out.print(k);
}
for(int r=i;r<=5;r++)
{
System.out.print(r);
}
System.out.println();
}
111111111
2222222
33333
444
5

for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(" ");
}
for(int k=i;k<5;k++)
{
System.out.print(i);
}
for(int r=i;r<=5;r++)
{
System.out.print(i);
}
}

*
**
***
****
*****
*****
****
***
**
*
for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
System.out.print(" ");
}
for(int k=1;k<=i;k++)
{
System.out.print("*");
}
System.out.println();

}
for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(" ");
}
for(int k=i;k<=5;k++)
{
System.out.print("*");

}
System.out.println();

Jumping statements

Jumping statements are used to terminate loop and skip the particular iteration of a loop.
Jumping statements are divided into 2 types.They are
1.break
2.continue
Jumping Statements must be applied on loops.

1.break

break statement is used to terminate the loop when condition is satisfied.

for(int i=1;i<=10;i++)
{
if(i==6)
{
break;
}
else
{
System.out.println(i);
}
}

2.continue

continue statement is used to skip the iteration(element) and executes remaining elements.

for(int i=1;i<=10;i++)
{
if(i==6)
{
continue;
}
else
{
System.out.println(i);
}
}

Arrays

1.Arrays is a predefine class.[Arrays class is present in java.util.Arrays package)


2.Arrays is non primitive/refernce datatype.
3.The purpose of Arrays is to store multiple values with same datatype.
4.1.Arrays Declaration syntax
datatype[] arrayvariablename = new datatype[size];
arrayvariablename[0]=element1;
arrayvariablename[1]=element2;
.........................
arrayvariablename[n]=elementn;
int[] arr1=new int[4];================>declaration
arr[0]=2;
arr[1]=3; =============>Assigning values based on index values
arr[2]=6;
arr[3]=4;

2.Array Initialization
datatype[] arrayvarname={ele1,ele2,ele3,.....};
int[] arr={2,3,4,5};

5.Arrays is index based it supports only positive index starts from 0 and
size-1.
Negative index is not supports===>ArrayIndexOutOfBoundsException
int[] arr={2,3,4,5};
System.out.println(arr[0])=====>2
System.out.println(arr[2])=====>4
System.out.println(arr[-3])=====>ArrayIndexOutOfBoundsException

6.If we print Array directly it will gives memory address.


int[] arr={2,3,4,5};
System.out.println(arr)===============>[I@372f7a8d

7.There are 3 ways to print array elements


1.for loop
2.Enhanced forloop or ForEach loop
3.toString()
8.Arrays size is Fixed.
int[] arr1=new int[4];================>declaration
arr[0]=2;
arr[1]=3; =============>Assigning values based on index values
arr[2]=6;
arr[3]=4;
arr[4]=6;===============>ArrayIndexOutOfBoundsException
9.length

length is used to get total number of elements in array.


syntax
-------
datatype varname=arrayvarname.length;
int l=ab.length;
int[] arr={2,3,4,5};
int len=arr.length;
System.out.println(len);========>4

10.Array is by itself an object.

11.Enhanced forloop or ForEach loop


syntax
-------
for(datatype vranme : arrayvarname)
{
Statetement
}
12.Difference forloop and enhance forloop

forloop

1.contains Initialization.
2.contains condition.
3.contains updation

enchance forloop

1.Does not contains Initialization.


2.Does not contains condition.
3.Does not contains updation
4.Enchance forloop is faster(because it is not performing operations like
initilazition,condition,updation)

import java.util.Arrays;
Here java===>package
util===>sub package
Arrays==>class.

Examples

1.class Rohit
{
public static void main(String[] args)
{
int[] ab=new int[4];
ab[0]=2;
ab[1]=4;
ab[2]=6;
ab[3]=8;
System.out.println(ab);============>[I@372f7a8d
}
}
class Rohit
{
public static void main(String[] args)
{
int[] ab=new int[4];
ab[0]=2;
ab[1]=4;
ab[2]=6;
ab[3]=8;
for(int i=0;i<=3;i++)
{
System.out.println(ab[i]);
}

}
}

class Rohit
{
public static void main(String[] args)
{
int[] ab=new int[4];
ab[0]=2;
ab[1]=4;
ab[2]=6;
ab[3]=8;
ab[4]=10;======>ArrayIndexOutOfBoundsException
for(int i=0;i<=3;i++)
{
System.out.println(ab[i]);
}

}
}

class Rohit
{
public static void main(String[] args)
{
int[] ab=new int[4];
ab[-1]=2;
System.out.println(ab[-1]);===>ArrayIndexOutOfBoundsException

}
}

class Rohit
{
public static void main(String[] args)
{
byte[] b=new byte[3];
b[0]=4;
b[1]=1;
b[2]=6;
for(int i=0;i<=2;i++)
{
System.out.println(b[i]);
}

}
}

class Sample
{
public static void main(String[] args)
{
int[] ab=new int[3];
ab[0]=2;
ab[1]=3;
ab[2]=4;
int l=ab.length;
System.out.println(l);

}
}

class Sample
{
public static void main(String[] args)
{
int[] ch=new int[4];
ch[0]=6;
ch[1]=2;
ch[2]=4;
ch[3]=7;
for(int i=0;i<ch.length;i++)
{
System.out.println(ch[i]);
}

}
}

class Sample
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
System.out.println(a);===>[I@372f7a8d

}
}

program to print array elements of an array.


class Sample
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}

}
}
program to print index of an array.

class Sample
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
for(int i=0;i<a.length;i++)
{
System.out.println(i);
}

}
}

write a java program to print array elements by using enhanced forloop.


class Sample
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
for(int b : a)
{
System.out.println(b);
}

}
}

predefine methods

The methods which are already present in java software.The methods which are
developed by java developers.

import java.util.Arrays

userdefine methods

The methods which are not present in java software.The methods which are
developed by java programmers.

1.sort()

sort() is used to sort elements in ascending order.

syntax

Arrays.sort(arrayvarname);
import java.util.Arrays;
class Sample
{
public static void main(String[] args)
{
int[] a={6,3,2,1};
Arrays.sort(a);
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}

}
}

2.toString()

toString() is used to print array elements.

syntax

Arrays.toString(arrayvarname);

import java.util.Arrays;
class Demo
{
public static void main(String[] args)
{
int[] a={2,3,1,4};
System.out.println(Arrays.toString(a));======>[2, 3, 1, 4]
}
}

3.equals()

equals () is used to compare 2 Arrays and returns either true or false

syntax
-------
boolean varname=Arrays.equals(arrvarnam1,arrvarnam2)

import java.util.Arrays;
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
int[] b={1,2,3,4};
boolean res=Arrays.equals(a,b);
System.out.println(res);==================>true

}
}
import java.util.Arrays;
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
int[] b={1,2,3,4,5};
boolean res=Arrays.equals(a,b);
System.out.println(res);============>false

}
}

import java.util.Arrays;
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
int[] b={1,2,4,3};
boolean res=Arrays.equals(a,b);
System.out.println(res);================>false

}
}

4.mismatch()

mismatch() returns -1 when both arrayelements are same


returns particular index where element is not matched

syntax
-------
int varname= Arrays.mismatch(arrayvarname1,arrayvarmae2);

import java.util.Arrays;
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
int[] b={1,2,3,4};
int abc=Arrays.mismatch(a,b);
System.out.println(abc);==================>-1

}
}

import java.util.Arrays;
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
int[] b={5,2,3,4};
int abc=Arrays.mismatch(a,b);
System.out.println(abc);========================>0

}
}

import java.util.Arrays;
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
int[] b={1,2,8,4};
int abc=Arrays.mismatch(a,b);
System.out.println(abc);=====================>2

}
}

5.binarySearch()

binarySearch() is used to get particular index of an element if it is present.

syntax
-------
int varname=Arrays.binarySearch(arrayvarname,element);

import java.util.Arrays;
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
int bhavadeesh=Arrays.binarySearch(a,3);
System.out.println(bhavadeesh);================>2

}
}

import java.util.Arrays;
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
int bhavadeesh=Arrays.binarySearch(a,4);
System.out.println(bhavadeesh);=================>3

}
}

import java.util.Arrays;
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
int bhavadeesh=Arrays.binarySearch(a,6);===========>-5
System.out.println(bhavadeesh);

}
}

import java.util.Arrays;
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
int bhavadeesh=Arrays.binarySearch(a,0);
System.out.println(bhavadeesh);=================>-1

}
}

import java.util.Arrays;
class Demo
{
public static void main(String[] args)
{
int[] a={2,4,7,8,9,10};
int bhavadeesh=Arrays.binarySearch(a,5);
System.out.println(bhavadeesh);================>-3

}
}

import java.util.Arrays;
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
int bhavadeesh=Arrays.binarySearch(a,5);
System.out.println(bhavadeesh);=====================>-5

}
}

6.copyOfRange()

copyOfRange() is used to copy array elements from 1 array into another array.

syntax
------
datatype[] varname=Arrays.copyOfRange(arrayvarname,startindex,endindex);
import java.util.Arrays;
class Demo
{
public static void main(String[] args)
{
int[] onearray={2,4,7,8,9,10};
int l=onearray.length;
int[] anotherarr=Arrays.copyOfRange(onearray,0,l-1);
System.out.println(Arrays.toString(anotherarr));===>[2,4,7,8,9]

}
}

import java.util.Arrays;
class Demo
{
public static void main(String[] args)
{
int[] onearray={2,4,7,8,9,10};
int l=onearray.length;
int[] anotherarr=Arrays.copyOfRange(onearray,0,3);
System.out.println(Arrays.toString(anotherarr));======>[2,4,7]

}
}

import java.util.Arrays;
class Demo
{
public static void main(String[] args)
{
int[] onearray={2,4,7,8,9,10};
int l=onearray.length;
int[] anotherarr=Arrays.copyOfRange(onearray,2,4);
System.out.println(Arrays.toString(anotherarr));=======>7,8

}
}

1.write a java program to print 1st,2nd and last element of an array.

int[] a={2,1,4,5,6};
System.out.println(a[0]);========================>2
System.out.println(a[1]);========================>1
System.out.println(a[a.length-1]);===============>6
a[5-1]
a[4]==========================>6

2.write a java program to print to add 1st and last element of an array.
int[] a={2,1,4,5,6};
int first=a[0];
int last=a[a.length-1];
System.out.println(first+last);
3.write a java program to swap to 1st and last element of an array.
import java.util.*;
class Demo
{
public static void main(String[] args)
{
int[] a={2,1,4,5,6};
int temp=a[0];
a[0]=a[a.length-1];
a[a.length-1]=temp;
System.out.println(a[0]);
System.out.println(a[a.length-1]);
System.out.println(Arrays.toString(a));

}
}

4.Write a java program to print array elements.


int[] arr={1,7,6,5};
for(int i=0;i<=arr.length-1;i++)
{
System.out.println(arr[i]);
}

5.Write a java program to print index values of an array.


int[] arr={1,7,6,5};
for(int i=0;i<=arr.length-1;i++)
{
System.out.println(i);
}

6.Write a java program to print even elements of an array.


int[] arr={1,7,6,5,2,4};
for(int i=0;i<arr.length;i++)====>to get array elements
{
if(arr[i]%2==0)===========>check even logic
{
System.out.println(arr[i]);
}
}

int[] arr={1,2,3,4,5};
for(int i=0;i<arr.length;i++)
{
if(arr[i]%2!=0)
{
System.out.println(arr[i]);
}
}

7.Write a java program to print count even numbers of an array

int[] arr={1,7,6,5,2,4};
int count=0;
for(int i=0;i<arr.length;i++)
{
if(arr[i]%2==0)
{
count++;
}
}
System.out.println(count);

8.Write a java program to print sum of all the elements of an array.

int[] a={1,2,3};
int sum=0;
for(int i=0;i<a.length;i++)
{
sum=sum+a[i];

}
System.out.println(sum);

9.Write a java program to print prime numbers of an array.


int[] a={1,2,3,4,5,6,7};
for(int i=0;i<a.length;i++)===>get elements from an array
{
int count=0;
for(int j=1;j<=a[i];j++)==>check prime logic
{
if(a[i]%j==0)
{
count=count+1;

}
}
if(count==2)
{
System.out.println(a[i]);
}
}

10.write a java program to reverse array elements

int[] arr={2,4,3,1};
for(int i=arr.length-1;i>=0;i--)
{
System.out.println(arr[i]);
}

11.write a java program to print duplicate elements of an array

int[] a={1,2,3,1};
for(int i=0;i<a.length;i++)
{
for(int j=i+1;j<a.length;j++)
{
if(a[i]==a[j])
{
System.out.println(a[i]);
}
}
}

int[] a={1,2,3,1,2,1};
for(int i=0;i<a.length;i++)
{
for(int j=i+1;j<a.length;j++)
{
if((a[i]!=0)&&(a[i]==a[j]))
{
System.out.println(a[i]);
a[j]=0;
break;
}
}
}
int[] a={1,2,3,1,2,1};
for(int i=0;i<a.length;i++)
{
int x=a[i];
boolean f=false;
for(int j=i+1;j<a.length;j++)
{
if(x!=9292 && a[i]==a[j])
{
a[j]=9292;
f=true;
}
}
if(f==true)
{
System.out.println(a[i]);
}
}

12.write a java program to sort an array without predefined methods.

int[] a={5,4,1,2};
for(int i=0;i<a.length;i++)
{
for(int j=i+1;j<a.length;j++)
{
if(a[i]>a[j])
{
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
for(int k=0;k<a.length;k++)
{
System.out.println(a[k]);
}

13.write a java program to find maximum number of an array.

1.want to sort of an array


2.compare 1st and 2nd element
3.if 1st element is greater than 2nd element
4.we have to swap.
5.After swapping the elements will be small to big.
6.To print 2nd maximum length-1.

int[] a={1,5,4,3,2};
for(int i=0;i<a.length;i++)
{
for(int j=i+1;j<a.length;j++)
{
if(a[i]>a[j])
{
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
System.out.println(a[a.length-1]);

int[] a={2,1,3,5,6};
int max=a[0];
for(int i=1;i<a.length;i++)
{
if(a[i]>max)
{
max=a[i];
}
}
System.out.println(max);

14.write a java program to find 2nd maximum number of an array.

1.want to sort of an array


2.compare 1st and 2nd element
3.if 1st element is greater than 2nd element
4.we have to swap.
5.After swapping the elements will be small to big.
6.To print 2nd maximum length-2.

int[] a={1,5,4,3,2};
for(int i=0;i<a.length;i++)
{
for(int j=i+1;j<a.length;j++)
{
if(a[i]>a[j])
{
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
System.out.println(a[a.length-2]);

15.write a java program to copy array elements into another array

int[] a1={1,2,3,4,5};
int[] a2=new int[a1.length];
for(int i=0;i<a1.length;i++)
{
a2[i]=a1[i];
System.out.println(a2[i]);
}

16.write a java program to print even numbers in left side and odd numbers in right
side.

int[] a1={1,2,3,4,5,6,7,8,9,10};
int[] output=new int[a1.length];
int evenindex=0;
int oddindex=a1.length-1;
for(int i=0;i<a1.length;i++)
{
if(a1[i]%2==0)
{
output[evenindex]=a1[i];
evenindex++;
}
else
{
output[oddindex]=a1[i];
oddindex--;
}
}
for(int anything : output)
{
System.out.println(anything);
}

17.Write a java program to find element is found or not.


int[] a={1,2,3,4,5};
int target=5;
for(int i=0;i<a.length;i++)
{
if(a[i]==target)
{
System.out.println("element found");
}

18.Write a java program to shift array elements to left side and first element to last.

import java.util.*;
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4,5};
int first=a[0];
for(int i=0;i<a.length-1;i++)
{
a[i]=a[i+1];
}
a[a.length-1]=first;
System.out.println(Arrays.toString(a));
}
}

19.Write a java program to print leader elements of an array.

int[] a={7,9,10,11,2};
int max=a[a.length-1];
System.out.println(max);
for(int i=a.length-2;i>=0;i--)
{
if(a[i]>max)
{
System.out.println(a[i]);
max=a[i];
}
}

20.Write a java program to merge to arrays and copy into another array.

int[] a={1,2,3};
int[] b={4,5,6};
int l1=a.length;
int l2=b.length;
int[] c=new int[l1+l2];
for(int i=0;i<a.length;i++)
{
c[i]=a[i];
}
int an=l1;
for(int j=0;j<b.length;j++)
{
c[an]=b[j];
an++;
}
System.out.println(Arrays.toString(c));

21.Write a java program to print unique elements of an array

import java.util.*;
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,1,2,1};
for(int i=0;i<a.length;i++)
{
for(int j=i+1;j<a.length;j++)
{
if(a[i]==a[j])
{
a[j]=0;
}
}
}
System.out.println(Arrays.toString(a));
for(int j=0;j<a.length;j++)
{
if(a[j]!=0)
{
System.out.println(a[j]);
}
}

}
}

22.Write a java program to print all pair of elements whose sum equals to 10.

int[] a={6,3,9,1,2,8,4,5};
for(int i=0;i<a.length-1;i++)
{
for(int j=i+1;j<a.length;j++)
{
if(a[i]+a[j]==10) 6,4
{ 9,1
System.out.println(a[i]+" "+a[j]); 8,2
}
}
}

23.Write a java program to print all subarrays of an array.

int[] a={1,2,3,4,5};
for(int i=0;i<a.length;i++)
{
for(int j=i;j<a.length;j++)
{
for(int k=i;k<=j;k++)
{
System.out.print(a[k]);
}
System.out.println();
}

24.Write a java program to print possible sub arrays where target sum=9

int[] a={1,2,3,4,5};
int target=9;
int max=Integer.MIN_VALUE;
for(int i=0;i<a.length;i++)
{
int sum=0;
for(int j=i;j<a.length;j++)
{
sum=sum+a[j];
if(sum==target)
{
for(int k=i;k<=j;k++)
{
System.out.print(a[k]);
}
System.out.println();

}
}

25.Write a java program to print missing number.

int[] a={5,3,1,2};
int n=a.length+1;
int sum=n*(n+1)/2;
int restSum=0;
for (int i = 0; i < a.length; i++) {
restSum+=a[i];
}
int missingNumber=sum-restSum;
System.out.println(missingNumber);

Multidimensional Arary

Array in another array is called Multidemsional array.


Multidemsional array is a combination of rows and columns.

class Demo
{
public static void main(String[] args)
{ r c
int[][] v=new int[3][3];
for(int i=0;i<3;i++)=================>rows
{
for(int j=0;j<3;j++)=============>columns
{
System.out.print(v[i][j]);
}
System.out.println();==================>000
} 000
} 000
}

class Demo
{
public static void main(String[] args)
{
int[][] v=new int[3][3];
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.println(v[i][j]);=================>
}

}
}
}
0
0
0
0
0
0
0
0
0

class Demo
{
public static void main(String[] args)
{
int[][] a=new int[2][3];
a[0][0]=1;
a[0][1]=2;
a[0][2]=3;
a[1][0]=4;
a[1][1]=5;
a[1][2]=6;
for(int i=0;i<2;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(a[i][j]);
}
System.out.println();
}
}
}

class Demo
{
public static void main(String[] args)
{
int[][] a={{1,2,3},{4,5,6}};
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[i].length;j++)
{
System.out.print(a[i][j]);
}
System.out.println();
}
}
}

jagged Array

Jagged Array is one type of multidimensional array.


The elements size is different from row to another row.

class Demo
{
public static void main(String[] args)
{
int[][] a={{1,2,3,7},{4,5,6}};
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[i].length;j++)
{
System.out.print(a[i][j]);
}
System.out.println();
}
}
}

1.Write a java program to add 2*2 matrix.

int[][] a={{1,2},{3,4}};
int[][] b={{5,6},{7,8}};
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[i].length;j++)
{
System.out.print(a[i][j]+b[i][j]+" ");
}
System.out.println();
}

2.Write a java program to subtract 2*2 matrix

int[][] a={{5,6},{7,8}};
int[][] b={{1,2},{2,4}};
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[i].length;j++)
{
System.out.print(a[i][j]-b[i][j]+" ");
}
System.out.println();
}

3.Write a java program to multiply 2*2 matrix

int[][] a={{1,2},{3,4}};
int[][] b={{1,1},{1,1}};
int[][] c=new int[2][2];
for(int i=0;i<2;i++)
{

for(int j=0;j<2;j++)
{
c[i][j]=0;

for(int k=0;k<2;k++)
{
c[i][j]+=a[i][k]*b[j][k];

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

String Handling

1.String
2.StringBuffer
3.StringBuilder
4.StringTokenizer
Note:String,StringBuffer,StringBuilder is present in java.lang package(bydefault).

1.String

1.String is a predefine class.


2.The purpose of String is to store multiple characters enclosed with double quotes.
3.String value can be stored in 2 ways.
1.By using directly(literal)
2.By using new keyword
4.String is immutable.
5.String is synchronized.
6.String is thread safe.

7.Difference between literal and new keyword.

1.By using literal

1.In literal string data stored in String constant pool(scp) area.


2.In literal String data is same in 2 variables then it will create one object.

String s1="pawan";
System.out.println(s1);===============================>pawan
System.out.println(System.identityHashCode(s1));==========>359023572
String s2="pawan";
System.out.println(s2);===============================>pawan
System.out.println(System.identityHashCode(s2));==========>359023572

1.By using new Keyword

1.In new Keyword string data stored in Heap area.


2.In new keyword string data is same in 2 variables then it will create 2 objects.

String s1=new String("pawan");


System.out.println(s1);===============================>pawan
System.out.println(System.identityHashCode(s1));==========>359023572
String s2=new String("pawan");
System.out.println(s2);==============================>pawan
System.out.println(System.identityHashCode(s2));========>305808283

8.Difference between equals() and ==.


equals() is used to compare string data and returns either true or false
== is used to compare memory address (identityhashcode) and returns either true or false.

String s1="pawan";
System.out.println(s1);
System.out.println(System.identityHashCode(s1));
String s2="pawan";
System.out.println(s2);
System.out.println(System.identityHashCode(s2));
System.out.println(s1.equals(s2));==============================>true
System.out.println(s1==s2);=====================================>true
System.out.println("===================================");
String s3=new String("pawan");
System.out.println(s3);
System.out.println(System.identityHashCode(s3));
String s4=new String("pawan");
System.out.println(s4);
System.out.println(System.identityHashCode(s4));
System.out.println(s3.equals(s4));========================>true
System.out.println(s3==s4);===============================>false

9.Difference between mutable and immutable.


mutable

1.mutable means data can be changed.


2.mutable classes are may or may not be synchronized.
3.Before and after operations hashCode will be same.

immutable

1.immutable means data cannot be changed.


2.immutable classes are synchronized.
3.Before and after operations hashCode will be different.

Examples

1.
String sname="Hemanth Kumar";
System.out.println(sname);===================>Hemanth Kumar

2. String sname=new String("Hemanth Kumar");


System.out.println(sname);===================>Hemanth Kumar

Predefine methods in String

1.charAt()

charAt() is used to get character by passing index.

syntax

datatype varname=stringvarname.charAt(index);

String s="Hemanth";
char abc=s.charAt(3);
System.out.println(abc);========>a

2.indexOf()

indexOf() is used to get first occurance index by passing character.

syntax

datatype varname=svn.indexOf(character);

String s="Hemanth";
int ad=s.indexOf('a');
System.out.println(ad);===============>3

String s="Haemanth";
int ad=s.indexOf('a');
System.out.println(ad);===============>1
3.lastIndexOf()

lastIndexOf() is used to last occurance index by passing character.

syntax

datatype varname=svn.lastIndexOf(character)

String s="Haemanth";
int b=s.lastIndexOf('a');
System.out.println(b);================>4

4.substring()

substring() is used to get particular characters by passing startindex and end index.

syntax

datatype varname=svn.substring(startindex,endindex);
String s="Hemanth";
int len=s.length();
System.out.println(len);
String xyz=s.substring(0,len);
System.out.println(xyz);

String s="Hemanth";

String xyz=s.substring(4);
System.out.println(xyz);============>nth

5.length()

length() is used to get total number of characters.

syntax

datatype varname=svn.length();

String s="Hemanth";
int len=s.length();
System.out.println(len);=============>7

6.split()

split() is used split(divide) the data based on delibiter(symbol)

syntax

datatype[] varname=svn.split(character);
String s="Heman kuma rah";
String[] abc=s.split(" ");
System.out.println(Arrays.toString(abc));==========>[Heman,kuma,rah]

String s="Hemankumarah";
String[] abc=s.split("a");
System.out.println(Arrays.toString(abc));==========>[Hem,nkum,r,h]

7.toCharArray()

toCharArray() is used to convert String into character Array.

datatype[] varname=svn.toCharArray();

String s="Durga";
char[] vn=s.toCharArray();
System.out.println(Arrays.toString(vn));=========>[D,u,r,g,a]

8.equals()

equals() returns either true or false by considering String case.

syntax

datatype varname=svn1.equals(svn2)

String s1="virat";
String s2="virat";
boolean anc=s1.equals(s2);
System.out.println(anc);================>true

String s1="vIrat";
String s2="virat";
boolean anc=s1.equals(s2);
System.out.println(anc);=============>false

9.equalsIgnoreCase()

equals() returns either true or false by without considering String case.

syntax

datatype varname=svn1.equals(svn2)

String s1="virat";
String s2="virat";
boolean anc=s1.equalsIgnoreCase(s2);
System.out.println(anc);================>true

String s1="vIrat";
String s2="virat";
boolean anc=s1.equalsIgnoreCase(s2);
System.out.println(anc);=============>true

10.concat()

concat() is used to combine or join add 2 strings.


syntax

datatype varname=svn.concat();

String s1="virat";
String s2="kohli";
String fullname=s1.concat(s2);
System.out.println(fullname);==============>viratkohli

String s1="virat";
String fullname=s1.concat("kohli");
System.out.println(fullname);==============>viratkohli

11.parseInt()

parseInt() is used to convert String into int.

syntax

datatype varname=Integer.parseInt(svn);

String s="123";
System.out.println(s+5);======>1235
int a=Integer.parseInt(s);
System.out.println(a+5);=====>128

String s="onetwothree";
System.out.println(s);
int a=Integer.parseInt(s);
System.out.println(a);=================>NumberFormatException

12.valueOf()

valueOf() is used to convert int into String.

syntax

datatype varname=String.valueOf(intvarname)

int a=123;
String s=String.valueOf(a);
System.out.println(s);=============>123

13.startsWith()

startsWith() returns either true(if sequence of characters are matched) or false(if sequence of characters are not
matched)

syntax

datatype varname=svn.startsWith(char);

String s="dhoni";
boolean vn=s.startsWith("d");
System.out.println(vn);===========>true
String s="dhoni";
boolean vn=s.startsWith("dho");
System.out.println(vn);=========>true

String s="dhoni";
boolean vn=s.startsWith("ho");
System.out.println(vn);========>false

13.endsWith()

endsWith() returns either true(if sequence of characters are matched) or false(if sequence of characters are not
matched)

syntax

datatype varname=svn.startsWith(char);

String s="dhoni";
boolean vn=s.endsWith("i");
System.out.println(vn);===========>true

String s="dhoni";
boolean vn=s.endsWith("ni");
System.out.println(vn);=========>true

String s="dhoni";
boolean vn=s.endsWith("ho");
System.out.println(vn);========>false

14.replace()

replace() is used to replace old character with new character.

syntax

datatype varname=svn.replace(oldchar,newchar)

String s="roshan";
String res=s.replace('r','t');
System.out.println(res);==============>toshan

15.replaceAll()

replaceAll() is used to replace sequence of old characters with new characters.

syntax

datatype varname=svn.replaceAll(oldcharacters,newcharacters)

String s="roshan";
String res=s.replaceAll("ros","tra");
System.out.println(res);============>trahan

16.toUpperCase()

toUpperCase() is used to convert any string to uppercase.


String s="roshan";
String s2=s.toUpperCase();
System.out.println(s2);==========>ROSHAN

17.toLowerCase()

toLowerCase() is used to convert any string to uppercase.

String s="RosHan";
String s2=s.toLowerCase();
System.out.println(s2);===============>roshan

18.hashCode()

hashCode() is used to print hashcode based String data.

syntax

datatype varname=svn.hashCode();

String s="roshan";
int xyz=s.hashCode();
System.out.println(xyz);===========>-925204225

2.StringBuffer

1.StringBuffer is a predefine class.


2.The purpose of StringBuffer is to store multiple characters enclosed with double quotes("").
3.StringBuffer value can be stored in 1 way.
1.By using new Keyword.
StringBuffer s=new StringBuffer("virat kohli");===========>virat kohli
System.out.println(s);

StringBuffer s="virat";
System.out.println(s);==============>error

4.StringBuffer is mutable.
5.StringBuffer is synchronized.
6.StringBuffer is thread safe.

predefine methods in StringBuffer

1.append()

append() is used to add new stringBuffer to the end of old stringBuffer.

syntax

datatype varname=sbvn.append(string);

StringBuffer s=new StringBuffer("pawan");


StringBuffer s2=s.append("kalyan");
System.out.println(s2);=======================>pawankalyan

String s="virat";
String s2=s.append("kohli");
System.out.println(s2);========================>error

2.insert()

insert() is used to insert particular character by passing index.

syntax

datatype varname=sbvn.insert(index,char);

StringBuffer s=new StringBuffer("Bhavadeesh");


StringBuffer s2=s.insert(1,'a');
System.out.println(s2);==============>Bahavadeesh

3.delete()

delete() is used to delete particular characters by passing index values.

syntax

datatype varname=sbvn.delete(startindex,endindex);
StringBuffer s=new StringBuffer("Bhavadeesh");
StringBuffer s2=s.delete(1,4);
System.out.println(s2);=========>Badeesh

4.reverse()

reverse() is used to reverse StringBuffer.

syntax

datatype varname=sbvn.reverse();
StringBuffer s=new StringBuffer("Bhavadeesh");
StringBuffer s2=s.reverse();
System.out.println(s2);============>hseedavahB

Write a java program to convert String into StringBuffer and reverse.

String s="virat";
StringBuffer s2=new StringBuffer(s);
StringBuffer s3=s2.reverse();
System.out.println(s3);

Write a java program to prove that String is immutable and StringBuffer is mutable

String s="virat";
s.concat("kohli");
System.out.println(s);=================================>virat
System.out.println("=========================");
StringBuffer s2=new StringBuffer("Mahesh");
s2.append("Babu");
System.out.println(s2);==============================>Mahesh Babu

String s="virat";
System.out.println(s.hashCode());=========================>112216210
String s2=s.concat("kohli");
System.out.println(s2.hashCode());========================>-2089279825
System.out.println("=====================");
StringBuffer s3=new StringBuffer("Rohit");
System.out.println(s3.hashCode());========================>305808283

StringBuffer s6=new StringBuffer("sharma");


StringBuffer s4=s3.append(s6);
System.out.println(s4.hashCode());========================>305808283

3.StringBuilder

1.StringBuilder is a predefine class.


2.The purpose of StringBuilder is to store multiple characters enclosed with double quotes("").
3.StringBuilder value can be stored in 1 way.
1.By using new Keyword.
StringBuilder s=new StringBuilder("virat kohli");===========>virat kohli
System.out.println(s);

StringBuilder s="virat";
System.out.println(s);==============>error

4.StringBuilder is mutable.
5.StringBuilder is not synchronized.
6.StringBuilder is not thread safe.

4.StringTokenizer

1.StringTokenizer is a predefine class.


2.StringTokenizer is present in java.util package.
3.The purpose of StringTokenizer is used to break or divide the String into tokens.
splitting the data based on delibiter.
4.StringTokenizer predefine methods
1.hasMoreElements()
2.nextElement()

1.hasMoreElements()(condition)

hasMoreElements() is used to check element is available or not.

2.nextElement()(output)

nextElement() is used to print the avialble element.

StringTokenizer s=new StringTokenizer("virat is a champ");


System.out.println(s.countTokens());
while(s.hasMoreElements())
{
System.out.println(s.nextElement());
}

import java.util.*;
class Demo
{
public static void main(String[] args)
{
StringTokenizer s=new StringTokenizer("vi_ra_ta","_");
System.out.println(s.countTokens());
while(s.hasMoreElements())
{
System.out.println(s.nextElement());
}
}
}

import java.util.*;
class Demo
{
public static void main(String[] args)
{
StringTokenizer s=new StringTokenizer("virat");

System.out.println(s);====================================>java.util.StringTokenizer@5e265ba
4
}
}

programs on Strings

1.Write a java program to check 1st character is vowel or consonant in String.

String s="virat";
if((s.charAt(0)=='a')||(s.charAt(0)=='e')||(s.charAt(0)=='i')||
(s.charAt(0)=='o')||(s.charAt(0)=='u')||(s.charAt(0)=='A')||
(s.charAt(0)=='E')||(s.charAt(0)=='I')||(s.charAt(0)=='O')||
(s.charAt(0)=='U'))
{
System.out.println("vowel");
}
else
{
System.out.println("Not vowel");
}

2.Write a java program to check each character of String is vowel or consonant.

String s="virat";
for(int i=0;i<s.length();i++)
{
if((s.charAt(i)=='a')||(s.charAt(i)=='e')||(s.charAt(i)=='i')||
(s.charAt(i)=='o')||(s.charAt(i)=='u')||(s.charAt(i)=='A')||
(s.charAt(i)=='E')||(s.charAt(i)=='I')||(s.charAt(i)=='O')||
(s.charAt(i)=='U'))
{
System.out.println("vowel");
}
else
{
System.out.println("consonant");
}
}

3.Write a java program to take 1 string data store in s1 and take empty string s2 copy s1 data in
s2.

String s1="virat";
String s2="";
for(int i=0;i<s1.length();i++)
{
s2=s2+s1.charAt(i);
}
System.out.println(s2);

4.Write a java program to reverse a String.

String s1="virat";
String s2="";
for(int i=s1.length()-1;i>=0;i--)
{
s2=s2+s1.charAt(i);
}
System.out.println(s2);

5.Write a java program to convert 1 character of string into capital.


String s1="virat";
char ch=s1.charAt(0);
int av=ch-32;
char cn=(char)av;
System.out.println(cn);

6.Write a java program to check string is palindrome or not.

String s1="madam";
String s2="";
for(int i=s1.length()-1;i>=0;i--)
{
s2=s2+s1.charAt(i);
}
if(s1.equals(s2))
{
System.out.println("palindrome");
}
else
{
System.out.println("Not palindrome");
}

7.Write a java program to check given Strings are anagram or not.


String s1="bhav";
String s2="vhab";
char[] c1=s1.toCharArray();
char[] c2=s2.toCharArray();
Arrays.sort(c1);
Arrays.sort(c2);
if(Arrays.equals(c1,c2))
{
System.out.println("Anagarm");
}
else
{
System.out.println("Not Anagarm");
}

8.write a java program to count alphabets,digits,symbols in string


String s="virat19@a";
int alpha=0;
int digit=0;
int symbol=0;
for(int i=0;i<s.length();i++)
{
if((s.charAt(i)>='a' && s.charAt(i)<='z') ||(s.charAt(i)>='A'&&
s.charAt(i)<='Z'))
{
alpha++;
}
else if(s.charAt(i)>='0' && s.charAt(i)<='9' )
{
digit++;
}
else
{
symbol++;
}

}
System.out.println(alpha);
System.out.println(digit);
System.out.println(symbol);

9.Write a java program to print Ascii values for given string


String s="Bhavi";
for(int i=0;i<s.length();i++)
{
char ch=s.charAt(i);
System.out.println(ch+":"+(int)(ch));
}

10.Write a java program to convert uppercase letters into lowercase in String.

String s="BhavI";
String res="";
for(int i=0;i<s.length();i++)
{
char ch=s.charAt(i);
if(ch>='A' && ch<='Z')
{
res=res+(char)+(ch+32);
}
else
{
res=res+ch;
}
}
System.out.println(res);

11.Write a java program to print length of each word.

String[] s={"virat","is", "a", "champ"};


for(int i=0;i<s.length;i++)
{
String res=s[i];
System.out.println(res.length());
}

12.Write a java program to reverse each word of String.

String[] s={"virat","is", "a", "champ"};


for(int i=0;i<s.length;i++)
{
String res=s[i];
for(int j=res.length()-1;j>=0;j--)
{
System.out.print(res.charAt(j));
}
System.out.println();
}

13.Write a java program to find longest word in a String.


String[] s={"viratkohli","is", "a", "champ"};
int max=s[0].length();
int index=0;
for(int i=1;i<s.length;i++)
{
if(s[i].length()>max)
{
max=s[i].length();
index=i;
}

}
System.out.println(s[index]);

14.Write a java program to remove spaces.

String s="virat is a king";


String res=s.replaceAll(" ","");
System.out.println(res);
String res1=s.replaceAll("\\s","");
System.out.println(res1);

15.Write a java program to remove spaces without predefine methods.

String s="virat is a king";


String res="";
for(int i=0;i<s.length();i++)
{
char ch=s.charAt(i);
if(ch!=' ')
{
res=res+ch;
}
else
{
res=res+s.charAt(i+1);
}
}
System.out.println(res);

16.Write a java program to each character frequency in string.

String s="ababac";
for(char ch='a';ch<='z';ch++)
{
int count=0;
for(int i=0;i<s.length();i++)
{
char nc=s.charAt(i);
if(nc==ch)
{
count=count+1;
}
}
if(count>0)
{
System.out.println(ch+":"+count);
}
}

String s="aabbabcc";
int[] count=new int[256];
for(int i=0;i<s.length();i++)
{
count[(int)s.charAt(i)]++;
}
for(int i=0;i<count.length;i++)
{
if(count[i]!=0)
{
System.out.println((char)i+" : "+count[i]);
}
}

17.Write a java program to print duplicate characters in string.

String s="ababac";
for(char ch='a';ch<='z';ch++)
{
int count=0;
for(int i=0;i<s.length();i++)
{
char nc=s.charAt(i);
if(nc==ch)
{
count=count+1;
}
}
if(count>1)
{
System.out.println(ch+":"+count);
}
}

18.Write a java program to print unique characters in string.

String s="ababac";
for(char ch='a';ch<='z';ch++)
{
int count=0;
for(int i=0;i<s.length();i++)
{
char nc=s.charAt(i);
if(nc==ch)
{
count=count+1;
}
}
if(count==1)
{
System.out.println(ch+":"+count);
}
}

19.Write a java program to print characters in aplhabets order.


String s="bhavi";
int asc=96;
for(int i=0;i<s.length();i++)
{
char ch=s.charAt(i);
int res=ch-asc;
System.out.println(ch+":"+res);
}

20.Write a java program to print all String permutations.

class Demo
{
public static void main(String[] args)
{
String s="abc";
for(char x='a';x<='c';x++)
{
for(char y='a';y<='c';y++)
{
for(char z='a';z<='c';z++)
{
if(x!=y && y!=z && z!=x)
{
System.out.println(x+" "+y+" "+z);
}
}

}
}
}
}

21.Write a java program to check one string rotation is another String.


String os="aradhya";
String ks="radhyaa";
String ns=os.concat(os);
if(ns.contains(ks))
{
System.out.println("Rotational string");
}
else
{
System.out.println("Not Rotational string");

Scanner

1.Scanner is a predefine class.


2.The purpose of Scanner is to take input from console(command prompt) and printing
output in command prompt.
3.Scanner is present in java.util package.

Steps to take input from Scanner.

1.import java.util package


2.Create object for Scanner class.
3.1.int-------->nextInt()
2.float------>nextFloat()
3.double----->nextDouble()
4.boolean---->nextBoolean()
5.char------->next().charAt(index)
6.String----->1.next()
2.nextLine()
import java.util.Scanner;
class Demo
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

int a=sc.nextInt();
System.out.println("output is"+a);============>output is 12
}
}

import java.util.*;
class Sample
{
public static void main(String[] args)
{
Scanner s1=new Scanner(System.in);
System.out.println("enter float num=");
float num=s1.nextFloat();
System.out.println(num);
}
}

import java.util.Scanner;
class Demo
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("enter num=");
int a=sc.nextInt();
System.out.println("output is"+a);
}
}

import java.util.*;
class Sample
{
public static void main(String[] args)
{
Scanner s1=new Scanner(System.in);
System.out.println("enter double num=");
double num=s1.nextDouble();
System.out.println(num);
}
}

import java.util.*;
class Sample
{
public static void main(String[] args)
{
Scanner s1=new Scanner(System.in);
System.out.println("enter boolean value=");
boolean b=s1.nextBoolean();
System.out.println(b);
}
}

import java.util.*;
class Demo
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("enter char value=");
char ch=sc.next().charAt(0);
System.out.println(ch);
}
}

enter char value=


99
9

import java.util.*;
class Demo
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("enter string 1 word=");
String s=sc.next();
System.out.println(s);
}
}

enter string 1 word=


Ajay is java student
Ajay

enter string 1 word=


Ajay
Ajay

import java.util.*;
class Demo
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("enter string no.of words=");
String s=sc.nextLine();
System.out.println(s);
}
}

enter string no.of words


Hemanth is a good boy
Hemanth is a good boy

Difference between next() and nextLine()


1.next() is used to take only 1 word
2.nextLine() is used to take multiple words.
import java.util.*;
public class Demo
{

public static void main(String[] args)


{
Scanner sc=new Scanner(System.in);
System.out.println("enter size=");
int size=sc.nextInt();

int[] arr=new int[size];


System.out.println("enter elements");
for(int i=0;i<arr.length;i++)
{
arr[i]=sc.nextInt();
}
System.out.println(Arrays.toString(arr));3

}
}

enter size=
3
enter elements
2
4
6
[2, 4, 6]

Methods

1.Method is collection of gruop of statements.


2.The purpose of method is to perform task and produce code resuabiltity.

3.Methods contains 3 parts


1.method heading
2.method body
3.method calling

1.method heading

Method heading is a collection of returntype,methodname and formal parameters.


2.method body

Method body is a collection group of statements.

3.Formal parameters

Formal parameters purpose is to take values(actual arguments) from method calling.

4.Actual Arguments

Actual arguments purpose is to send values to(variables) formal parameters in method heading

void

void is return type and returns empty.

syntax

returntype methodName(formal parameters)


{

statements

class Sample
{
void suresh(int a)
{
System.out.println(a);=======================================>8
}
public static void main(String[] args)
{
Sample s1=new Sample();
s1.suresh(8);

}
}

Methods can define 4 ways.

1.with formal parameters and without return statement


2.without formal parameters and without return statement
3.with formal parameters and with return statement
4.without formal parameters and with return statement.

void======================>System.out.println()
Datatype==================>return

1.with formal parameters and without return statement

class Demo
{
void parithosh(String s)
{
System.out.println(s);
}
public static void main(String[] args)
{
Demo d1=new Demo();
d1.parithosh("virat");

}
}

2.without formal parameters and without return statement

class Demo
{
void parithosh()
{
System.out.println("method topic started");
}
public static void main(String[] args)
{
Demo d1=new Demo();
d1.parithosh();

}
}

class Sample
{

void add(int a,int b)


{
System.out.println(a+b);
}
public static void main(String[] args)
{
Sample s1=new Sample();
s1.add(6,5);
}
}

3.with formal parameters and with return statement

class Sample
{
int venky(int a)
{
return a;

}
public static void main(String[] args)
{
Sample s1=new Sample();
int res=s1.venky(16);
System.out.println(res);
}
}

class Sample
{
float venky(float a)
{
return a;

}
public static void main(String[] args)
{
Sample s1=new Sample();
float res=s1.venky(16.6f);
System.out.println(res);

}
}

4.without formal parameters and with return statement.

class Sample
{
String hemanth()
{
return "virat is a champ";

}
public static void main(String[] args)
{
Sample s1=new Sample();
String s=s1.hemanth();
System.out.println(s);
}
}

import java.util.*;
class Sample
{

void add(int[] a)
{
System.out.println(Arrays.toString(a));

}
public static void main(String[] args)
{
Sample s1=new Sample();
int[] b={1,2,3,4};
s1.add(b);

}
}
steps to install jdk

1.Go to google and type java oracle india.


2.Windows====>64 bit download===>yes===>next===>next===>close
3.This pc====>c folder===>program files===>java===>jdk 20==>copy path
4.Search bar==>edit environmental variables for your account==>path==>new==>paste path==>move up

class Demo
{
public static void main(String[] args)
{
System.out.println("welcome to java");
}

C:\Users\heman>cd C:
C:\Users\heman

C:\Users\heman>cd /

C:\>cd Durga6pm

C:\Durga6pm>javac Demo.java

C:\Durga6pm>java Demo
welcome to java

command line arguments

1.The arguments which will take at command prompt are called command line arguments.
2.It will take the arguments based on index value.
3.By default arguments will store on String format.

class First
{
public static void main(String[] args)
{
String s1=args[0];
String s2=args[1];
System.out.println(s1+s2);

}
}

C:\Durga6pm>javac First.java
C:\Durga6pm>java First Taj Mahal
TajMahal

class First
{
public static void main(String[] args)
{
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
System.out.println(a+b);

}
}

C:\Durga6pm>javac First.java

C:\Durga6pm>java First 3 4
7

C:\Durga6pm>javac First.java

C:\Durga6pm>java First virat 2


Exception in thread "main" java.lang.NumberFormatException: For input string: "virat"

variable length arguments

variable length arguments are formal parameters.


The purpose of variable length arguments is to take multiple values from actual arguments in
method heading.
variable length arguments ends with datatype...
Internally variable length arguments behaves like array.
variable length argument must be last.

class First
{
void sample(int a)
{
System.out.println(a);
}
public static void main(String[] args)
{
First f1=new First();
f1.sample(5,6,7);===================>error(expecting only 1 actual argument)
}
}

class First
{
void sample(int... a)
{
System.out.println(a);
}
public static void main(String[] args)
{
First f1=new First();
f1.sample(5,6,7);
}
}

C:\Durga6pm>javac First.java

C:\Durga6pm>java First
[I@372f7a8d

import java.util.*;
class First

{
void sample(int... a)
{
System.out.println(Arrays.toString(a));
}
public static void main(String[] args)
{
First f1=new First();
f1.sample(5,6,7);
}
}

C:\Durga6pm>javac First.java

C:\Durga6pm>java First
[5,6,7]

import java.util.*;
class First

{
void sample(int b,int... a)
{
System.out.println(Arrays.toString(a));
System.out.println(b);
}
public static void main(String[] args)
{
First f1=new First();
f1.sample(5,6,7);
}
}

C:\Durga6pm>javac First.java

C:\Durga6pm>java First
[6, 7]
5

import java.util.*;
class First

{
void sample(int...a,int b)
{
System.out.println(Arrays.toString(a));
System.out.println(b);
}
public static void main(String[] args)
{
First f1=new First();
f1.sample(5,6,7);
}
}

Error because variable llength argument must be last parameter.

Java features

Java features are services or facilities.

1.simple programming language.


2.platform independent programming language.
3.Statically typed programming language.
4.Highlevel programming language.
5.Integrated programming language.
6.Robust programming language.
7.Both functional and object oriend programming language.
8.Portable programming language.
9.Multithread programming language.
10.Dynamic programming language.

1.simple programming language.

1.java is a simple programming language because it contains predefine methods.


2.Java removed complicated topic like pointers.
3.Java contains simple syntax and easy to understand.

2.predefine methods

The methods which are already present in java software(jdk).These methods are developed by
java developers.

Examples

1.sqrt()
2.add()
3.max()
4.min()

3.Userpredefine methods
The methods which are not present in java software(jdk).These methods are developed by
java programmers.

Examples

1.bhavadeesh()
2.virat()
3.dhoni()
4.pawan()

class Demo
{
public static void main(String[] args)
{
System.out.println(Math.sqrt(49));===================>7.0
System.out.println(Math.sqrt(81));===================>9.0
System.out.println(Math.pow(2,3));===================>8.0
}
}

2.platform independent programming language.

A language where we can write program on one platform and we can execute in any platform.

Examples

1.java
2.python

platform dependent programming language.

A language where we can write program on one platform and we can execute in same platform.

Examples

1.c
2.c++

3.Statically typed programming language.

If we specify datatype infront of variable is called Statically typed programming language.

Examples

java
c
c++

int a=10;
Here int is datatype
a is variable
10 is value
String c="20";
dynamically typed programming language.

If we need not specify datatype infront of variable is called dynamically typed programming language.

Examples

python

a=10
c="20"

Here a is variable
10 is value

4.Highlevel programming language.

If we give input in machine understandale language it will gives output in human understandable
language.

Examples

java
python

int a=0b1010;===================>binary data (Machines)


System.out.println(a);==========>10 normal data (Humans)

5.Integrated programming language.

A language will takes place with both compilation and execution.

Difference between compiler and interpreter.

compiler

1.compiler will converts source code into intermediate code or byte code all at a time

Interpreter

1.Interpreter will execute line by line byte code .


2.Interpreter is present in jvm.

jdk

1.jdk stands for java development kit


2.In jdk both compilation and execution will occurs(develop and run===>developers)
3.Jdk contains jre,jvm

jre

1.jre stands for java runtime environment.


2.In jre only execution will occurs(run==>endusers/testers)
3.jre contains jvm.

jvm

1.jvm stands for java vitual machine.


2.jvm contains interpreter.
3.The purpose of jvm is to execute line by line byte code or intermediate code.

6.Robust programming language

1.Robust means strong.


2.Java is robust programming language because strongly typed,Garbage collector and Exception Handling.

1.Strongly typed
-----------------
Compiler will check each and every declaration and assignments at compile time.

Ex
--
int a="virat kohli";

javac Demo.java====>compile time error string data cannot store in int

2.Garbage Collector
--------------------
The purpose of Garbage collector removes unwanted memory and improves system performance.

3.Exception Handling
--------------------
The purpose of Exception Handling is to convert abnormal termination into normal termination.

7.Both object oriented and functional programming language

functional/procedural programming language

A language which supports only fundamentals and not oops principles(Inheritance,polymorphism,


Abstraction,Encapsulation) and donot stores the data in the form of objects.
Ex

object oriented programming language

A language which supports only oops principles but not fundamentals and stores data in the form
of objects.

Note:Java supports both oops principles(stores data in the form of objects) and fundamentals.

8.Portable programming language.

We can carry or migrate the java byte code from 1 platform to any platform without making changes
is called portable.
Note:Mobile portability in India

Ex
--
java
python

9.Multithread programming language.

1.Java provides predefines rich API for Multithreading.


1.Thread
2.Runnable
2.By using multithreading we can exeutes multiple thread at a time simultaneously,so the application performance
improved and execution can be fastly.

10.Dynamic Programming language

In java all.class files wont be loaded at begining and whenever .class file is required then
it is going to load.

The main advantage is program will always get latest version of .class file.

class Student
{
static
{
System.out.println("student class loaded");
}
}

class Test
{
static
{
System.out.println("Test class loaded");
}

public static void main(String[] args)


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

}
}

javac Test.java

java Test
Test class loaded
Hello

class Student
{
static
{
System.out.println("student class loaded");
}
}

class Test
{
static
{
System.out.println("Test class loaded");
}

public static void main(String[] args)


{
System.out.println("Hello");
Student s1=new Student();

}
}

javac Test.java

java Test
Test class loaded
Hello
Student class loaded

Literals

Literals are input values are going to store on variables.


They are 6 types of Literals.They are

1.Integer Literals==================>1,2,3...0,-1,-2....
2.Flaoting point literals===========>1.2,1.6,1.8........
3.Character Literals================>'a','b','c',.......
4.Boolean Literals==================>true,false
5.String Literals==================>"virat","dhoni".......
6.Object Literals=================>Null

int a =12;

int=====>datatype
a=======>variable
12======>value

Oops

1.Oops standards for object oriented programming system.


2.OOps is not a technology.
3.OOPS is a techniuque or methodlogy.
4.OOPS contains 4 principles
1.Inheritance
2.Polymorphism
3.Encapsulation
4.Abstraction
5.If we want to implement above principles we require class and object.

Difference between object oriented and object based language.

Object oriented language

A language which supports both inheritance and runtime polymorphism then it is called a
object oriented language.

Examples

java,c++,python,.net...........

Object based language

A language which does not supports inheritance and runtime polymorphism then it is called a
object based language.

Examples

javascript,vbscript........

class

1.class is a nonprimitive/refernce datatype.


2.class is a collection of variables and methods.

syntax

class classname
{
variables....
methods......

class Demo
{
int a=5;
int b=6;
public static void main(String[] args)
{

}
}

object

1.object is a instance of class.


2.Instance is allocating memory address to the instance variables.
variables

1.A variable is a container.


2.The purpose of variable is to stote operand(value,variable,expression).
3.There are 3 types of variables.They are
1.Instance/non static variables
2.static variables
3.Local variables
4.There is no gloabal variables in java.

1.Instance/non static variables

1.A variable that is defined outside of a method and without static keyword is called
Instance/non static variable.
2.Instance variables stored in Heap area.
3.Instance varibles can be accessed in 2 ways.
1.By using object
2.By using object refernce
4.Instance variables have default values.
5.The purpose of instance variables is to store different values.

object

1.object contains data.


2.Use object to access instance variables for 1 time.

object refernce

1.object contains Hashcode.


2.use object refernce to access instance variables for multiple times.
Note:By using object refernce access 1 time also possible but memory wasted.

2.static variable

1.A variable that is defined outside of a method and with static keyword is called static variable.
2.Static variables stored method area.
3.Static variables can be accessed in 4 ways.
1.By using object
2.By using object refernce
3.By using directly.
4.By using class name
4.static varibles have default values.
5.The purpose of static variables is to store common values.

Note:First 2 ways are not recommended according to industry standards.

By classname
when static variable name and local variable name both are same if we want to access static
variables then use classname.
When static variables are present multiple classes access by using classname.

3.Local varibles

1.A varible that is defined inside of a method without static keyword is called Local variable.
2.Formal parameters are local variables.
3.Local variables stored in stack area.
4.Local varibles are accessed in 1 way.
1.By using directly.
5.There is no default values for local variables.
6.Local varibles must be initialize.
7.The purpose of local variables is to perform opertions or task.

class Emp
{
int a=12;

public static void main(String[] args)


{
Emp e1=new Emp();
System.out.println(e1);===============>Emp@379619aa

}
}

Note:
syntax

classname objectrefernce/refernce varname = new classname()==============>object refernce


new classname()

Anonymous/unrefernce object

Anonymous object is a one type of object with no name.


The process of creating new and classname() and without classname and refernce variable/object
refernce.

new classname()

new

1.new is dynamic memory allocator.


2.It will allocates memory address to the instance variables at runtime.
class Student
{
int a=5;==================>instance variable
static int b=9;==========>static variable
void welcome(int d)======>Local variable
{
int r=14;==========>Local variable
}
public static void main(String[] args)
{
int c=12;=========>Local variable

}
}

class Student
{
int a=12;

public static void main(String[] args)


{
Student s1=new Student();
System.out.println(s1.a);

}
}

class Student
{
int a=12;

public static void main(String[] args)


{
System.out.println (new Student().a);
}
}

class Emp
{
String s="virat";
public static void main(String[] args)
{
Emp e1=new Emp();
System.out.println(e1.s);
System.out.println(new Emp().s);

}
}

class Emp
{
int s;
String a;
boolean b;
char c;
float d;
public static void main(String[] args)
{
Emp e1=new Emp();
System.out.println(e1.s);
System.out.println(e1.a);
System.out.println(e1.b);
System.out.println(e1.c);
System.out.println(e1.d);

}
}

output

0
null
false
.
o.o

class Emp
{
static int a=56;
public static void main(String[] args)
{
Emp e1=new Emp();
System.out.println(e1.a);
System.out.println (new Emp().a);
System.out.println(a);
System.out.println(Emp.a);

}
}

class Emp
{

public static void main(String[] args)


{
int a=12;
System.out.println(a);

}
}

class Emp
{

public static void main(String[] args)


{
int a;
System.out.println(a);==========>error
}
}

class StudentInfo
{
static String iname="Durga";
int sno;
String sname;
long mobile;

void display(int no,String name,long mob)


{
sno=no;
sname=name;
mobile=mob;
System.out.println(sno+" "+sname+" "+mobile+" "+iname);
}
public static void main(String[] args)
{
StudentInfo s1=new StudentInfo();
s1.display(1,"Hemanth",88888);
s1.display(2,"Parithosh",88871);
s1.display(3,"Ajay",88123);

}
}

class A
{
static int a=6;
}
class B
{
static int c=9;
public static void main(String[] args)
{
System.out.println(c);
System.out.println(A.a);
}
}

Methods

1.Methods is a collection of group of statemnts.


2.The purpose of methods is to perform task and produce code resuability.
3.There are 2 types of methods.They are
1.Instance methods.
2.static methods.

1.Instance methods

1.The methods which is defined without static keyword then it is called Instance method.
2.The purpose of Instance methods is to perform different task and produce code resuability.
3.Instance methods can be accessed in 2ways.
1.By using object
2.By using object refernce.
class Demo
{
void m1()
{
System.out.println("welcome to instance");
}
public static void main(String[] args)
{
Demo d1=new Demo();
d1.m1();
new Demo().m1();

}
}

2.static methods

1.The methods which is defined with static keyword then it is called static method.
2.The purpose of static methods is to perform common task and produce code resuability.
3.static methods can be accessed in 4 ways.
1.By using object
2.By using object refernce.
3.By using directly.
4.By using classname.

class Demo
{
static void m1()
{
System.out.println("welcome to static");
}
public static void main(String[] args)
{
Demo.m1();
m1();

}
}

Blocks

1.Blocks is collection of group of statments({}).


2.There are 2 types of blocks.
1.Instance blocks.
2.Static blocks.

1.Instance blocks.

1.A block which is defined without static keyword.


2.Instance blocks can execute when create object or object refernce

class Demo
{
{
System.out.println("welcome to instance block");
}
public static void main(String[] args)
{
Demo d1=new Demo();
new Demo();
}
}

2.static blocks.

1.A block which is defined with static keyword.


2.static blocks can execute whenever class will load.

class Demo===========>class will load


{
static
{
System.out.println("welcome to static");
}
public static void main(String[] args)====>main method call
{

}
}

class Demo============>class load


{
int a=12;
static int b=13;
void m1()
{
System.out.println("instance method");=========>instance method 6
}
static void m2()
{
System.out.println("static method");==============>static method 3
}
{
System.out.println("instance block");===========>instance block 4

}
static {
System.out.println("static block");=========>static block 1

}
public static void main(String[] args)========>main method call
{
int c=14;
System.out.println(c);==================>14 2
m2();
Demo d1=new Demo();
System.out.println(d1.a);=============>12 5
d1.m1();

}
}
Inheritance

1.The process of creating new class of existing class by using extends keyword is called Inheritance.
2.Existing class is a super class
3.New class is a sub class.
4.If we create object for super class we can access only super class variables or methods.
5.If we create object for sub class we can access both super and sub class variables and methods.
6.The purpose of Inheritance is to reuse features(variables and methods) from super class to sub class.
7.They are 6 types of Inheritance.They are
1.Single Inheritance
2.Multiple Inheritance
3.Multilvel Inheritance
4.Hierarchical Inheritance
5.Multipath Inheritance
6.Hybrid Inheritance

1.Single Inheritance

1 sub class is derived 1 super class.

2.Multiple Inheritance

1 sub class is derived from multiple super classes.


Note:Multiple Inheritance is not possible in classes because ambiguity(If same methods present in multiple super
classes which method want to call jvm will get
confusion)
Multiple Inheritance is possible in interfaces

3.Multilevel Inheritance

1 sub class derived from 1 intermediate class and that intermediate class is derived from 1 super class.

4.Hierarchical Inheritance

Multiple sub classes are derived from 1 super class.

5.Multipath Inheritance

1 sub is derived from multiple intermediate classes and that intermediate classes are derived from 1 super class.
Hierarchical Inheritance is not possible because it follows multiple Inheritance

6.Hybrid Inheritance

combination any inheritance.


Hybrid Inheritance is not possible because it follows multiple Inheritance

single Inheritance

class Chiranjeevi
{
int chiamount=500;
}
class Ramcharan extends Chiranjeevi
{
int ramamount=600;
public static void main(String[] args)
{

Ramcharan r1=new Ramcharan();


System.out.println(r1.ramamount);===============>600
System.out.println(r1.chiamount);===============>500
Chiranjeevi c1=new Chiranjeevi();
System.out.println(c1.chiamount);===============>500
System.out.println(c1.ramamount);===============>error

}
}
class Vehicle
{
String s="engine";
}
class Car extends Vehicle
{
int price=2000;
public static void main(String[] args)
{
Vehicle v=new Vehicle();
System.out.println(v.s);===============>engine
Car c=new Car();
System.out.println(c.price);===========>2000
System.out.println(c.s);===============>engine

Multilevel Inheritance

class Vehicle
{
String s="engine";
}
class Car extends Vehicle
{
int ctyres=4;
}
class Nexon extends Car
{
int price=100000;
public static void main(String[] args)
{
Vehicle v=new Vehicle();
System.out.println(v.s);
Car c1=new Car();
System.out.println(c1.ctyres);
System.out.println(c1.s);
Nexon n=new Nexon();
System.out.println(n.s);
System.out.println(n.ctyres);
System.out.println(n.price);

Hierarchical Inheritance

class Vehile
{
String s="engine";
}
class Car extends Vehile
{
int ct=4;
}
class Bike extends Vehile
{
int bt=2;
public static void main(String[] args)
{
Vehicle v=new Vehicle();
System.out.println(v.s);
Car c1=new Car();
System.out.println(c1.ct);
System.out.println(c1.s);
Bike b1=new Bike();
System.out.println(b1.bt);
System.out.println(b1.s);

}
}

class A
{
int a=6;
}
class C
{
int c=8;
}
class B extends A,C==========================>error
{
int b=7;
public static void main(String[] args)
{

}
}

this

1.this is an object refernce or refernce variable.


2.this is implicitly present.
3.when instance variable names and local variable name are same if we want access instance varibles
the use this.
4.this is used to call instance methods in current class.
5.this cannot be used for static content.

class A
{
int a=7;============>Instance variable
void m1()
{
int x=9;=========>Local variable
System.out.println(x);============================>9
System.out.println(this.a);=======================>7

}
public static void main(String[] args)
{
A a1=new A();
a1.m1();

}
}

class A
{
int a=12;======================>Instance var
void display()
{
int a=16;===================>Local var
System.out.println(a);===============>16
System.out.println(this.a);==========>12
}
public static void main(String[] args)
{
A a1=new A();
a1.display();

}
}

class A
{
void show()
{
System.out.println("show method");
}
void display()
{
this.show();
System.out.println("display method");
}
public static void main(String[] args)
{
A a1=new A();
a1.display();

}
}

class A
{
void show()
{
System.out.println("show method");
this.display();
}
void display()
{

System.out.println("display method");
}
public static void main(String[] args)
{
A a1=new A();
a1.show();

}
}

class A
{
static int a=9;
void show()
{
int a=6;
System.out.println(a);=======================>6
System.out.println(this.a);==================>9
}
public static void main(String[] args)
{
A a1=new A();
a1.show();

}
}

class A
{
static int a=9;
static void show()
{
int a=6;
System.out.println(a);
System.out.println(this.a);==================>error
}
public static void main(String[] args)
{
A a1=new A();
a1.show();

}
}

super

1.super is object refernce or reference variable.


2.when super class variables and methods(features) and sub class variables and methods name are
same if we want access super class features then use super.

Note:static methods does not refer this and super keyword anyway.
static variables can refer by this and super keyword

class A
{
int a=6;
}
class B extends A
{
int b=9;
void display()
{
System.out.println(b);================>9
System.out.println(a);================>6
}
public static void main(String[] args)
{
B b1=new B();
b1.display();
}
}

class A
{
int a=6;
}
class B extends A
{
int a=9;
void display()
{

System.out.println(a);=======================>9
System.out.println(super.a);================>6
}
public static void main(String[] args)
{
B b1=new B();
b1.display();
}
}

class A
{
void mahesh()
{
System.out.println("Mahesh in super class");
}
}
class B extends A
{
void pawan()
{
System.out.println("pawn in sub class");

}
public static void main(String[] args)
{
B b1=new B();
b1.mahesh();
b1.pawan();
}
}

class A
{
void mahesh()
{
System.out.println("Mahesh in super class");
}
}
class B extends A
{
void mahesh()
{
System.out.println("pawan in sub class");===================>pawan in sub class
super.mahesh();=============================================>Mahesh in super class
}
public static void main(String[] args)
{
B b1=new B();
b1.mahesh();

}
}

class A
{
String m="ntr";
void mahesh()
{
System.out.println(m);
System.out.println("Mahesh in super class");
}
}
class B extends A
{
String va="prabhas";
void mahesh()
{
System.out.println(va);
super.mahesh();
System.out.println("pawan in sub class");
}
public static void main(String[] args)
{
B b1=new B();
b1.mahesh();

}
}
class A
{
static int a=7;
}
class B extends A
{
int a=8;
void display()
{
System.out.println(a);===========================>8
System.out.println(super.a);=====================>7
}
public static void main(String[] args)
{
B b1=new B();
b1.display();
}
}
class A
{
int a=7;
}
class B extends A
{
int a=8;
static void display()
{
System.out.println(a);
System.out.println(super.a);=======================>error
}
public static void main(String[] args)
{
B b1=new B();
b1.display();
}
}

Modifiers
1.Modifiers are keywords.
2.Modifiers are used to give accessbility and modifies the behaviour of variables,methods
and class.
3.Modifiers are divided into 2 types.They are
1.Access Modifiers
2.Non Access Modifiers.

1.Access Modifiers

Access Modifiers are used to give accessibility to the variables,methods,class.


There are 4 types of Access modifiers.They are
1.public=========>Any where
2.protected======>package and sub class of another package
3.default========>package
4.private==========>class

We can increase the accessibility but donot decrease the accessibility to the access modifiers.

1.public==========>public
2.protected=======>public,protected
3.default=========>public,protected,default
4.private=========>No

class A
{
String s="Rajamouli";
}
class B extends A
{
String s2="Maniratnam";
public static void main(String[] args)
{
B b1=new B();
System.out.println(b1.s2);===========>Maniratname
System.out.println(b1.s);============>Rajamouli
}

class A
{
private String s="Rajamouli";
}
class B extends A
{
String s2="Maniratnam";
public static void main(String[] args)
{
B b1=new B();
System.out.println(b1.s2);
System.out.println(b1.s);===================>error
}

}
class A
{
private String s="Rajamouli

}
class B extends A
{
String s2="Maniratnam";
public static void main(String[] args)
{
A b1=new A();

System.out.println(b1.s);====================>Error
}

class B
{
private String s2="Maniratnam";
public static void main(String[] args)
{
B b1=new B();

System.out.println(b1.s2);===================>Maniratnam
}

class A
{
void m1()
{
System.out.println("m1 in A");
}
}
class B extends A
{
void m2()
{
System.out.println("m2 in B");
}
public static void main(String[] args)
{
B b1=new B();
b1.m1();
b1.m2();
}
}

output

m1 in A
m2 in B

class A
{
private void m1()
{
System.out.println("m1 in A");
}
}
class B extends A
{
void m2()
{
System.out.println("m2 in B");
}
public static void main(String[] args)
{
B b1=new B();
b1.m1();============>error
b1.m2();
}
}

private class A
{
void m1()
{
System.out.println("m1 in A");
}
}
class B extends A=================================>ERROR
{
void m2()
{
System.out.println("m2 in B");
}
public static void main(String[] args)
{
B b1=new B();
b1.m1();
b1.m2();
}
}

class A
{
public void m1()
{
System.out.println("m1 in A");
}
}
class B extends A
{
void m2()
{
System.out.println("m2 in B");
}
public static void main(String[] args)
{
B b1=new B();
b1.m1();===========================>m1 in A
b1.m2();===========================>m2 in B
}
}

class A
{
protected void m1()
{
System.out.println("m1 in A");
}
}
class B extends A
{
void m2()
{
System.out.println("m2 in B");
}
public static void main(String[] args)
{
B b1=new B();
b1.m1();=============================>m1 in A
}
}

class A
{
void m1()
{
System.out.println("m1 in A");
}
}
class B extends A
{
void m2()
{
System.out.println("m2 in B");
}
public static void main(String[] args)
{
B b1=new B();
b1.m1();===========================>m1 in A
}
}

Constructors

1.Constructor is a one type of special method.


2.Constructor name and class Name must be same and with no return type including void.
3.Constructor will execute whenever we create an object.
4.The purpose of constructors is to initilize instance variables.
5.They are 3 types of constructors.They are
1.default/Non parameterized constructor.
2.Parameterized Constructor
3.Copy Constructor.

1.default/Non parameterized constructor.


----------------------------------------
The constructor without formal parameters or Zero formal parameters is called default or
Non parameterized constructor.

2.Parameterized Constructors
----------------------------
The constructor with formal parameters is called parameterized constructors.

3.Copy Constructor.
--------------------
The process of copying 1 object refernce or refernce variable into another Onject refernce or
reference variable.

6.If there is no constructor jvm will provide 1 default constructor.


7.Constructor Overloading
--------------------------
The process of 2 or more constructors with same name and different formal parameters list.
8.Constructor overriding is not possible because inheritance is not possible.

8.Constructor chaining

1.The process of calling one constructor to another constructor is called constructor chaining.
2.Constructor chaining can be possible by this(),super().
3.this() and super() must be written in first statement.
4.super() is implicitly present in every class but not this().

3.this()
---------
this() will call default constructor in current class.

this(int x)
-----------
this(int x) will parameterized constructor in current class.

4.super()
---------
super() will call default constructor in super class
super(int x)
---------
super(int x) will call parameterized constructor in super class

Difference between methods and constructors

Methods

1.The purpose of methods is to perform task and produce code resuability.


2.There will be return type in methods.
3.Method name and class name must not be same.
4.Method will execute whenever we call method.
5.Actual arguments is passed in method calling in methods.
6.Method overriding is possible in methods.
7.Inheritance is possible in methods.
8.this() and super() is not present in methods.

Constructors

1.The purpose of constructors is to iniatilize instance varaibles.


2.There will be no return type in constructors.
3.constructor name and class name must be same.
4.Constructor will execute whenever we create object.
5.Actual arguments is passed in object creation in constructors.
6.Constructors ovverriding is not possible in constructors.
7.Inheritance is not possible in constructors.
8.this() and super() is present in constructors.

class Demo
{
Demo()
{
System.out.println("welcome to constructors");==============>Welcome to constructors

}
public static void main(String[] args)
{
Demo d1=new Demo();

}
}

class Demo
{
Demo(int a)
{
System.out.println(a+" parameterized constructors");=========>6 parameterized constructors

}
public static void main(String[] args)
{
Demo d1=new Demo(6);

}
}

class Demo
{
Demo(int a,int b)
{
System.out.println(" parameterized constructors");==>parameterized constructors
System.out.println(a+" "+b);===>6 8

}
public static void main(String[] args)
{
Demo d1=new Demo(6,8);

}
}

class Demo
{
int a;
int b;
Demo()
{
a=6;
b=7;
System.out.println(a+" "+b);

}
Demo(Demo ref)
{
a=ref.a;
b=ref.b;
System.out.println(a+" "+b);

}
public static void main(String[] args)
{
Demo d1=new Demo();
Demo d2=new Demo(d1);

}
}

class Student
{
int sno;
String sname;
Student()
{
sno=123;
sname="Hemanth";
System.out.println(sno+" "+sname);===========>123 Hemanth

}
Student(Student s3)
{
sno=s3.sno;
sname=s3.sname;
System.out.println(sno+" "+sname);==========>123 Hemanth
}
public static void main(String[] args)
{
Student s1=new Student();
Student s2=new Student(s1);

}
}

class Emp
{
int eno=12;
String ename="Parithosh";
Emp()
{
System.out.println(eno+" "+ename);==================>12 Parithosh

}
public static void main(String[] args)
{
Emp e1=new Emp();

}
}

class Emp
{
int eno;
String ename;
Emp(int empno,String empname)
{
eno=empno;
ename=empname;

}
void display()
{
System.out.println(eno+" "+ename);
}
public static void main(String[] args)
{
Emp e1=new Emp(12,"Mohan");
e1.display();

}
}

class Student=======================>1 class will load


{
int sno;======================>Instance Variable
String sname;================>Instance variable
Student(int sno,String sname)=================>parameterized constructor4
{
sno=sno;
sname=sname;
}
void display()================================>Instance method
{
System.out.println(sno+" "+sname);
}
public static void main(String[] args)==================>2 main method call
{
Student s1=new Student(4,"Bhavadeesh");=====>Object refernce==>3
s1.display();===============================>method calling

}
}

class Institute===================>1 class will load


{
int ino;
String iname;
Institute(int ino,String iname)========>4
{
this.ino=ino;==============>5
this.iname=iname;=========>6
}
void show()================================>8
{
System.out.println(ino+" "+iname);===========>9 567 Durga
}
public static void main(String[] args)======================>2 main method call
{
Institute i1=new Institute(567,"Durga");===============> 3 object created
i1.show();=============================================>7 method calling

}
}

class Demo
{

public static void main(String[] args)


{
Demo d1=new Demo();

}
}
No output
-------------------------------------------------------

class Demo
{
Demo()
{
}

public static void main(String[] args)


{
Demo d1=new Demo();

}
}
No output
class Demo
{
Demo()
{
System.out.println("default con");
}
Demo(int x)
{
System.out.println("parameterized con");
}
Demo(int x,String y)
{
System.out.println(x+" "+y);
}

public static void main(String[] args)


{
Demo d1=new Demo(8);=========================>parameterized con
Demo d2=new Demo(8,"virat");================>8 virat

}
}

class A=========================>super class


{
A()=======================>default constructor
{
System.out.println("defalut con in super class");
}
}
class B extends A=============>sub class
{
B(int x)=================>parameterized constructor
{
System.out.println("parameterized con in sub class");

}
public static void main(String[] args)
{
B b1=new B();==================>created object for sub class for executing default constructor
}
}

error

class B
{
B()
{
System.out.println("defalut con");
}
B(int x)
{
this();

System.out.println("parameterized con");
}
public static void main(String[] args)
{
B b1=new B(7);
}
}

Defalut con
parameterized con

class B
{
B()
{
this(5);
System.out.println("defalut con");
}
B(int x)
{

System.out.println("parameterized con");
}

public static void main(String[] args)


{
B b1=new B();
}
}

parameterized con
defalut con

class B
{
B()
{

System.out.println("defalut con");
this(5);=============================>error
}
B(int x)
{

System.out.println("parameterized con");
}

public static void main(String[] args)


{
B b1=new B();
}
}

class A
{
A()
{
System.out.println("default con in super class");
}
}
class B extends A
{
B(int x)
{
super();
System.out.println("parameterized con in sub class");
}
public static void main(String[] args)
{
B b1=new B(6);
}
}

default con in super class


parameterized con in sub class

class A
{
A(int x)
{
System.out.println("param con in super class");
}
}
class B extends A
{
B()
{
super(6);
System.out.println("default con in sub class");
}
public static void main(String[] args)
{
B b1=new B();
}
}

param con in super class


default con in sub class

class A
{
A()
{
System.out.println("default con in super class");
}
}
class B extends A
{
B(int x)
{

System.out.println("parameterized con in sub class");


}
public static void main(String[] args)
{
B b1=new B(7);
}
}
class A
{
A()
{
System.out.println("default con in super class");
}
}
class B extends A
{
B(int x)
{
super();

System.out.println("parameterized con in sub class");


}
B()
{
this(6);

System.out.println("default con in sub class");


}

public static void main(String[] args)


{
B b1=new B()
}

default con in super class


parameterized con in sub class
default con in sub class

class A
{
A()
{
System.out.println("default con in super class");
}
}
class B extends A
{
B(int x)
{
this();
System.out.println("parameterized con in sub class");
}
B()
{

System.out.println("default con in sub class");


}

public static void main(String[] args)


{
B b1=new B(7);
}
}
default con in super class
default con in sub class
parameterized con in sub class

polymorphism

1.poly means many and morphism means forms.(polymorphism===========>many forms)


2.The ability to have more than 1 form is called polymorphism.
3.They are 2 types of polymorphism.They are
1.compiletime/static polymorphism.
2.runtime/dynamic polymorphism.

1.compiletime/static polymorphism.

The process of binding method heading with method calling at compile time is called compile
time polymorphism.

Ex

1.overloading,method hiding

2.Runtime/dynamic polymorphism.

The process of binding method heading with method calling at run time is called runtime
time polymorphism.

Ex

1.overriding

1.Method overloading

1.The process of 2 or more methods name should be same and different formal paramter list.
2.Formal parameter list
1.No.of Formal parameters
2.change in order
3.change in datatype
3.Method overloading is possible in 1 class and multiple classes.
4.Inheritance is not required for method overloading (but possible in Inheritance also).
5.static methods can be overloaded.
6.private methods can be overloaded.
7.final methods can be overloaded.

2.Method overriding

1.The process of 2 or more methods name should be same and same formal paramter list.
2.Method overriding is not possible in 1class atleast 2 classes is required.
3.Method overriding can be implemented by using inheritance concept.
4.static methods cannot be override because (The purpose of static methods is to perform commom
task if we override static methods it will lost common task so thats why not possible).

5.private methods cannot be override because we cannot inherit 1 method of 1 class into another
class.
6.final methods cannot be ovverride because the purpose of final is to prevent inheritance.

class A
{
void add(int a)
{
System.out.println("welcome to java");
}
void add(float b)
{
System.out.println("welcome to python");
}
public static void main(String[] args)
{
A a1=new A();
a1.add(12);========================================>welcome to java

}
}

class A
{
void add(int a)
{
System.out.println("welcome to java");
}
void add(float b)
{
System.out.println("welcome to python");
}
public static void main(String[] args)
{
A a1=new A();
a1.add(12.6f);===================================>welcome to python

}
}
class A
{
void add(int a)=================================>method 1
{
System.out.println("welcome to java");
}
void add(float b)=================================>method 2
{
System.out.println("welcome to python");
}
public static void main(String[] args)
{
A a1=new A();
a1.add("mahesh");======================>error

}
}

class A
{
void add(int a,int b)
{
System.out.println("welcome to java");
}
void add(int c)
{
System.out.println("welcome to python");
}
public static void main(String[] args)
{
A a1=new A();
a1.add(1,7);==========================>welcome to java

}
}

class A
{
void add(int a,float b)
{
System.out.println("welcome to java");
}
void add(float a,int b)
{
System.out.println("welcome to python");
}
void add(int a)
{
System.out.println("welcome to c");
}

public static void main(String[] args)


{
A a1=new A();
a1.add(6.7f,7);=====================================>welcome to python

}
}
class A
{
void add()
{
System.out.println("Virat Kohli");
}

void add()
{
System.out.println("Sachin Tendulkar");
}
public static void main(String[] args)
{
A a1=new A();
a1.add();==========================>error because(method overriding is not
possible in 1 class)
}

class A
{
void add()
{
System.out.println("Virat kohli");
}

}
class B extends A
{
void add()
{
System.out.println("Sachin Tendulkar");
}
public static void main(String[] args)
{
B b1=new B();
b1.add();==========================================>scahin Tendulakar
}

class A
{
void add()
{
System.out.println("Virat kohli");
}

}
class B extends A
{
void add()
{
System.out.println("Sachin Tendulkar");
}
public static void main(String[] args)
{
A a1=new A();
a1.add();================================>virat kohli

}
}
class B
{
static void m1()
{
System.out.println("chicken");
}
void m1(int a)
{
System.out.println("mushroom");
}

public static void main(String[] args)


{
B b1=new B();
b1.m1(56);===========================>mushroom
}
}

class A
{
final void display()
{
System.out.println("Display in A");
}
}
class B extends A
{
void display()
{
System.out.println("Display in B");
}
public static void main(String[] args)
{
A a1=new A();
a1.display();=====================================>error
}
}

class A
{
private void display()
{
System.out.println("Display in A");
}
}
class B extends A
{
void display()
{
System.out.println("Display in B");
}
public static void main(String[] args)
{
A a1=new A();
a1.display();================================>error
}
}

class A
{
static void display()
{
System.out.println("Display in A");
}
}
class B extends A
{
void display()
{
System.out.println("Display in B");
}
public static void main(String[] args)
{
A a1=new A();
a1.display();==================================>error
}
}

class B
{
final void display(int a)
{
System.out.println("Display in virat");
}
void display()
{
System.out.println("Display in B");
}
public static void main(String[] args)
{
B b1=new B();
b1.display();========================>Display in B
}
}

class B
{
private void display(int a)
{
System.out.println("Display in virat");
}
void display()
{
System.out.println("Display in B");
}
public static void main(String[] args)
{
B b1=new B();
b1.display();========================>Display in B
}
}
class B
{
static void display(int a)
{
System.out.println("Display in virat");
}
void display()
{
System.out.println("Display in B");
}
public static void main(String[] args)
{
B b1=new B();
b1.display();========================>Display in B
}
}

class Calculator
{
void add(int a,int b)
{
System.out.println(a+b);
}
void add(int a,int b,int c)
{
System.out.println(a+b+c);
}
void add(int a,int b,int c,int d)
{
System.out.println(a+b+c+d);
}
public static void main(String[] args)
{
Calculator c1=new Calculator();
c1.add(6,8,9);
}
}

class Sbi
{
void phonePay(int am)
{
System.out.println(am);
}
}
class PunjabBank extends Sbi
{
void phonePay(int am)
{
System.out.println(am);
}
public static void main(String[] args)
{
Sbi ajay=new Sbi();
ajay.phonePay(500);
PunjabBank pari=new PunjabBank();
pari.phonePay(700);
}
}

class Anand
{
void love()
{
System.out.println("vaishnavi loves Anand");
}
}
class Viraj extends Anand
{
void love()
{
System.out.println("vaishnavi loves viraj");
}
public static void main(String[] args)
{
Viraj vaishu=new Viraj();
vaishu.love();
}

final

final is a non accesser modifier.


The purpose of final is to modifys the behaviour of variable,method,class.
final is used to avoid variable modification,method overriding and class inheritance
final variables must be intialize.

int a=6;
a=8;
a=12;
System.out.println(a);===================>12

final String s="pawan";


System.out.println(s);===============>pawan

final String s="pawan";


s="kalyan";
System.out.println(s);==============>error

class B
{
void show()
{
System.out.println("show in B");
}
}
class A extends B
{
void show()
{
System.out.println("show in A");
}
public static void main(String[] args)
{
B b1=new B();
b1.show();=========================>show in B

}
}

class B
{
final void show()
{
System.out.println("show in B");
}
}
class A extends B
{
void show()
{
System.out.println("show in A");
}
public static void main(String[] args)
{
B b1=new B();
b1.show();==========================>error

}
}

final class B
{
void show()
{
System.out.println("show in B");
}
}
class A extends B===========================>error
{
void display()
{
System.out.println("display in A");
}
public static void main(String[] args)
{
B b1=new B();
b1.show();

}
}

class B
{
void show()
{
System.out.println("show in B");
}
}
class A extends B
{
void display()
{
System.out.println("display in A");
}
public static void main(String[] args)
{
B b1=new B();
b1.show();====================================>show in B

}
}

final int a;
System.out.println(a);=============>error

upcasting

1.The process of assigning object or object refernce of sub class to super class.
2.Upcasting done by system implicitly.
3.Upcasting always valid

class A
{
void m1()
{
System.out.println("m1 in A");
}
}
class B extends A
{
void m2()
{
System.out.println("m2 in B");
}
}
class C extends B
{
void m3()
{
System.out.println("m3 in c");
}
}
class Test
{
public static void main(String[] args)
{
A a1=new B();
a1.m1();================>m1 in A
a1.m2();================>error
}
}

class A
{
void m1()
{
System.out.println("m1 in A");
}
}
class B extends A
{
void m2()
{
System.out.println("m2 in B");
}
}
class C extends B
{
void m3()
{
System.out.println("m3 in c");
}
}
class Test
{
public static void main(String[] args)
{
A a1=new B();
a1.m1();=====================>m1 in A
B b1=new C();
b1.m1();====================>m1 in A
b1.m2();====================>m2 in B
A a2=new C();
a2.m1();====================>m1 in A

a2.m2();==================>error
}
}

class Vehicle
{
void engine()
{
System.out.println("engine in vehicle");
}
}
class Car extends Vehicle
{
void tyres()
{
System.out.println("4 tyres in car");
}
}
class Punch extends Car
{
void price()
{
System.out.println("10 lakhs punch");
}
}
class Demo
{
public static void main (String[] args)
{
Vehicle v1=new Car();
v1.engine();=================>engine in Vehicle
v1.tyres();==================>error
v1.price();==================>error
Car c1=new Punch();
c1.engine();=================>engine in vehicle
c1.tyres();==================>4 tyres in Car
c1.price();==================>error
Vehicle v2=new Punch();
v2.engine();=================>engine in Vehicle
v2.tyres();==================>error
v2.price();==================>error

Vehicle v3=c1;
v3.engine();==================>engine in Vehicle
v3.tyres();==================>error
v3.price();==================>error

}
}

downcasting

1.The process of assigning object or object refernce of super class to sub class.
2.Downcasting can be done by programmer explicitly.
3.Downcasting always required upcasting.

class Vehicle
{
void engine()
{
System.out.println("engine in vehicle");
}
}
class Car extends Vehicle
{
void tyres()
{
System.out.println("4 tyres in car");
}
}
class Punch extends Car
{
void price()
{
System.out.println("10 lakhs punch");
}
}
class Demo
{
public static void main (String[] args)
{
Vehicle v1=new Car();
Car c1=(Car)v1;
c1.engine();
c1.tyres();

Car c2=new Punch();


Punch p1=(Punch)c2;
p1.engine();
p1.tyres();
p1.price();

}
}

Object class

1.Object is a predefine class.


2.Object class is a super class for all classes directly or indirectly.
3.Object class is present in java.lang package.
4.Object class contains 11 methods.

1.toString()
2.hashCode()
3.equals()
4.finalize()
5.getClass()
6.clone()
7.wait()
8.wait(long ms)
9.wait(long ms,int s)
10.notify()
11.notifyAll()

1.toString()

Before overriden of toString method we got toString representation(Demo@372f7a8d)


After overriden of toString method we got welcome to java
Note:toString() must be ovverride.

class Demo
{
public static void main(String[] args)
{
Demo d1=new Demo();
System.out.println(d1);============>Demo@372f7a8d
}
}

Demo@372f7a8d

className@hexdecimaldata

getClass().getName().toHexString().hashCode()

class Demo
{
public static void main(String[] args)
{
Demo d1=new Demo();
System.out.println(d1);============>Demo@372f7a8d

System.out.println(d1.toString());============>Demo@372f7a8d

}
}

class Demo
{
public static void main(String[] args)
{
System.out.println("Happy Friday");=============>Happy Friday
}
}

import java.lang.*;
class Demo extends Object
{
public static void main(String[] args)
{
System.out.println("Happy Friday");=============>Happy Friday
}
}

class Demo
{
public String toString()
{
return "welcome to java";
}
public static void main(String[] args)
{
Demo d1=new Demo();
System.out.println(d1);===============>welcome to java
System.out.println(d1.toString());=====>welcome to java
}
}

class Demo
{
int sno;
String sname;
Demo(int sno,String sname)
{
this.sno=sno;
this.sname=sname;
}
public static void main(String[] args)
{
Demo d1=new Demo(7,"Dhoni");
System.out.println(d1);=========>Demo@372f7a8d===>toString representation
}
}

class Demo
{
int sno;
String sname;
Demo(int sno,String sname)
{
this.sno=sno;
this.sname=sname;
}
public String toString()
{
return sno+" "+sname;
}
public static void main(String[] args)
{
Demo d1=new Demo(7,"Dhoni");
System.out.println(d1); =========>7 Dhoni
}

class Demo
{ public static void main(String[] args)
{
Demo d1=new Demo();
System.out.println(d1);
System.out.println(d1.toString());
int hs=d1.hashCode();
System.out.println(hs);
}
}
Demo@372f7a8d
Demo@372f7a8d
925858445

Relationships

There are 2 types of relationships.They are


1.Is a relationship====>Inheritance==>extends
2.Has a relationship===>Association==>no extends

1.In is a relationship there is a relation between classes.


2.The purpose of is a relationship is to reuse all the features of one class to another class.
1.In Has a relationship there is a relation between objects.
2.The purpose of Has a relationship is to reuse required the features of one class to another class.

Association is divided into 2 types.They are


1.composition
-------------
1.If container object(Bharath University) destroy and automatically contained objects(Depts)
is going to destroy.
2.container object(Bharath University) is strongly associated with contained objects(Depts)
2.Aggregation
1.If container object(ECE DEPT) destroy and may or may not be contained objects(Proffesors)
is not going to destroy.
2.container object(ECE DEPT) is weakly associated with contained objects(Proffesors)

class Person
{
int hands=2;
int legs=2;
}
class Student extends Person
{
int sno=12;
String sname="Hemanth Babu";
void getStudent()
{
System.out.println("sno"+sno+" "+"sname"+sname+" "+"hands"+hands+" "+"legs"+legs);
}
public static void main(String[] args)
{
Student s1=new Student();
s1.getStudent();

}
}
Student is a person

sno12 snameHemanth Babu hands2 legs2

class Bike
{
int speed=120;
String color="Black";
}
class Duke extends Bike
{
int dukeprice=1000;
void getDuke()
{
System.out.println(speed+" "+color+" "+dukeprice);
}
public static void main(String[] args)
{
Duke d1=new Duke();
d1.getDuke();
}

Duke is a Bike

120 Black 1000

class Engine
{
void start()
{
System.out.println("Bike started");
}
void stop()
{
System.out.println("Bike stopped");
}

}
class Bike
{
Engine e1=new Engine();
void work()
{
e1.start();
System.out.println("Bike is running......");
e1.stop();
}
public static void main(String[] args)
{
Bike b1=new Bike();
b1.work();
}
}

Bike started
Bike is running......
Bike stopped

class Address
{
int dno=12;
String stname="mythrivanam";
}
class Emp
{
Address a1=new Address();
String ename="Hemanth";
void getEmp()
{
System.out.println(ename+" "+a1.dno+" "+a1.stname);
}
public static void main(String[] args)
{
Emp e1=new Emp();
e1.getEmp();
}
}
Emp has a Address

Hemanth 12 mythrivanam

Encapsulation

1.The process of binding/wrapping/grouping/combining variables and methods into single class is


called encapsulation.
2.The purpose of encapusaltion is to hide the data to the object or object refernce and giving
access to the methods.
(or)
The purpose of encapsulation is to perform validations by using getter and setter methods.
3.The purpose of getter methods is to get values.

4.The purpose of setter methods is to set values.


5.Note:Declare variables as private and methods as public.

class Demo
{
int no=12;
String name="parithosh";
void display()
{
System.out.println(no+" "+name);
}
public static void main(String[] args)
{
Demo d1=new Demo();
d1.display();
}
}

class Student
{
int sno;
String sname;
String dname;
}

}
class Teacher
{
public static void main(String[] args)
{
Student s1=new Student();
s1.sno=123;
s1.sname="Mohan";
s1.dname="ECE";
System.out.println(s1.sno);
System.out.println(s1.sname);
System.out.println(s1.dname);
}
}

output

123
Mohan
ECE

class Student
{
private int sno;
private String sname;
private String dname;
}

}
class Teacher
{
public static void main(String[] args)
{
Student s1=new Student();
s1.sno=123;
s1.sname="Mohan";
s1.dname="ECE";
System.out.println(s1.sno);
System.out.println(s1.sname);
System.out.println(s1.dname);
}
}

output

error because of instance variables as decalred as private

class Student
{
private int sno;
private String sname;
private String dname;
public void setSno(int sno)
{
this.sno=sno;
}
public void setSname(String sname)
{
this.sname=sname;
}
public void setDname(String dname)
{
this.dname=dname;
}
public void getSno()
{
System.out.println(sno);
}
public void getSname()
{
System.out.println(sname);

}
public void getDname()
{
System.out.println(dname);

}
class Teacher
{
public static void main(String[] args)
{
Student s1=new Student();
s1.setSno(334);
s1.setSname("AjayKumar");
s1.setDname("ECE");
s1.getSno();
s1.getSname();
s1.getDname();

output

334
AjayKumar
ECE

class Student
{
private int sno;
private String sname;
private String dname;
public void setSno(int sno)
{
this.sno=sno;
}
public void setSname(String sname)
{
this.sname=sname;
}
public void setDname(String dname)
{
this.dname=dname;
}
public void getSno()
{
System.out.println(sno);
}
public void getSname()
{
System.out.println(sname);

}
public void getDname()
{
System.out.println(dname);

}
class Teacher
{
public static void main(String[] args)
{
Student s1=new Student();
s1.setSno(-87);
s1.setSname("AjayKumar");
s1.setDname("ECE");
s1.getSno();
s1.getSname();
s1.getDname();

output

-87
AjayKumar
ECE

class Student
{
private int sno;
private String sname;
private String dname;
public void setSno(int sno)
{
this.sno=sno;
}
public void setSname(String sname)
{
this.sname=sname;
}
public void setDname(String dname)
{
this.dname=dname;
}
public void getSno()
{
if(sno>0)
{
System.out.println("valid"+sno);
}
else
{
System.out.println("Invalid donot use ultra pro knowledge");

}
}
public void getSname()
{
System.out.println(sname);

}
public void getDname()
{
System.out.println(dname);

}
class Teacher
{
public static void main(String[] args)
{
Student s1=new Student();
s1.setSno(-87);
s1.setSname("AjayKumar");
s1.setDname("ECE");
s1.getSno();
s1.getSname();
s1.getDname();

output

Invalid donot use ultra pro knowledge


AjayKumar
ECE

class Student
{
private int sno;
private String sname;
private String dname;
public void setSno(int sno)
{
this.sno=sno;
}
public void setSname(String sname)
{
this.sname=sname;
}
public void setDname(String dname)
{
this.dname=dname;
}
public void getSno()
{
if(sno>0)
{
System.out.println("valid"+sno);
}
else
{
System.out.println("Invalid donot use ultra pro knowledge");

}
}
public void getSname()
{
System.out.println(sname);

}
public void getDname()
{
System.out.println(dname);

}
class Teacher
{
public static void main(String[] args)
{
Student s1=new Student();
s1.setSno(97);
s1.setSname("AjayKumar");
s1.setDname("ECE");
s1.getSno();
s1.getSname();
s1.getDname();

output
valid 97
AjayKumar
ECE

Adopter class

Adopter class is a one type of implementation class.


Adopter class contains concrete methods.
Adopter class contains body but no logic.

Note:If we want access only m2() in normal interfaces with implememtation class we have ovveride
all the methods and we have to write logic for all the methods.

Toovercame this problem adopter class came into the picture.

Note:If we want access only m2() in normal interfaces with implememtation class we have ovveride
all the methods and we have to write logic for only required (m2) methods.

interface A
{
void m1();
void m2();
void m3();
void m4();
void m5();
}
class B implements A
{
public void m1()
{
System.out.println("m1 in imple");
}
public void m2()
{
System.out.println("m2 in imple");
}
public void m3()
{
System.out.println("m3 in imple");
}
public void m4()
{
System.out.println("m4 in imple");
}
public void m5()
{
System.out.println("m5 in imple");
}

}
class Test
{
public static void main(String[] args)
{
A a1=new B();
a1.m2();
}
}

output

m2 in imple

interface A
{
void m1();
void m2();
void m3();
void m4();
void m5();
}
class B implements A
{
public void m1()
{

}
public void m2()
{

}
public void m3()
{

}
public void m4()
{

}
public void m5()
{

}
class Test extends B
{
public void m2()
{
System.out.println("m2 in Test class");
}
public static void main(String[] args)
{
Test t1=new Test();
t1.m2();
}
}

output
m2 in Test class.

interface Student
{
void getMarks();
void getDetails();
void getAddress();
void getDept();

}
class StudentDetails implements Student
{
public void getMarks()
{
}
public void getDetails()
{
}
public void getAddress()
{
}
public void getDept()
{
}

}
class Test extends StudentDetails
{
public void getMarks()
{
System.out.println("Telugu =92");
System.out.println("Hindi =94");
System.out.println("English =92");
System.out.println("Maths =99");
System.out.println("Physics =93");
System.out.println("Chemistry =94");
}
public static void main(String[] args)
{
Test t1=new Test();
t1.getMarks();
}

output

Telugu =92
Hindi =94
English =92
Maths =99
Physics =93
Chemistry =94
enum(Enumuration)

1.enum is our own datatype


2.Internally enum will behave like class.
2.The purpose of enum is to store constant values(fixed universal values).
3.In enum by default public static final is provided to the constants.
4.enum can be accessed by using enum name.
5.enum byitself an object.
6.enum can be declare inside class and outside class.
7.main method allowed in inside enum and outside enum.
8.values()

The purpose of values() is to list out the total number of constansts in enum.
9.ordinal()

The purpose of ordinal() is to give ordinal value from 0 to length-1 to the enum constants.

10.enum is ordinal based ordinal starts from 0 and ends with length-1.
11.enum allows variables,methods,constructors.

enum Week
{
Sun,Mon,Tue,Wed,Thu,Fri,Sat
}
class Test
{
public static void main(String[] args)
{
Week w1=Week.Sun;
System.out.println(w1);
Week w2=Week.Mon;
System.out.println(w2);
Week w3=Week.Tue;
System.out.println(w3);
Week w4=Week.Wed;
System.out.println(w4);

}
}

output

Sun
Mon
Tue
Wed

class Test
{
enum Week
{
Sun,Mon,Tue,Wed,Thu,Fri,Sat;
}
public static void main(String[] args)
{
Week w1=Week.Sun;
System.out.println(w1);
Week w2=Week.Mon;
System.out.println(w2);
Week w3=Week.Tue;
System.out.println(w3);
Week w4=Week.Wed;
System.out.println(w4);

}
}

output

Sun
Mon
Tue
Wed

enum Directions
{
East,West,North,South;
public static void main(String[] args)
{
Directions d1=Directions.East;
System.out.println(d1);
Directions d2=Directions.West;
System.out.println(d2);
Directions d3=Directions.North;
System.out.println(d3);
Directions d4=Directions.South;
System.out.println(d4);

}
}

enum Directions
{
East,West,North,South;
public static void main(String[] args)
{
Directions[] d1=Directions.values();
for(Directions d2:d1)
{
System.out.println(d2+"......"+d2.ordinal());
}

}
}

output
East......0
West......1
North......2
South......3

enum Directions
{
East,West,North,South;
Directions()
{
System.out.println("constructor");
}
public static void main(String[] args)
{
Directions d1=Directions.East;
}
}

output

constructor
constructor
constructor
constructor

enum Beer
{
kf(100),Bw(70),Ko(85);
int getPrice;
Beer(int getPrice)
{
this.getPrice=getPrice;
}

int getRates()
{
return getPrice;
}

}
class Test
{
public static void main(String[] args)
{
Beer[] b1=Beer.values();
for(Beer b2:b1)
{
System.out.println(b2+"....."+b2.getRates());
}

}
}

output

kf.....100
Bw.....70
Ko.....85
enum Beer
{
kf(100),Bw(70),Ko(85),BB;
int getPrice;
Beer(int getPrice)
{
this.getPrice=getPrice;
}
Beer()
{
getPrice=200;

int getRates()
{
return getPrice;
}

}
class Test
{
public static void main(String[] args)
{
Beer[] b1=Beer.values();
for(Beer b2:b1)
{
System.out.println(b2+"....."+b2.getRates());
}

}
}

output

kf.....100
Bw.....70
Ko.....85
BB.....200

Annotations

1.Annotations are used to give errors and information in compilation.


2.Annotations are begin with @ symbol.
3.Annotations are applied to variables,methods,constructors,class,interfaces.......
4.Annotations are divided into 2 types.They are
1.predefine/standard annotations
2.UserDefine/custom annotations

1.predefine/standard annotations

The annotations which are already present in java software(jdk).These annotations are developed
by java developers.
predefine annotations are divided into 2 types.They are
1.General purpose annotations.
2.Meta annotations.
1.General purpose annotations.

General purpose annotations will give information to the compiler.


General purpose annotations are present in java.lang package
Ex
--
@override
@Depricated
@FunctionalInterface
@SuppressWarnings

2.Meta Annotations

Meta annotations give information about general purpose annotations.


Meta annotations are present in java.lang.annotation package

@Target
@Tetention
@Inherited
@Documented

@Target

@Target annotation will give information where we applied to the corresponding annotation
(where it can be method,variable,class,Constructor)
1.ElementType.TYPE====>class

2.ElementType.METHOD====>Method

3.ElementType.FIELD====>variable

2.@Retention

@Retention annotation will decide scope for an annotation. (SOURCE,CLASS,RUNTIME)

RetentionPolicy.SOURCE
RetentionPolicy.CLASS
RetentionPolicy.RUNTIME

3.@Documented

By default java applications are not in the form of Documentation.


By using @Documented annotation we can make an annotation as documentable annotation

4.@Inherited

@Inherited annotation is used to reuse one annotation features into another annotation.

2.UserDefine/custom annotations

The annotations which are not present in java software(jdk).These annotations are developed
by java programmers.

Marker Annotation

An annotation contains without members.

@interface Bank
{
}

Single value Annotation

An annotation contains only 1 member.

@interface Bank
{
int bno();
}

Multivalue Annotation

An annotation contains multiple members.

@interface Bank
{
int bno();
String bname();
}

@override

If we are trying to do override sub class method with super class method unfortunately or by mistake if we does
spelling mistakes then @Override annotation will give error at compile time.

class Sbi
{
void sendMoneyToCustome()
{
System.out.println("sending money from sbi");
}
}
class Axis extends Sbi
{

void sendMoneyToCustomer()

{
System.out.println("sending money from Axis");
}
}
class Test
{
public static void main(String[] args)
{
Axis bhavadeesh=new Axis();
bhavadeesh.sendMoneyToCustome();
}
}

output

sending money from sbi

class Sbi
{
void sendMoneyToCustome()
{
System.out.println("sending money from sbi");
}
}
class Axis extends Sbi
{

@Override
void sendMoneyToCustomer()

{
System.out.println("sending money from Axis");
}
}
class Test
{
public static void main(String[] args)
{
Axis bhavadeesh=new Axis();
bhavadeesh.sendMoneyToCustome();
}
}

output

error: method does not override or implement a method from a supertype


@Override

class Sbi
{
void sendMoneyToCustomer()
{
System.out.println("sending money from sbi");
}
}
class Axis extends Sbi
{

@Override
void sendMoneyToCustomer()

{
System.out.println("sending money from Axis");
}
}
class Test
{
public static void main(String[] args)
{
Axis bhavadeesh=new Axis();
bhavadeesh.sendMoneyToCustomer();
}
}
output

Sending money from Axis

@Deprecated

If we are trying to access outdated methods then @Depricated annotation will give error

class Tcs
{

void getSalary(int basic,int hra)


{
System.out.println("Before ycp govt");
}
void getSalary(int basic,int hra,int jtax)
{
System.out.println("After ycp govt");
}

class Test
{
public static void main(String[] args)
{
Tcs t1=new Tcs();
t1.getSalary(2000,1200);

}
}

output

Before Ycp govt

class Tcs
{
@Deprecated
void getSalary(int basic,int hra)
{
System.out.println("Before ycp govt");
}
void getSalary(int basic,int hra,int jtax)
{
System.out.println("After ycp govt");
}
}
class Test
{
public static void main(String[] args)
{
Tcs t1=new Tcs();
t1.getSalary(2000,1200);

}
}

output

Note: Test.java uses or overrides a deprecated API.


Note: Recompile with -Xlint:deprecation for details.

@FunctionalInterface

1.An normal interface contains multiple abstract methods.


2.An interface which contains no variables and methods is called marker interface
3.Functional Interface contains 1 abstract method.

Note:if we want to make normal interface into functional interface then we have use @FunctionalInterface and with
1 abstract method.

interface A
{

interface A
{
void m1();
void m2();
void m3();
}
class B implements A
{
public void m1()
{

}
public void m2()
{
}
public void m3()
{
}
}
class Test
{
public static void main(String[] args)
{
}

@FunctionalInterface
interface A
{
void m1();
void m2();
}
class B implements A
{
public void m1()
{

}
public void m2()
{
}

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

output

error: Unexpected @FunctionalInterface annotation


@FunctionalInterface
^
A is not a functional interface
multiple non-overriding abstract methods found in interface A

@FunctionalInterface
interface A
{
void m1();

}
class B implements A
{
public void m1()
{

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

@SuppressWarnings

If we perform unchecked or unsafe operations the compiler will give error (warning messages).
To overcame this problem then we are using @SuppressWarnings

import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add(1);
al.add(1.2);
al.add("venky");
System.out.println(al);
}

Note: Test.java uses unchecked or unsafe operations.


Note: Recompile with -Xlint:unchecked for details.

import java.util.*;
class Test
{
@SuppressWarnings("unchecked")
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add(1);
al.add(1.2);
al.add("venky");
System.out.println(al);
}

output

[1,1.2,venky]

import java.lang.annotation.*;
@Inherited
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Bank
{
int bno();
String bname();
}

@Bank(bno=4567,bname="HDFC")
class Account
{
int acno;
String aname;
Account(int acno,String aname)
{
this.acno=acno;
this.aname=aname;
}
void display()
{
System.out.println(acno);
System.out.println(aname);
}
}
class Test
{
@SuppressWarnings("unchecked")
public static void main(String[] args)
{
Account a1=new Account(23,"parithosh");
a1.display();
Class c1=a1.getClass();
Annotation a2=c1.getAnnotation(Bank.class);
Bank b1=(Bank)a2;
System.out.println(b1.bno());
System.out.println(b1.bname());
}
}

import java.lang.annotation.*;
@Inherited
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)

@interface School
{
int slno();
String schname();
}
@School(slno=345,schname="Durga")
class Student
{

int sno;
String sname;
Student(int sno,String sname)
{
this.sno=sno;
this.sname=sname;
}
void display()
{
System.out.println(sno);
System.out.println(sname);
}
}

class Test
{
@SuppressWarnings("unchecked")
public static void main(String[] args)
{
Student s1=new Student(12,"Venky");
s1.display();
Class c1=s1.getClass();
Annotation a1=c1.getAnnotation(School.class);
School s2=(School)a1;
System.out.println(s2.slno());
System.out.println(s2.schname());

}
}

output

12
Venky
345
Durga

import java.lang.annotation.*;
@Inherited
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Bank
{
int bno();
String bname();
}

@Bank(bno=4567,bname="HDFC")
class Account
{
int acno;
String aname;
Account(int acno,String aname)
{
this.acno=acno;
this.aname=aname;
}
void display()
{
System.out.println(acno);
System.out.println(aname);
}
}
class Dept extends Account
{
}
class Test
{
@SuppressWarnings("unchecked")
public static void main(String[] args)
{
Account a1=new Account(23,"parithosh");
a1.display();
Class c1=a1.getClass();
Annotation a2=c1.getAnnotation(Bank.class);
Bank b1=(Bank)a2;
System.out.println(b1.bno());
System.out.println(b1.bname());
}
}

interface

1.interface is a collection of public static final variables and public abstract methods.
2.In interface public static final is implicitly present to the variables.
3.In interface public abstarct is implicitly present to the methods.
4.If we want to perform abstraction inheritance is required.
5. ======>1 class can extends 1 class
======>1 class implements multiple interfaces
======>1 interface extends multiple interfaces
6.interface cannot be instantiated(we cannot create object for interface because it contains
abstract methods(didnot contain body)there is no use to call abstract methods in interface.
7.abstract methods must be override with public access modifier in implementation class.
8.abstract methods cannot be static
9.abstract methods cannot be private
10.abstract methods cannot be final
11.interface cannot be final.
12.Constructors are not possible in interfaces.
13.In interfaces we can achieve multiple inheritance.

Difference between abstract class and interfaces.


abstract class

1.abstract class contains concrete methods and abstract methods


2.In abstract class abstract methods are not public abstract implicitly.
3.Multiple inheritance is not possible in abstarct class.
4.constructors are allowed in abstract class.
5.main method is possible in abstract class.
6. implemented class can extends only 1 abstract class.

interfaces

1.interface contains only abstract methods.


2.In interface abstract methods are public abstract implicitly.
3.Multiple inheritance is possible in interface.
4.constructors are not allowed in interfaces.
5. main method is not possible in interface.
6. implemented class can implements multiple interfaces.

interface Demo
{
public static final int a=12;==========>int a=12;

public abstract void m1();=============>void m1();

interface Demo
{
public static final int a=12;
public abstract void m1();
}
class B implements Demo
{
void m1()
{
System.out.println(a);
System.out.println("welcome to interfaces");
}

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

output

error interface Demo cannot be instantiated(we cannot create object for interface
interface Demo
{
public static final int a=12;
public abstract void m1();
}
class B implements Demo
{
void m1()
{
System.out.println(a);
System.out.println("welcome to interfaces");
}

}
class Test
{
public static void main(String[] args)
{
Demo d1=new B();
d1.m1();
}
}

output

void m1() attempting to assign weaker access privileges; was public

interface Demo
{
public static final int a=12;
public abstract void m1();
}
class B implements Demo
{
public void m1()
{
System.out.println(a);
System.out.println("welcome to interfaces");
}

}
class Test
{
public static void main(String[] args)
{
Demo d1=new B();
d1.m1();
}
}

output

12
welcome to interfaces
interface Loan
{
int itr=2;
void getLoan();
}
class HomeLoan implements Loan
{
public void getLoan()
{
System.out.println(itr+" ruppes interest for HomeLoan");
}
}
class EducationLoan implements Loan
{
public void getLoan()
{
System.out.println(itr+" ruppes interest for EducationLoan");
}
}
class GoldLoan implements Loan
{
public void getLoan()
{
System.out.println(itr+" ruppes interest for GoldLoan");
}
}
class User
{
public static void main(String[] args)
{
Loan bhavi=new HomeLoan();
bhavi.getLoan();
Loan Hemanth=new EducationLoan();
Hemanth.getLoan();
Loan venky=new GoldLoan();
venky.getLoan();
}
}

output

2 ruppes interest for HomeLoan


2 ruppes interest for EducationLoan
2 ruppes interest for GoldLoan

interface Physics
{
void getpyMarks();
}
interface Chemistry
{
void getchMarks();
}
class Student implements Physics,Chemistry
{
public void getpyMarks()
{
System.out.println("67 marks in physics");
}
public void getchMarks()
{
System.out.println("87 marks in chemistry");
}

}
class User
{
public static void main(String[] args)
{
p1.getpyMarks();
p1.getchMarks();
Physics p2=new Student();
p2.getpyMarks();
Chemistry p3=new Student();
p3.getchMarks();
}
}
67 marks in physics
87 marks in chemistry
67 marks in physics
87 marks in chemistry

interface A
{
void m1();
}
interface B
{
void m2();
}
interface C extends A,B
{
void m3();
}
class D implements C
{
public void m1()
{
System.out.println("m1 in D");
}
public void m2()
{
System.out.println("m2 in D");
}
public void m3()
{
System.out.println("m3 in D");
}

}
class Test
{
public static void main(String[] args)
{
D d1=new D();
d1.m1();
d1.m2();
d1.m3();
A a1=new D();
a1.m1();
B b1=new D();
b1.m2();
C c1=new D();
c1.m3();
}
}

m1 in D
m2 in D
m3 in D
m1 in D
m2 in D
m3 in D

Inner classes

1.The process of defining 1 class in another class is called Inner classes.


2.The purpose of inner classes will provide more readable and maintabable code because it logically
group into classes and interfaces into single unit.
3.one class private features we can access into another class.
4.There are 4 types of inner classes.They are
1.Instance class.
2.static class.
3.Local class.
4.Anonymous class.

1.Instance class.

A class which is defined outside of a method without using static keyword then that is called
a Instance class.
Instance class can access private features(variables or methods),static features(variables or
methods) from outer class.
Main method is allowed for outer class not for inner class.

class Outer
{
void m2()
{
System.out.println("m2 in outer");
}

class Inner
{
void m1()
{
System.out.println("m1 in Inner");
}
}
public static void main(String[] args)
{
Outer o1=new Outer();
o1.m2();
new Outer().m2();
}
}

output

m2 in outer
m2 in outer

class Outer
{
void m2()
{
System.out.println("m2 in outer");
}

class Inner
{
void m1()
{
System.out.println("m1 in Inner");
}
}
public static void main(String[] args)
{
Outer o1=new Outer();
o1.m2();
new Outer().m2();
Outer.Inner i1=o1.new Inner();
i1.m1();
}
}

output

m2 in outer
m2 in outer
m1 in inner

class Outer
{
void m2()
{
System.out.println("m2 in outer");
}

class Inner
{
void m1()
{
System.out.println("m1 in Inner");
}
}
public static void main(String[] args)
{
Outer o1=new Outer();
Outer.Inner i1=o1.new Inner();
i1.m1();
Outer.Inner i2=new Outer().new Inner();
i2.m1();
new Outer().new Inner().m1();

}
}

output

m1 in Inner
m1 in Inner
m1 in Inner

class Outer
{
int x=5;
void m2()
{
System.out.println("m2 in outer");
}

class Inner
{
int y=7;
void m1()
{
System.out.println(y);
System.out.println(x);

System.out.println("m1 in Inner");
m2();
}
}
public static void main(String[] args)
{
new Outer().new Inner().m1();

}
}

output

7
5
m1 in Inner
m2 in outer

class Outer
{
private int x=5;
static int z=5;
void m2()
{
System.out.println("m2 in outer");
}

class Inner
{
int y=7;
void m1()
{
System.out.println(y);
System.out.println(x);
System.out.println(z);

System.out.println("m1 in Inner");
m2();
}
}
public static void main(String[] args)
{
new Outer().new Inner().m1();

}
}

output

7
5
5
m1 in Inner
m2 in outer

class Outer
{
class Inner
{
public static void main(String[] args)
{
}
}
}

output

error

class Outer
{
class Inner
{
private int x=4;
static int y=9;
int z=18;
void m1()
{
System.out.println(x);
System.out.println(y);
System.out.println(z);

}
public static void main(String[] args)
{
new Outer().new Inner().m1();
}
}
output

4
9
18

static class

1.The class which is defined with static keyword is called static class.
2.static class can access only static features(var & meth) from outer class but inside static
class both static and non static possible.

class Outer
{
static class Inner
{
void m2()
{
System.out.println("m2 in Inner");
}

}
public static void main(String[] args)
{
Outer o1=new Outer();
Inner i1=new Outer.Inner();
i1.m2();

}
}

output

m2 in Inner

class Outer
{
static class Inner
{
int x=7;
void m2()
{
System.out.println(x);
System.out.println("m2 in Inner");
}
}
public static void main(String[] args)
{
Outer o1=new Outer();
Inner i1=new Outer.Inner();
i1.m2();
new Outer.Inner().m2();

}
}

output

7
m2 in Inner
7
m2 in Inner

class Outer
{
static int y=9;
static int z=17;
static private int u=8;
static class Inner
{
int x=7;
void m2()
{
System.out.println(y);
System.out.println(z);
System.out.println(u);

System.out.println(x);
System.out.println("m2 in Inner");
}

}
public static void main(String[] args)
{
new Outer.Inner().m2();

}
}

output

9
17
8
7
m2 in inner

class Outer
{
static int y=9;
int z=17;
private int u=8;
static class Inner
{
int x=7;
void m2()
{
System.out.println(y);
System.out.println(z);===============>error
System.out.println(u);==============>error

System.out.println(x);
System.out.println("m2 in Inner");
}

}
public static void main(String[] args)
{
new Outer.Inner().m2();

}
}

3.Local class.

A class is defined inside a method without static keyword is called a local class.

class Outer
{
public static void main(String[] args)
{
class Inner
{
void m1()
{
System.out.println("m1 in Inner");
}

}
Inner i1=new Inner();
i1.m1();

}
}

class Outer
{
void m1()
{
System.out.println("m1 in Outer");
class Inner
{
void m2()
{
System.out.println("m2 in Inner");
}

}
new Inner().m2();

}
public static void main(String[] args)
{
new Outer().m1();
}
}

4.Anonymus class

1.Anonymous class is a one type of local class without name


2.Anonymous class is a sub class of abstract class and interface.
3.The purpose of anonymous class will reduce the code by removing implementation class.

Note:
1.private,protected,static is not allowed for outer class.
2.static,public,protected,private is not allowed for local class and anonymous class.
3.All access modifiers are allowed in instance and static class.

abstract class A
{
abstract void m1();
}
class Demo
{
public static void main(String[] args)
{
A a1=new A()
{
void m1()
{
System.out.println("m1 in anon...class");
}
};
a1.m1();

}
}

interface A
{
void m1();
}
class Demo
{
public static void main(String[] args)
{
A a1=new A()
{
public void m1()
{
System.out.println("m1 in imple class");
}
};
a1.m1();
}
}

Explain public static void main(String[] args)

1.public

public is an access modifier.


jvm can access main method anywhere because of public

2.static

static is a non access modifier.


jvm will call the main method directly because of static.

Note:jvm will call the main method by using object or object refernce if main method is not static

void

void is empty return type


main method will returns nothing to jvm because of void

main

main is a method name


In jvm bydefaultly main name is configured.

String[] args

String[] args are formal parameters.


String[] args are command line arguments
we will take arguments(values) at the command prompt by default data in the for String array based on index value.

Note

String[] args
String []args
String args[]
String bhavi[]

1.modifiers order is not important

static public void main(String[] args)


public static void main(String[] args)

2.mandatory modifiers:public static


optional modifiers:final,synchronized,strictfp

3.public void main(String[] args)================>invalid (static)


4.static void main(String[] args)===============>invalid(public)
5.public static int main(String[] args)========>invalid(void)
6.public static void mainVenky(String[] args)==>invalid(main)
7.static public void main(String[] args)========>valid
8.public static void main(String... args)=======>valid
9.public static void main(String... venky)======>valid
10.main method can be overloaded but bydefault it will takes data in the form String .
11.main method cannot be ovverride because main method is static.
12.variable length arguments allowed in main method.

3.class Demo
{
public static void main(String venky[])
{
String s=venky[0];
System.out.println(s);
}
}

class Demo
{
public static void main(String venky[])
{
String s=venky[0];
System.out.println(s);
}
}

javac Demo.java
java Demo Dhoni

Dhoni

class Demo
{
public static void main(String[] args)
{
System.out.println("string data");
}
public static void main(int[] args)
{
System.out.println("int data");
}

output

String data
Abstraction

1.The process of hiding uncessesary details and showing necessary details is called Abstaraction.
2.The process of hiding implementation code and showing only functinality to the user.
3.Abstraction can be achieved in 2 ways.They are
1.abstract class
2.interfaces

1.abstarct class

1.A class which is defined with abstract keyword then that is called a abstract class.
2.abstract class is a collection of concrete methods and abstract methods.

abstract class A
{
}

concrete methods

1.The methods which have body then that is called a concrete method.
2.The purpose of concrete methods to give common functinality to the implementation classes.

void m1()
{
}
static void m2()
{
}

abstract methods

1.A method which is defined with abstarct keyword and without body is called abstract method.
2.The purpose of abstract method is give different funtionality to the implementation classes.
3.abstract methods can be defined in abstract classes only.
Important points on Abstarction

1.Abstarct class cannot be instantiated(we cannot create object for abstarct class) because abstract class contains
abstract methods (i.e abstract methods donot have body or implemented code
then there is no use to call abstract method.

2.If we want perform Abstarction Inheritance is required.


3.abstract methods must be ovveride.
4.abstract methods cannot be private.
5.abstarct methods cannot be static.
6.abstract methods cannot be final.
7.abstract class cannot be final.
8.concrete methods can be static.
9.abstract class can have main method also.
10.abstarct class can have constructors.

Ex
--
abstract void m1();

abstract class A
{
void m1()
{
System.out.println("welcome to concrete");
}
abstract void m2();
}
class Test
{
public static void main(String[] args)
{
A a1=new A();
a1.m1();

}
}

output

A is abstract cannot be instantiated

abstract class A
{
void m1()
{
System.out.println("welcome to concrete");
}
abstract void m2();
}
class Test extends A
{
public static void main(String[] args)
{
Test t1=new Test();
t1.m1();
}
}

output

Test is not abstract and does not override abstract method m2() in A

abstract class A
{
void m1()
{
System.out.println("welcome to concrete");
}
abstract void m2();
}
class Test extends A
{
void m2()
{
System.out.println("m2 is ovverriden in implemetation Test class");
}

public static void main(String[] args)


{
Test t1=new Test();
t1.m1();
t1.m2();
}
}

output

welcome to concrete
m2 is ovverriden in implemetation Test class

abstract class RealMe


{
void playYoutube()
{
System.out.println("Youtube is playing in Realme");
}
abstract void sendSms();
}
class Airtel extends RealMe
{
void sendSms()
{
System.out.println("sending sms from Airtel");
}
}
class Jio extends RealMe
{
void sendSms()
{
System.out.println("sending sms from Jio");
}
}
class User
{
public static void main(String[] args)
{
RealMe bhavadeesh1=new Airtel();
bhavadeesh1.playYoutube();
bhavadeesh1.sendSms();
RealMe bhavadeesh2=new Jio();
bhavadeesh2.playYoutube();
bhavadeesh2.sendSms();

}
}

Youtube is playing in Realme


sending sms from Airtel
Youtube is playing in Realme
sending sms from Jio

abstract class A
{
void m1()
{
System.out.println("m1 in A");
}
abstract private void m2();

}
class B extends A
{
void m2()
{
System.out.println("m2 in B");
}
}
class Test
{
public static void main(String[] args)
{
A a1= new B();
a1.m1();
a1.m2();
}
}

output

error

abstract class A
{
void m1()
{
System.out.println("m1 in A");
}
abstract final void m2();

}
class B extends A
{
void m2()
{
System.out.println("m2 in B");
}
}
class Test
{
public static void main(String[] args)
{
A a1= new B();
a1.m1();
a1.m2();
}
}

output

error

final abstract class A


{
void m1()
{
System.out.println("m1 in A");
}
abstract void m2();

}
class B extends A
{
void m2()
{
System.out.println("m2 in B");
}
}
class Test
{
public static void main(String[] args)
{
A a1= new B();
a1.m1();
a1.m2();
}
}

output

error

abstract class A
{
static void m1()
{
System.out.println("m1 in A");
}
abstract void m2();
}
class B extends A
{
void m2()
{
System.out.println("m2 in B");
}
}
class Test
{
public static void main(String[] args)
{
A a1= new B();
a1.m1();
a1.m2();
A.m1();
}
}

output

m1 in A
m2 in B
m1 in A

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

welcome to abstract class

abstract class Demo


{
Demo()
{
System.out.println("constrcutors in abstract class");
}
void m1()
{
System.out.println("concrete without static in abstract class");
}
static void m2()
{
System.out.println("concrete with static in abstract class");
}
abstract void m3();
}
class B extends Demo
{
void m3()
{
System.out.println("abstract method in imple class");
}
}
class Test
{
public static void main(String[] args)
{
Demo d1=new B();
d1.m1();
d1.m2();
d1.m3();
}
}

output

constrcutors in abstract class


concrete without static in abstract class
concrete with static in abstract class
abstract method in imple class

IO Streams

Stream

1.Stream is a medium or channel.


2.The purpose of Stream is to carry data from input devices to output devices and
output devices to input devices.
3.Streams are divided into 2 types.They are
1.Byte Streams
2.Character Streams

Note:Streams are present in java.io package

1.Byte Streams

Byte Streams stores the data in binary format like text,audio,video,pictures..etc

ByteStreams are divided into 2 types.They are


1.InputStream
2.OutputStream

1.InputStream

The purpose of InputStream is to carry the data from source file(java file) to target file(abc.txt)
Ex
---
1.FileInputStream
2.ObjectInputStream
3.DataInputStream

2.OutputStream

The purpose of OutputStream is to carry the data from target file(abc.txt) to source file(java.file)

Ex
---
1.FileOutputStream
2.ObjectOutputStream
3.DataOutputStream

2.Character Streams

Character Streams stores the data in characters format like text.


Character Streams are divided into 2 types.They are
1.Reader
2.Writer

1.Reader

Reader is used to carry the character data from input devices to java application
Ex
--
1.FileReader
2.BufferedReader

2.Writer

Writer is used to carry the character data from java applications to output devices.

1.FileWriter
2.BufferdWriter
3.PrintWriter

PrinWriter

1.printWriter is predefine class.


2.PrintWriter converts primitive data(byte,short,int,float,char...) into text format.

Methods in PrintWriter

1.print===>print() is used to print the data from source file(Demo.java) to target file(venky.txt)in same line.

2.println===>println() is used to print the data from source file to target file in new line.
3.printf===>printf() is used to print the formatting data from source file to target file.

import java.io.*;
class FileOutput
{
public static void main(String[] args)throws Exception
{
FileOutputStream fos=new FileOutputStream("xyz.txt",);
String s1="virat";
byte[] b=s1.getBytes();
fos.write(b);
fos.close();
}
}

xyz.txt=============>String s1="virat";
virat

xyz.txt=============>String s1="kohli";
kohli

FileOutputStream fos=new FileOutputStream("xyz.txt",true);


String s1="virat";
byte[] b=s1.getBytes();
fos.write(b);
fos.close();

xyz.txt=============>String s1="virat";
virat

xyz.txt=============>String s1="kohli";
viratkohli

import java.io.*;
class FileOutput
{
public static void main(String[] args)throws Exception
{
FileInputStream fis=new FileInputStream("xyz.txt");
int size=fis.available();
byte[] b=new byte[size];
fis.read(b);
String s=new String(b);
System.out.println(s);
fis.close();
}
}

viratkohli

import java.io.*;
class Demo
{
public static void main(String[] args)throws Exception
{
FileWriter fw=new FileWriter("pqr.txt");
String data="Hello everyone";
char[] ch=data.toCharArray();
fw.write(data);
fw.close();

}
}

import java.io.*;
class Demo
{
public static void main(String[] args)throws Exception
{
FileReader fr=new FileReader("pqr.txt");
String data="";
int av=fr.read();
while(av!=-1)
{
data=data+(char)av;
av=fr.read();
}
System.out.println(data);
fr.close();
}
}

import java.io.*;
class Demo
{
public static void main(String[] args)throws Exception
{
FileInputStream fis=new FileInputStream("virat.jpg");
int size=fis.available();
byte[] b=new byte[size];
fis.read();
fis.close();

FileOutputStream fos=new FileOutputStream("c:/fs/dhonifriend.jpg");


fos.write(b);
System.out.println("Image is copied into virat to dhonifriend");
fos.close();

}
}

import java.io.*;
class Demo
{
public static void main(String[] args)throws Exception
{
PrintWriter pw=new PrintWriter("mno.txt");
pw.print("virat");
pw.print("kohli");
pw.println("is champ");
pw.println("in the world");

int a=5;
pw.printf("value of a is %d",a);
System.out.println("printing in console");
pw.close();

}
}

viratkohliis champ
in the world
value of a is 5

Dynamic Input approaches

The process of providing input data at runtime(command prompt)is called dynamic data.
There are 3 ways to take data from command prompt.They are

1.BufferedReader
2.Scanner
3.console

1.BufferedReader methods

readLine() is used to store the complete String line data in the form of String.
read() is used to store 1st character of String in the form of ascii value.

BufferedReader can store only String data.


If we want to store byte,short,int,long......data we have convert String into corressponding datatype.

2.Scanner methods

Scanner can store any type of data(byte,short,int,long,float.......)


Scanner is not suitable for to store passwords,pin numbers.....(not secure)

1.int======>nextInt()
2.byte=====>nextByte()
3.short=====>nextShort()
4.long======>nextLong()
5.float=====>nextFloat()
6.double====>nextDouble()
7.char======>next().charAt(0)
8.String====>next(),nextLine()

next() is used to take only single word.


nextLine() is used to take multiple words(String line).

3.Console methods

Console is suitable for to store passwords,pin numbers.....( secure)

readLine() is used to store the complete String line data in the form of String
readPassword() is used to password in the hidden form(it is not visible to users).

import java.io.*;
class Demo
{
public static void main(String[] args)throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter data 1st:");
String s1=br.readLine();
System.out.println("enter data 2nd:");
int av=br.read();
System.out.println("first data:"+s1);
System.out.println("second data:"+av+(char)av);
}
}

enter data 1st:


Bhavadeesh
enter data 2nd:
Bhavadeesh
first data:Bhavadeesh
second data:66B

import java.io.*;
class Demo
{
public static void main(String[] args)throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter a value: ");
String a=br.readLine();
System.out.println("enter b value: ");
String b=br.readLine();
System.out.println(a+b);
int fn=Integer.parseInt(a);
int sn=Integer.parseInt(b);
System.out.println(fn+sn);
}
}

enter a value:
5
enter b value:
6
56
11

import java.io.*;
import java.util.*;
class Demo
{
public static void main(String[] args)throws Exception
{
Scanner sc=new Scanner(System.in);
System.out.println("enter username: ");
String uname=sc.nextLine();
System.out.println("enter password: ");
String pd=sc.next();
System.out.println(uname);
System.out.println(pd);

}
}

enter username:
Bhavadeesh
enter password:
Bhavi
Bhavadeesh
Bhavi

import java.io.*;
class Demo
{
public static void main(String[] args)throws Exception
{
Console c=System.console();
System.out.println("enter username: ");
String uname=c.readLine();
System.out.println("enter password: ");
char[] pwd=c.readPassword();
String pd=new String(pwd);
System.out.println(uname);
System.out.println(pd);

}
}
enter username:
Bhavadeesh
enter password:

Bhavadeesh
bhavi

Serialization

The process of converting an object into a series of bits.


In java Object must be Serializable to do the following operations.

1.Writing an object to file


2.Reading an object from file
3.Writing an object to Network
2.Reading an object from Network

class must implements Serializable interface.


Serializable

Serializable is a marker interface(i.e) no methods.


The purpose of marker interface will provide information about objects to jvm.

DeSerialization

The process of converting series of bits into an Object.

import java.io.*;
class Emp implements Serializable
{
int eno;
String ename;
}
class SerEx
{
public static void main(String[] args)throws Exception
{
Emp e1=new Emp();
FileOutputStream fs=new FileOutputStream("pqr.txt");
ObjectOutputStream oos=new ObjectOutputStream(fs);
oos.writeObject(e1);
fs.close();
oos.close();

FileInputStream fis=new FileInputStream("pqr.txt");


ObjectInputStream ois=new ObjectInputStream(fis);
Emp e2=(Emp)ois.readObject();
System.out.println(e2.eno+" "+e2.ename);
fis.close();
ois.close();

}
}

packages

1.package is a folder structure.


2.Package is a collection of classes,interfaces,enums,annotations,errors,Exceptions.
3.packages are divided into 2 types.They are
1.predefine packages
2.UserDefine packages

1.predefine packages

A package which is already present in java software(jdk).These packages are developed by java
developers.
java.lang is a bydefault package in java.

There are 14 predefine packages in java.


1.java.lang
2.java.util
3.java.io.......

2.Userdefine packages

A package which is not present in java software(jdk).These packages are developed by java
programmers.

package conventions

www.tcs.com==================>domain name

com.tcs======================>reverse domain

com.tcs.bank.withdraw

com.tcs=====>domain
bank========>project
withdraw====>module

com.tcs.bank.withdraw module1
com.tcs.bank.account module2
com.tcs.bank.transfer module3
com.tcs.bank.loans module4

syntax
------
package packagename;
class ClassName
{
}
interface InterfaceName
{
}
enum EnumName
{
}

Advantages of packages

1.parallely we can develop project


2.code resuability across folders.
3.packages removes naming conflicts
4.maintenance easy and readibility improved

package com.tcs.bank.account;
class Sample
{
public static void main(String[] args)
{
System.out.println("welcome to packages");
}
}
interface I1
{
}

javac Sample.java
Sample
I1

java Sample

error

compilation of packages

javac -d . Sample.java

Here
-d====================>directory
.====================>current directory

com
|---tcs
|--bank
|--account
|-I1
|-Sample

Execution of packages

java fullname
java com.tcs.bank.account.Sample

package com.tcs.bank.account;
class Sample
{
public static void main(String[] args)
{
System.out.println("welcome to packages");
}
}
interface I1
{
}

javac -d . Sample.java

java com.tcs.bank.account.Sample
welcome to packages

package com.tcs.bank.withdraw;
class Sample
{
public static void main(String[] args)
{
System.out.println("packages easy");
}
}

javac -d . Sample.java

java com.tcs.bank.withdraw.Sample
packages easy
com
|--tcs
|--bank
|--withdraw
|-Sample

import

1.import is a keyword in java.


2.The purpose of import carrying or trasffering variables and methods from 1 package to another
package.

public=======>Anywhere
protected====>package and subclass of another package
default======>package
private======>class

without import statement shall we access methods or variables from 1 package to another package.

yes,possible.

package com.state.info;
public class Info
{
public void apInfo()
{
System.out.println("jai ap");
}
public void tsInfo()
{
System.out.println("jai ts");
}

package com.state.requiredinfo;
import com.state.info.Info;

class Client
{
public static void main(String[] args)
{
Info i1=new Info();
i1.apInfo();
i1.tsInfo();
}
}

javac -d . Info.java

javac -d . Client.java

java com.state.requiredinfo.Client
jai ap
jai ts
package com.state.info;
public class Info
{
public void apInfo()
{
System.out.println("jai ap");
}
public void tsInfo()
{
System.out.println("jai ts");
}

package com.state.requiredinfo;

class Client
{
public static void main(String[] args)
{
com.state.info.Info i1=new com.state.info.Info();
i1.apInfo();
i1.tsInfo();
}
}

javac -d . Info.java

javac -d . Client.java

java com.state.requiredinfo.Client
jai ap
jai ts

1.Multitasking Introduction
2.Types of Multitasking
3.Thread class and Runnable Interface
4.Getting and setting names for Threads
5.Priorities of Thread
6.join(),yield(),sleep()
7.synchronization and Asynchronization
8.Daemon Threads
9.InterThread communication
10.Deadlock and starvation

Multitasking

1.The process of executing multiple tasks a time(simultaneously/parallely/concurrently)


2.Multitasking is divided into 2 types.They are
1.Process based tasking
2.Thread based tasking(Multithreading)

1.Process based tasking

The process of executing multiple tasks simultaneously.Here each task is a separate process(program)
Process based tasking is applicable for os level.
Each process(program) has separate memory address.
Processors(programs) are heavy weight.
Communication between 2 processors is exepensive
Switching from 1 processor to another processor is expensive

2.Thread based tasking(Multithreading)

The process of executing multiple tasks simultaneously.Here each task is a separate


thread in same program.
Thread based tasking is applicable for programmatic level.
All the threads in same program will have memory address.
Threads are light weight.
Communication between 2 Threads is not exepensive
Switching from 1 Thread to another Thread is not expensive.

Note:The purpose of MultiThreading is to achieve concurrent/parallel/simultaneous


execution.So we will get fastest execution.

Realtime applications for Multithreading

1. Video games applications.


2. Animations applications.
3.Multimedia graphics applications.

Thread

1.Thread is a flow of control or piece of code.


2.Threads are divided into 2 types.They are
1.predefine Threads(single Thread)
2.Userdefine Threads(Multiple Threads)
3.In java Thread is defined in 2 ways.They are
1.By extending Thread class
2.By implementing Runnable interface

Note:1 class extends 1 class


1 class implements multiple interfaces
1 interface extends multiple interface

Thread

1.Thread is a predefine class.


2.Thread class contains start() and run()
Runnable

1.Runnable is a predefine interface.


2.Runnable interface contains run().

Note:Multiple Inheritance cannot possible in Thread.


Multiple Inheritance can possible in Runnable.

start()

start() is used to start the userdefine thread.


When we call start() Thead is born and not able to predict output.

run()

run() is used to write logic for userdefine thread.


run() must be ovveride.
When we call run() Thead is not born and it will execute like normal method able to predict output.

getName()

getName() is used to get name of the Thread.

setName()

setName() is used to set name for the Thread

currentThread()

currentThread() is used to execute currentThread


currentThread() is static method
we can access currentThread() by using Thread class.

1.predefine Threads

The Threads which are already present java software(jdk).These Threads are developed
by java developers.

Ex
---
Main Thread

Note:In java byfefault Thread is Main Thread.


we can have only single main thread but we can create multiple
userdefine threads.

2.Userdefine Threads

The Threads which are not present java software(jdk).These Threads are developed
by java Programmers.

Ex
---
Mohan Thread
Ajay Thread

Life Cycle of Thread

1. Thread is born
AjayThread a=new AjayThread()

2. Thread is ready to run


a.start()

3. Running state
run() is executing while running thread if calling sleep() or wait() then thread
goes sleeping or waiting state.

4. Dead state
If run method completed thread is going to die.

Priorities

1.Range(MINPRI TO MAXPRI) ===============> 1 to 10


2.Bydefault Priority=======================>5

3.Note:If we set priorities more than 10 and less than 1 then it will give
IllegalArgumentException

4.If we increase or decrease priorities for main thread it will be same for child thread.

5.If we increase or decrease priorities for child thread it will be differnt for main thread.

6.Bydefault priorities will be same for both threads main(5) and child(5) threads
So we not able to predict output.

7.To overcame this problem priorities came into the picture.


If we increase priority for child thread(8) when compared to main thread(5) child
thread will be executed first.

8.If we decrease priority for child thread(3) when compared to main thread(5) child
thread will be executed last.

getPriority()

getPriority() is used to get priority of a Thread

setPriority()

setPriority() is used to set priority for a Thread


class AjayThread extends Thread
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
System.out.println("Main Thread");
}
}
}

Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread

class AjayThread extends Thread


{
public void run()
{
for(int i=1;i<=10;i++)======>Userdefine Thread will die when cond is false
{
System.out.println("Userdefine Thread");====>UserThread is Exceuting
}

}
public static void main(String[] args)
{
AjayThread a=new AjayThread();=====>UserdefineThread is born
a.start();=======================>Userdefine Thread is ready to run

for(int i=1;i<=10;i++)
{
System.out.println("Predefine Thread");
}
}
}

Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Predefine Thread

Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread

class AjayThread extends Thread


{
public void run()
{
for(int i=1;i<=10;i++)
{
System.out.println("Userdefine Thread");
}

}
public static void main(String[] args)
{
AjayThread a=new AjayThread();
a.run();

for(int i=1;i<=10;i++)
{
System.out.println("Predefine Thread");
}
}
}

Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread

class Car extends Thread


{
public void run()
{
System.out.println("car is going");
System.out.println("=================");

}
public static void main(String[] args)
{
Car c1=new Car();
c1.start();
Car c2=new Car();
c2.start();
Car c3=new Car();
c3.start();

}
}

car is going

car is going

car is going

class UserDefineThread implements Runnable


{
public void run()
{
System.out.println("userdefinethread");
}
public static void main(String[] args)
{
UserDefineThread u=new UserDefineThread();
Thread t1=new Thread(u);
t1.start();

}
}

userdefinethread
interface I1
{
}
class UserDefineThread implements Runnable,I1
{
public void run()
{
System.out.println("userdefinethread with multiple inheritance");

}
public static void main(String[] args)
{
UserDefineThread u=new UserDefineThread();
Thread t1=new Thread(u);
t1.start();

}
}

userdefinethread with multiple inheritance

class Venky
{
}
class UserDefineThread extends Thread,Venky
{
public void run()
{
System.out.println("userdefinethread with multiple inheritance");

}
public static void main(String[] args)
{
UserDefineThread u=new UserDefineThread();
u.start();

}
}

Error
UserDefineThread extends Thread,Venky

class VenkyThread extends Thread


{
public static void main(String[] args)
{
System.out.println(Thread.currentThread().getName());==>main
Thread.currentThread().setName("PawanThread");
System.out.println(Thread.currentThread().getName());==>PawanThread

}
}
class VenkyThread extends Thread
{
public void run()
{
}
public static void main(String[] args)
{
System.out.println(Thread.currentThread().getName());
Thread.currentThread().setName("PawanThread");
System.out.println(Thread.currentThread().getName());
System.out.println("================================");
VenkyThread v=new VenkyThread();
System.out.println(v.getName());
v.setName("MaheshThread");
System.out.println(v.getName());

}
}

main
PawanThread

Thread-0
MaheshThread

class VenkyThread extends Thread


{
public void run()
{
System.out.println(Thread.currentThread().getName());
Thread.currentThread().setName("ManjuThread");
System.out.println(Thread.currentThread().getName());

}
public static void main(String[] args)
{
System.out.println(Thread.currentThread().getName());
Thread.currentThread().setName("AjayThread");
System.out.println(Thread.currentThread().getName());
VenkyThread v=new VenkyThread();
v.start();

}
}

main
AjayThread
Thread-0
ManjuThread

class VenkyThread extends Thread


{
public void run()
{
System.out.println(Thread.currentThread().getName());
System.out.println(Thread.currentThread().getPriority());

}
public static void main(String[] args)
{
System.out.println(Thread.currentThread().getName());
System.out.println(Thread.currentThread().getPriority());
System.out.println("============================");
VenkyThread v=new VenkyThread();
v.start();

}
}

main
5

Thread-0
5

class VenkyThread extends Thread


{
public void run()
{
System.out.println(Thread.currentThread().getName());
System.out.println(Thread.currentThread().getPriority());

}
public static void main(String[] args)
{
System.out.println(Thread.currentThread().getName());
System.out.println(Thread.currentThread().getPriority());
Thread.currentThread().setPriority(7);
System.out.println(Thread.currentThread().getPriority());

System.out.println("============================");
VenkyThread v=new VenkyThread();
v.start();

}
}

main
5
7

Thread-0
7

class VenkyThread1 extends Thread


{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("child thread");
}

}
public static void main(String[] args)
{
System.out.println(Thread.currentThread().getName());
System.out.println(Thread.currentThread().getPriority());
System.out.println("================================");
VenkyThread1 v=new VenkyThread1();

System.out.println(v.getName());
v.setPriority(8);
System.out.println(v.getPriority());

v.start();

for(int i=1;i<=5;i++)
{
System.out.println("main thread");
}

}
}

main
5

Thread-0
8
main thread
main thread
main thread
main thread
main thread
child thread
child thread
child thread
child thread
child thread

class Car extends Thread


{

public static void main(String[] args)


{
System.out.println(Thread.currentThread().getPriority());
Thread.currentThread().setPriority(33);==>.IllegalArgumentException
System.out.println(Thread.currentThread().getPriority());

}
}

join()

when join() is called one thread(Mohan thread) want to wait until completion of another thread(Ajay Thread).
join() will give InterruptedException
public void join()
public void join(long ms,int ns)

yield()

yield() is used to stop the execution of current thread(Ajay Thread) and give chance to another thread(Mohan
Thread).

sleep()

sleep() is used to wait/stop the thread for particular time.


sleep() will give InterruptedException

class Demo extends Thread


{
public void run()
{
for(int i=1;i<=10;i++)
{
System.out.println("Ajay thread");
try
{
Thread.sleep(2000);

}
catch(InterruptedException e)
{
}

}
}
public static void main(String[] args)throws InterruptedException
{
Demo d=new Demo();
d.start();
d.join();
for(int i=1;i<=10;i++)
{
System.out.println("Mohan thread");
}

}
}

d.join()

Ajay Thread
Ajay Thread
Ajay Thread
Ajay Thread
Ajay Thread
Ajay Thread
Ajay Thread
Ajay Thread
Ajay Thread
Ajay Thread
Mohan Thread
Mohan Thread
Mohan Thread
Mohan Thread
Mohan Thread
Mohan Thread
Mohan Thread
Mohan Thread
Mohan Thread
Mohan Thread

d.join(3000)

Ajay thread
Ajay thread
Mohan thread
Mohan thread
Mohan thread
Mohan thread
Mohan thread
Mohan thread
Mohan thread
Mohan thread
Mohan thread
Mohan thread
Ajay thread
Ajay thread
Ajay thread
Ajay thread
Ajay thread
Ajay thread
Ajay thread
Ajay thread

class Demo extends Thread


{
public void run()
{
for(int i=1;i<=10;i++)
{
System.out.println("Ajay thread");

}
}
public static void main(String[] args)throws InterruptedException
{
Demo d=new Demo();
d.start();
d.yield();
for(int i=1;i<=10;i++)
{
System.out.println("Mohan thread");
}

}
}

Mohan thread
Mohan thread
Mohan thread
Mohan thread
Mohan thread
Mohan thread
Mohan thread
Mohan thread
Mohan thread
Mohan thread
Ajay thread
Ajay thread
Ajay thread
Ajay thread
Ajay thread
Ajay thread
Ajay thread
Ajay thread
Ajay thread
Ajay thread

synchronization

1.The process of executing one by one thread among multiple threads.


2.The purpose of synchronization is to achieve data consistency.
3.synchronization can be applied by using synchronized.
4.synchronization can be applied to the methods and blocks
5.In case of synchronized method synchronization is applied to the entire method

6.In case of synchronized block synchronization is applied to the few lines of code
and not to entire method.

class ClassRoom
{
synchronized void takeClass(String faculty)
{
for(int i=1;i<=10;i++)
{
System.out.println(i+" class is taking by : "+faculty);
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
}
}
}
}
class UserThread extends Thread
{
ClassRoom c1;
String faculty;
UserThread(ClassRoom c1,String faculty)
{
this.c1=c1;
this.faculty=faculty;
}
public void run()
{
c1.takeClass(faculty);
}

class Demo
{
public static void main(String[] args)
{
ClassRoom c1=new ClassRoom();
UserThread u1=new UserThread(c1,"Bhavadeesh");
UserThread u2=new UserThread(c1,"Durga");
u1.start();
u2.start();

}
}

1 class is taking by : Bhavadeesh


2 class is taking by : Bhavadeesh
3 class is taking by : Bhavadeesh
4 class is taking by : Bhavadeesh
5 class is taking by : Bhavadeesh
6 class is taking by : Bhavadeesh
7 class is taking by : Bhavadeesh
8 class is taking by : Bhavadeesh
9 class is taking by : Bhavadeesh
10 class is taking by : Bhavadeesh
1 class is taking by : Durga
2 class is taking by : Durga
3 class is taking by : Durga
4 class is taking by : Durga
5 class is taking by : Durga
6 class is taking by : Durga
7 class is taking by : Durga
8 class is taking by : Durga
9 class is taking by : Durga
10 class is taking by : Durga

class ClassRoom
{
void takeClass(String faculty)
{
System.out.println("1st 100 lines");
synchronized(this){

for(int i=1;i<=10;i++)
{
System.out.println(i+" class is taking by : "+faculty);
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
}
}
}
System.out.println("last 20 lines");

}
}
class UserThread extends Thread
{
ClassRoom c1;
String faculty;
UserThread(ClassRoom c1,String faculty)
{
this.c1=c1;
this.faculty=faculty;
}
public void run()
{
c1.takeClass(faculty);
}

class Demo
{
public static void main(String[] args)
{
ClassRoom c1=new ClassRoom();
UserThread u1=new UserThread(c1,"Bhavadeesh");
UserThread u2=new UserThread(c1,"Durga");
u1.start();
u2.start();

}
}

1st 100 lines


1st 100 lines
1 class is taking by : Bhavadeesh
2 class is taking by : Bhavadeesh
3 class is taking by : Bhavadeesh
4 class is taking by : Bhavadeesh
5 class is taking by : Bhavadeesh
6 class is taking by : Bhavadeesh
7 class is taking by : Bhavadeesh
8 class is taking by : Bhavadeesh
9 class is taking by : Bhavadeesh
10 class is taking by : Bhavadeesh
1 class is taking by : Durga
last 20 lines
2 class is taking by : Durga
3 class is taking by : Durga
4 class is taking by : Durga
5 class is taking by : Durga
6 class is taking by : Durga
7 class is taking by : Durga
8 class is taking by : Durga
9 class is taking by : Durga
10 class is taking by : Durga
last 20 lines

Asynchronization

1.The process of executing all threads at a time among multiple threads.


2.In Asynchronization data inconsistency will come.

class ClassRoom
{
void takeClass(String faculty)
{
for(int i=1;i<=10;i++)
{
System.out.println(i+" class is taking by : "+faculty);
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
}
}
}
}
class UserThread extends Thread
{
ClassRoom c1;
String faculty;
UserThread(ClassRoom c1,String faculty)
{
this.c1=c1;
this.faculty=faculty;
}
public void run()
{
c1.takeClass(faculty);
}

class Demo
{
public static void main(String[] args)
{
ClassRoom c1=new ClassRoom();
UserThread u1=new UserThread(c1,"Bhavadeesh");
UserThread u2=new UserThread(c1,"Durga");
u1.start();
u2.start();

}
}

1 class is taking by : Bhavadeesh


1 class is taking by : Durga
2 class is taking by : Durga
2 class is taking by : Bhavadeesh
3 class is taking by : Bhavadeesh
3 class is taking by : Durga
4 class is taking by : Bhavadeesh
4 class is taking by : Durga
5 class is taking by : Bhavadeesh
5 class is taking by : Durga
6 class is taking by : Durga
6 class is taking by : Bhavadeesh
7 class is taking by : Durga
7 class is taking by : Bhavadeesh
8 class is taking by : Durga
8 class is taking by : Bhavadeesh
9 class is taking by : Durga
9 class is taking by : Bhavadeesh
10 class is taking by : Durga
10 class is taking by : Bhavadeesh

Daemon Thread

1.A Thread which will execute in background along with another Thread.
2.The purpose of Daemon Thread is to provide support or services to non DaemonThreads.
3.We cannot create Daemon thread for main thread(predefine thread).

4.We can create Daemon thread for child thread(userdefine thread).


5.Life cycle of Daemon thread :Daemon thread will execute based on another thread
(main thread)

Examples

1.Garbage collector, Attach listener,signal Dispatcher,finalizer..etc


Garbage collector

Garbage collector will run along with jvm.


The purpose of Garbage collector is to remove unwanted memeory and improves system
performance.

Methods

1.public final void setDaemon(boolean)


-------------------------------------
setDaemon() is used to set Daemon thread for non Daemon thread.
2.public final boolean isDaemon()
----------------------------------
isDaemon() returns either if thread is Daemon(true) or if thread is not Daemon(false).

class UserDefineThread extends Thread


{
public void run()
{
System.out.println("child Thread");===================>child Thread
System.out.println(Thread.currentThread().isDaemon());===>true
}
public static void main(String[] args)throws IllegalThreadStateException
{
UserDefineThread u1=new UserDefineThread();
u1.setDaemon(true);

u1.start();
System.out.println("main thread");==============>main thread

}
}

class UserDefineThread extends Thread


{
public void run()
{
for(int i=1;i<=10;i++)
{
System.out.println("child thread");
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
}
}

}
public static void main(String[] args)
{
UserDefineThread u1=new UserDefineThread();
u1.start();
System.out.println("main thread");

}
}
u1.setDaemon(true)
main thread main thread
child thread child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread

class UserDefineThread extends Thread


{
public static void main(String[] args)
{
System.out.println(Thread.currentThread().isDaemon());
Thread.currentThread().setDaemon(true);==>IllegalThreadStateException
System.out.println(Thread.currentThread().isDaemon());

}
}

InterThread communication

1.The process of communicating one thread with another thread.


2.InterThread communication can be perform by using
1.wait()
2.notify()
3.notifyAll()
3.InterThread communication is applied to the only synchronized threads.

1.wait()

when a thread is expecting updation or notification from another thread then we have
to use wait() and then thread will goes to waiting state.

2.notify()

when a thread is sending or giving updation or notification to the single waiting thread then we have to use notify().

3.notifyAll()

when a thread is sending or giving updation or notification to the multiple waiting threads then we have to use
notifyAll().
class AjayThread extends Thread
{
public void run()
{

int sum=0;
for(int i=1;i<=100;i++)
{
sum=sum+i;
}

}
}
class Demo
{
public static void main(String[] args)throws Exception
{
AjayThread a1=new AjayThread();
a1.start();
System.out.println(a1.sum);

}
}

case-1 main thread got chance


0

case-2 child thread got chance


5050

case-3 child thread got chance and performed some logic and main got chance
0 to 5050

class AjayThread extends Thread


{
public void run()
{
synchronized(this)
{
System.out.println("child thread got chance 2nd");
int sum=0;
for(int i=1;i<=100;i++)
{
sum=sum+i;
}
System.out.println("performed all logic and giving upd to main");
this.notify();

}
}
}
class Demo
{
public static void main(String[] args)throws Exception
{
AjayThread a1=new AjayThread();
a1.start();
synchronized(a1)
{
System.out.println("main got chance 1st and waiting");
a1.wait();
System.out.println("main got updation");
System.out.println(a1.sum);

}
}
}

output

main got chance 1st and waiting


child got chance 2nd
performed all logic and giving upd to main
main got updation
5050

Deadlock

If two threads are waiting for each other forever where waiting never ends.

starvation

If two threads are waiting for each other forever where waiting ends with certain point.

class AjayThread extends Thread


{
static Thread mt;
public void run()
{
try
{
mt.join();
}
catch(InterruptedException e)
{
}
for(int i=1;i<=10;i++)
{
System.out.println("child Thread");
}

}
}
class Demo
{
public static void main(String[] args)throws Exception
{
AjayThread.mt =Thread.currentThread();
AjayThread a1=new AjayThread();
a1.start();
for(int i=1;i<=10;i++)
{
System.out.println("main Thread");
Thread.sleep(1000);
}

}
}

Here child thread calling join method on main thread object and child thread will stops its execution and wait for
until completion of main thread.

main Thread
main Thread
main Thread
main Thread
main Thread
main Thread
main Thread
main Thread
main Thread
main Thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread

class AjayThread extends Thread


{
static Thread mt;
public void run()
{
try
{
mt.join();
}
catch(InterruptedException e)
{
}
for(int i=1;i<=10;i++)
{
System.out.println("child Thread");
}
}
}
class Demo
{
public static void main(String[] args)throws Exception
{
AjayThread.mt =Thread.currentThread();
AjayThread a1=new AjayThread();
a1.start();
a1.join();
for(int i=1;i<=10;i++)
{
System.out.println("main Thread");
Thread.sleep(1000);
}

}
}

If main thread calls join() on child thread object


child thread calls join() on main thread object
Here both threads will wait forever and stucked .Hence it is called Deadlock

class A
{
public synchronized void d1(B b)
{
System.out.println("Thread1 starts execution of d1 method");
try
{
Thread.sleep(2000);
}
catch(Exception e)
{
}
System.out.println("Thread1 trying to call bis last method");
b.last();
}
public synchronized void last()
{
System.out.println("Inside A last method");
}
}
class B
{
public synchronized void d2(A a)
{
System.out.println("Thread2 starts execution of d2 method");
try
{
Thread.sleep(2000);
}
catch(Exception e)
{
}
System.out.println("Thread2 trying to call Ais last method");
a.last();
}
public synchronized void last()
{
System.out.println("Inside B last method");
}
}
class MyThread extends Thread
{
A a=new A();
B b=new B();
public void m1()
{
this.start();
a.d1(b);
}
public void run()
{
b.d2(a);
}
}
class Demo
{
public static void main(String[] args)
{
MyThread t=new MyThread();
t.m1();
}
}

Thread1 starts execution of d1 method


Thread2 starts execution of d2 method
Thread1 trying to call bis last method
Thread2 trying to call Ais last method

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy