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

Comprehensive Java Programming 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)
21 views225 pages

Comprehensive Java Programming 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

ALL-IN-ONE: JAVA NOTES

java Introduction
[Link] is a popular programming language.
[Link] of java is James’s gosling.
[Link] 1st version (1.0) was introduced by Sun microsystem in 1996.
[Link] 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.
[Link] j2se we will learn java fundamentals.
[Link] using j2se we will develop standalone/desktop/window-based App

2. j2ee
1.j2ee stands for java 2 enterprise edition.
[Link] j2ee we will learn server-side programming.
[Link] using j2ee we will develop enterprise/distributed app.

3. j2me
1.j2me stands for java 2 micro edition.
[Link] j2me we will learn micro side programming.
[Link] 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)
{
[Link]("welcome to java");
}
}
OUTPUT:
welcome to java
___________________________________________________________

Literals
[Link] are input values.
[Link] are divided into 6 types:
[Link] Literals========================>-12,0,12...
[Link] Point Literals=================>-1.2f,1.0f,2.5f...
[Link] Literals======================>'a','z','1',...
[Link] Literals=========================>"Excelr","Trainer"...
[Link] Literals========================>true, false
[Link] Literals=========================>null

Variables
1.A variable is a container.
[Link] purpose of variable is to store operand(value,variable,expression).

[Link] declaration
datatype varname;==========>variable declaration
varname=value==============>assigning
int a;
a=5;

[Link] Initialization
datatype varname=value;
int a=2;

[Link] a=5=======>value
[Link] b=a========>variable
[Link] 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(_ $).
[Link] must not use as variables.
[Link] size is unlimited but according to industry standards do not use variable size more than 16 digits.
[Link] is case sensitive.
[Link] 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
[Link] is a one type of variable.
[Link] purpose of identifier is to identify package, subpackage, class, interface, method....

package
[Link] 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
 [Link]=====>java(package) lang(sub package)
 [Link]=======>java(package) io(sub package)
 [Link]==>java(package) util(subpackage) Arrays(class)
 LinkedList======>class
 lastIndexOf()===>method
 List============>interface
 Set=============>interface
 Map=============>interface
 Comparator======>interface
 Comparable=====>interface

Keywords
[Link] are set of reserved words.
[Link] words will have particular functionality.
[Link] present there are 50 keywords in java including assert, strictfp, enum.
[Link] must be written in lowercase.
[Link] and const are not using in java.
[Link] 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:
[Link]
[Link] primitive/reference datatype

[Link] Datatypes
Primitive datatypes are predefine datatypes.
primitive datatypes store 1 value at a time
There are 8 primitive datatypes in java.
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]

[Link]-primitive datatypes
Non-Primitive datatypes are user-define datatypes.
Non-primitive datatypes store multiple values at a time

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

[Link]
byte datatype will store both positive and negative values without decimals.
Examples:
byte a=10;
[Link](a); ==>10
byte a=-10;
[Link](a); ===>-10

byte a=1.2;
[Link](a); ===>error
byte a=129;
[Link](a); ===>error

[Link]
short datatype will store both positive and negative values without decimals.

Examples:
short a=10;
[Link](a); ==>10
short a=-10;
[Link](a); ===>-10

short a=1.2;
[Link](a); ===>error

[Link]
int datatype will store both positive and negative values without decimals.

Examples:
int a=10;
[Link](a); ==>10
int a=-10;
[Link](a); ===>-10

int a=1.2;
[Link](a); ===>error

[Link]
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;
[Link](a); ==>10
long a=-10;
[Link](a); ===>-10

long a=1.2;
[Link](a); ===>error

[Link]([Link]);

long a=21474836478;
[Link](a); ===>error

long a=21474836478l;
[Link](a); ===>21474836478
[Link] 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

[Link]([Link]);
[Link](Byte.MIN_VALUE);
[Link](Byte.MAX_VALUE);

int datatype stores number format data.

[Link] 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;
[Link](a); ==============>10

int a=012;
[Link](a); ======>10

int a=0x12;
[Link](a); =========>18

int a=10;
[Link](a); ===========>10

String b=[Link](a);
[Link](b); ===========>1010

int a=10;
[Link](a); //10

String b=[Link](a);
[Link](b); //12

int a=10;
[Link](a); //10
String b= [Link](a);
[Link](b); //a

Floating point values


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

[Link]
[Link] datatype stores both positive and negative values with decimal and without decimal.
[Link] values must be ends with f or F.
[Link] float datatype after decimal we can store 7 digits.

Examples
1.>float ab=1.2;====>error
[Link](ab);
2.>float ab=1.2f;
[Link](ab);===>1.2

3.>float ab=-1.2f;
[Link](ab);===>-1.2

4.>float ab=1f;
[Link](ab);===>1.0

Note:float datatype stores scientific data.


e==>exponent===>10

1. float a=3e2f;
[Link](a);=======>300.0

1. float a=7e2f;
[Link](a);========>700.0

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

[Link]

[Link] datatype stores both positive and negative values with decimal and without decimal.
[Link] values must not be ends with f or F.
[Link] double datatype after decimal we can store 16 digits.
[Link] datatype also stores scientific data.

Examples

1.>double ab=1.2;
[Link](ab);====>1.2

2.>double ab=-1.2;
[Link](ab);===>-1.2

3.>double ab=1;
[Link](ab);===>1.0

[Link] DATATYPE SIZE RANGE

1. float 32 1.4E-45 TO 3.4028235E38


2. double 64 4.9E-324 TO 1.7976931348623157E308

[Link]

[Link] datatype store single character and enclosed with single quotes('').
[Link] 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

[Link] ch='a';=====>valid
[Link](ch);===================>a

[Link] ch='ab';=====>invalid
[Link](ch);===================>error

[Link] ch=a;=====>invalid
[Link](ch);===================>error

[Link] ch='9';
[Link](ch);==========>9

[Link] ch='19';
[Link](ch);==========>error

[Link] ch=97;
[Link](ch);=====>a

[Link] ch=65;
[Link](ch);=====>A

[Link] ch='97';
[Link](ch);====>error
[Link]

[Link] datatype is used to store true or false values.


[Link] datatype donot store 0,1 values.

Examples

[Link] b=true
[Link](b);=========>true

[Link] b=false
[Link](b);=========>false

[Link] b=0
[Link](b);=========>error

[Link] b=1
[Link](b);=========>error

Type conversions

[Link] process of converting one datatype into another datatype is called type conversion.
[Link] present total 56 type conversions in java.
[Link] conversions are divided into 2 [Link] are
[Link] type conversions.(19)
[Link] 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

[Link] b=true;
int a=b;
[Link](a);==============>error

[Link] b=true;
float a=b;
[Link](a);==============>error

[Link] a=5;
boolean b=a;
[Link](b);=======>error

[Link] type conversions.(19)

[Link] type conversions are implicit type conversions.


[Link] 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;
[Link](b);=========>12

2. byte a=112;
int b=a;
[Link](b);========>112
3 int a=12;
float b=a;
[Link](b);========>12.0

4. char ch='a';
int b=ch;
[Link](b);========>97

[Link] type conversions.(23)

[Link] type conversions are explicit type conversions.


[Link] 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;
[Link](bh);=========>error

char ch='A';
byte bh=(byte)ch;
[Link](bh);==============>65

int a=122;
char ch=(char)a;
[Link](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

[Link] a=7;
int b=6;
[Link](a+b);===========>13

[Link] a=6;
char b=97;
[Link](a+b);======>103

[Link] a=6;
char b='a';
[Link](a+b);===>103

[Link] a=6;
String s="virat";
[Link](a+s)====>6s

[Link](6+"virat"+7);===>6virat7

Operators

[Link] is a symbol.
[Link] purpose of operators is to perform operations

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


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

[Link] operators(+,-,*,/,%)

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

Examples

[Link](1+2);==========>3
[Link](3-2);==================>1
[Link](6*2);==================>12
[Link](6/2);=================>3(quotient)
[Link](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;
[Link](a+b+(b+c));======================>20
}
}

int a=5;
int b=6;
int c=3;
int d=7;
[Link](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

[Link] operators(<,>,<=,>=,==,!=)

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

[Link](5>3);=============>true
[Link](5>11);============>false
[Link](5>11<2);==========>error
[Link](5<2);=============>false
[Link](5<21);=============>true
[Link](5<=6);=============>true
[Link](6<6);===============>false
[Link](6<=6);==============>true
[Link](2>=2);===============>true
[Link](2==2);===============>true
[Link](2==3);===============>false
[Link](2!=3);==============>true
[Link](2!=2);==============>false

Note:Difference b/w = and ==.


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

[Link] 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.!

[Link]((2>1) && (6>2));======>true


[Link]((2>6) && (6>2));======>false
[Link]((2>1) && (6>2) && (7>5));==>true
[Link]((2>1) && (6>2) && (7>11));==>false
[Link]((2>1) || (6>2) || (7>2));====>true
[Link]((2>1) || (6>12) || (7>2));===>true
[Link]((2>1) || (6>12) || (7>12));===>true
[Link]((2>11) || (6>12) || (7>12));===>false
[Link](!(6>2));==========>false
[Link](!(6>12));=========>true

Increment/Decrement operators

[Link] operator(++var or var++)

Increment operator is used to increment 1 value.


They are 2 types of increment operators.
[Link] increment(++var)
[Link] increment(var++)

[Link] increment(++var)

In pre increment 1st incrementation and next value


In pre increment incrementation is applied to the current operation.

[Link] 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;
[Link](a);====>6

2. int a=5;
a++;
[Link](a);===>6

3. int a=5;
[Link](++a);===>6

4. int a=5;
[Link](a++);===>5

5. int a=5;
[Link](++a + ++a);====>13

6. int a=5;
[Link](a++ + ++a);

7. int a=5;
[Link](a++ + a++);===>11

8. int a=5;
[Link](a++ + ++a + a++);======>19

[Link] operator(--var or var--)

Decrement operator is used to Decrement 1 value.


They are 2 types of Decrement operators.
[Link] Decrement(--var)
[Link] Decrement(var--)

[Link] Decrement(--var)

In pre Decrement 1st Decrementation and next value


In pre Decrement Decrementation is applied to the current operation.

[Link] Decrement(var--)

In post Decrement 1st value and next Decrementation.


In post Decrement Decrementation is applied to the next operation.

Examples

int a=5;
[Link](a++ + --a + a++);=====>15

int a=5;
[Link](a-- + --a + a++);====>11

Bitwise Operators

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

[Link] LeftShift(<<)
[Link] RightShift(>>)
[Link] Complementary(~)
[Link] AND(&)
[Link] OR(|)
[Link] XOR(^)

[Link] LeftShift(<<)

b
FORMULA a*2

Examples

int a=12;
int b=3;
[Link](a<<b);===>96

[Link] RightShift(>>)

FORMULA a
__
b
2

Examples

int a=12;
int b=3;
[Link](a>>b);===>1

[Link] Complementary(~)

Formula ~n=-(n+1)

int a=12;

[Link](~a);===>-13
[Link] AND(&)(multiply)

int a=9;
int b=7;
[Link](a&b);===>1

[Link] OR(|)(addition)

int a=9;
int b=7;
[Link](a|b);===>15

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

1111===>15

[Link] XOR(^)

If same values is there means take 0.


If Different values is there means take 1.

int a=9;
int b=7;
[Link](a^b);

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

11 10

[Link] 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

[Link](5>2?2:3);====>2
[Link](5>12?2:3);=====>3
[Link](5>12?"Excelr institute":"tcs");====>tcs

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

[Link](res);

int a=5;
int b=12;
String res=(a>b)?"super":(b>a)?"Excellent":"Bad";
[Link](res);===>Excellent

[Link] operator

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


tors)

int a=-5;
int b=-a;
[Link](b);========>5

int a=5;
int b=2;
a=a+b;
[Link](a);=====>7

int a=5;
int b=2;
a+=b;===========>a=a+b===>5+2
[Link](a);====>7

int a=5;
int b=2;
a-=b;===>a=a-b
[Link](a);==>3

int a=5;
int b=2;
a*=b;
[Link](a);====>10

int a=5;
int b=2;
a/=b;
[Link](a);==>2

int a=5;
int b=2;
a%=b;
[Link](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 [Link] are


[Link] Statements
[Link] Statements
[Link] Statements
[Link] Statements

[Link] 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
[Link] Statement
[Link] 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
[Link](a);=====>out Statement========>5
}
}

[Link] Statements

[Link] Statements are used to check conditions if condition is true then it


will executes true block other wise false block.
[Link] Statements are divided into 6 [Link] are
[Link] if
[Link] else
[Link] if
[Link] if
[Link] if
[Link]

[Link] 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)
{
[Link]("positive num");=============>positive num
}

int a=5;
if(a>12)
{
[Link]("positive num");================>No ouput
}

[Link] else

[Link] else is used to check 1 condition in 2 blocks.


[Link] condition is true means if block will execute
[Link] condition is false means else block will execute

Syntax

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

int a=5;
int b=2;
if(a>b)
{
[Link](a+" is big num");
}
else
{
[Link](a+" is not big num");

output===>5 is big num

int a=5;
int b=12;
if(a>b)
{
[Link](a+" is big num");
}
else
{
[Link](a+" is not big num");

output===>5 is not big num

[Link] 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)
{
[Link]("A grade");
}
else if((marks>80) && (marks<90))
{
[Link]("B grade");
}
else if((marks>70) && (marks<80))
{
[Link]("C grade");
}
else
{
[Link]("Fail");
}

output====>Fail

int marks=90;
if(marks>90)
{
[Link]("A grade");
}
else if((marks>80) && (marks<90))
{
[Link]("B grade");
}
else if((marks>70) && (marks<80))
{
[Link]("C grade");
}

No ouput

[Link] 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)
{
[Link]("A grade");
}
if((marks>80) && (marks<90))
{
[Link]("B grade");
}
if((marks>70) && (marks<80))
{
[Link]("C grade");
}
else
{
[Link]("Fail");
}

output

B grade
Fail

int marks=87;
if(marks>90)
{
[Link]("A grade");
}
if((marks>80) && (marks<90))
{
[Link]("B grade");
}
if((marks>70) && (marks<80))
{
[Link]("C grade");
}

Output

B grade

if(5>2)
{
[Link]("java");
}
if(15>2)
{
[Link]("python");
}
if(17>2)
{
[Link]("ruby");
}

Output

java
python
ruby

if(5>2)
{
[Link]("java");
}
else if(15>2)
{
[Link]("python");
}
else if(17>2)
{
[Link]("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)
{
[Link]("Nested if");
}
}

Output===>Nested if
if(15>2)====>1(true)
{
if(6>11)====>2(false)
{
[Link]("Nested if");
}
else===>3
{
[Link]("else in nested if");==>4
}
}

output:else in nested if

if(15>22)=======>1(false)
{
if(6>11)
{
[Link]("Nested if");
}
else
{
[Link]("else in nested if");
}
}
else====>2
{
if(12>6)====>3(true)
{
[Link]("if in else");===>4

}
else
{
[Link]("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:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
case 4:
[Link]("Thursday");
break;
case 5:
[Link]("Friday");
break;
case 6:
[Link]("Saturday");
break;
case 7:
[Link]("Sunday");
break;
default:
[Link]("Invalid day");
}
}
}

Programs on Conditional statements

[Link] 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)
{
[Link]("num is even"+num);
}
else
{
[Link]("num is odd"+num);

[Link] a java program to check big number between 2 numbers.

int first=12;
int second=16;
if(first>second)
{
[Link](first+"is a big num");
}
else
{
[Link](second+"is a big num");
}

[Link] a java program to check big number among 3 numbers.

int first=12;
int second=16;
int third=11;
if((first>second) && (first>third))
{
[Link](first+" is a big num");
}
else if((second>first) && (second>third))
{
[Link](second+" is a big num");

}
else
{
[Link](third+" is a big num");

[Link] 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))
{
[Link](first+" is a big num");
}
else if((second>first) && (second>third) && (second>four))
{
[Link](second+" is a big num");

}
else if((third>first) && (third>second) && (third>four))
{
[Link](third+" is a big num");

}
else
{
[Link](four+" is a big num");

[Link] 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'))
{
[Link](ch+"is a lowercase");
}
else
{
[Link](ch+"is a uppercase");

[Link] a java program to check character lowercase or uppercase or digit

char ch='v';
if((ch>='a') && (ch<='z'))
{
[Link](ch+"is a lowercase");
}
else if((ch>='A') && (ch<='Z'))
{
[Link](ch+"is a uppercase");

}
else
{
[Link](ch+"is a digit");

[Link] a java program to check character lowercase or uppercase or digit or special


symbol.

char ch='*';
if((ch>='a') && (ch<='z'))
{
[Link](ch+"is a lowercase");
}
else if((ch>='A') && (ch<='Z'))
{
[Link](ch+"is a uppercase");

}
else if((ch>='0') && (ch<='9'))
{
[Link](ch+"is a digit");

}
else
{
[Link](ch+"is a special symbol");

[Link] 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'))
{
[Link]("vowel");
}
else
{
[Link]("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'))
{
[Link]("vowel");
}
else
{
[Link]("consononat");

[Link] a java program to convert lowercase charcter into upper case.

char ch='b';
[Link](ch);
int val=ch-32;
[Link](val);
char ori=(char)val;
[Link](ori);

[Link] a java program to convert uppercase charcter into lowerr case.

char ch='b';
[Link](ch);
int val=ch+32;
[Link](val);
char ori=(char)val;
[Link](ori);

[Link] a java program to swap 2 numbers with 3rd variable.

int first=10;
int second=20;
[Link]("Before Swapping");
[Link]("first is"+first);
[Link]("second is"+second);
[Link]("===================");
[Link]("After Swapping");
int temp=first;
[Link]("temp is"+temp);
first=second;
[Link]("first is"+first);
second=temp;
[Link]("second is"+second);

[Link] a java program to swap 2 numbers without 3rd variable.


int first=10;
int second=20;
[Link]("Before Swapping");
[Link]("first is"+first);
[Link]("second is"+second);
[Link]("===================");
[Link]("After Swapping");
first=first+second;
[Link](first);
second=first-second;
[Link](second);
first=first-second;
[Link](first);

int first=10;
int second=20;
[Link]("Before Swapping");
[Link]("first is"+first);
[Link]("second is"+second);
[Link]("===================");
[Link]("After Swapping");
first=first*second;
[Link](first);
second=first/second;
[Link](second);
first=first/second;
[Link](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))
{
[Link](" leap year");
}
else
{
[Link](" 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

[Link]====>Starting value
[Link]=========>Ending value
[Link] into block (execute statements)
[Link](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++)
{
[Link](i);
}

[Link] 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)
{
[Link](i);
i++;
}
}

[Link] while loop

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

do while loop Execution


-------------------------
[Link]
[Link]
[Link]/dec
[Link]
Syntax

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

int i=5;
do
{
[Link](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
{
[Link](i);
}
}

Programs on while loop

[Link] 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;
}
[Link](cd);

[Link] 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;
}
[Link](sum);

[Link] 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;
}
[Link](rev);

[Link] a java program to print 5 table.

int num=5;
int i=1;
while(i<=10)
{
[Link](num+"*"+i+"="+num*i);
i++;
}

[Link] 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)
{
[Link]("palindrome");
}
else
{
[Link]("Not palindrome");

[Link] 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)
{
[Link]("Armstrong");
}
else
{
[Link]("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;

}
[Link](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)
{
[Link]("Armstrong");
}
else
{
[Link]("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+=([Link](rem,count));
temp=temp/10;
}

if(num==sum)
{
[Link]("Armstrong");
}
else
{
[Link]("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)
{
[Link]("Strong");
}
else
{
[Link]("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;
}
[Link](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;
}
[Link](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;
}
[Link](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)
{
[Link](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;

}
[Link](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)
{
[Link]("prime");
}
else
{
[Link]("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)
{
[Link]("perfect");
}
else
{
[Link]("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;
[Link](first);
[Link](second);
for(int i=2;i<=10;i++)
{
int sum=first+second;
[Link](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)
{
[Link](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)
{
[Link](i);
}
}

pattern programs

1>Square

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

for(int i=1;i<=5;i++)
{
for(int j=1;j<=5;j++)
{
[Link]("*");
}
[Link]();
}

[Link] Traingle

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

for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
[Link]("*");
}
[Link]();
}

3.>Decrementing Traingle

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

for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
[Link]("*");
}
[Link]();
}
1
12
123
1234
12345

for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
[Link](j);

}
[Link]();
}

1
22
333
4444
55555

for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
[Link](i);

}
[Link]();
}
1
23
456
78910
1112131415

int c=1;
for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
[Link](c);
c++;
}
[Link]();
}

1
21
321
4321
54321
for(int i=1;i<=5;i++)
{
for(int j=i;j>=1;j--)
{
[Link](j);
}
[Link]();
}
5
54
543
5432
54321
for(int i=5;i>=1;i--)
{
for(int j=5;j>=i;j--)
{
[Link](j);
}
[Link]();
}

5
44
333
2222
11111

for(int i=5;i>=1;i--)
{
for(int j=5;j>=i;j--)
{
[Link](i);
}
[Link]();
}

5
45
345
2345
12345

for(int i=5;i>=1;i--)
{
for(int j=i;j<=5;j++)
{
[Link](j);
}
[Link]();
}

12345
2345
345
45
5
for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
[Link](j);
}
[Link]();
}

11111
2222
333
44
5
for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
[Link](i);
}
[Link]();
}

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

for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
[Link](" ");
}
for(int k=1;k<=i;k++)
{
[Link]("*");
}
[Link]();

}
1
12
123
1234
12345

for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
[Link](" ");
}
for(int k=1;k<=i;k++)
{
[Link](k);
}
[Link]();
}

1
22
333
4444
55555
for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
[Link](" ");
}
for(int k=1;k<=i;k++)
{
[Link](i);
}
[Link]();
}
1
21
321
4321
54321

for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
[Link](" ");
}
for(int k=i;k>=1;k--)
{
[Link](k);
}
[Link]();
}

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

for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
[Link](j);
}
for(int k=1;k<=i;k++)
{
[Link]("*");
}
[Link]();
}
123451
234512
345123
451234
512345

for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
[Link](j);
}
for(int k=1;k<=i;k++)
{
[Link](i);
}
[Link]();
}

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

for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
[Link](" ");
}
for(int k=1;k<i;k++)
{
[Link]("*");
}
for(int r=1;r<=i;r++)
{
[Link]("*");
}
[Link]();

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

for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
[Link](" ");
}
for(int k=1;k<i;k++)
{
[Link](k);
}
for(int r=1;r<=i;r++)
{
[Link]("*");
}
[Link]();

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

for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
[Link](" ");
}
for(int k=1;k<i;k++)
{
[Link]("*");
}
for(int r=1;r<=i;r++)
{
[Link](r);
}
[Link]();

1
112
12123
1231234
123412345

for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
[Link](" ");
}
for(int k=1;k<i;k++)
{
[Link]("*");
}
for(int r=1;r<=i;r++)
{
[Link](r);
}
[Link]();

1
222
33333
4444444
555555555

for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
[Link](" ");
}
for(int k=1;k<i;k++)
{
[Link](i);
}
for(int r=1;r<=i;r++)
{
[Link](i);
}
[Link]();

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

for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
[Link](" ");
}
for(int k=i;k<5;k++)
{
[Link]("*");
}
for(int r=i;r<=5;r++)
{
[Link]("*");
}
[Link]();
}

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

for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
[Link](" ");
}
for(int k=i;k<5;k++)
{
[Link](k);
}
for(int r=i;r<=5;r++)
{
[Link]("*");
}
[Link]();
}
****12345
***2345
**345
*45
5

for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
[Link](" ");
}
for(int k=i;k<5;k++)
{
[Link]("*");
}
for(int r=i;r<=5;r++)
{
[Link](r);
}
[Link]();
}

123412345
2342345
34345
445
5
for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
[Link](" ");
}
for(int k=i;k<5;k++)
{
[Link](k);
}
for(int r=i;r<=5;r++)
{
[Link](r);
}
[Link]();
}
111111111
2222222
33333
444
5

for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
[Link](" ");
}
for(int k=i;k<5;k++)
{
[Link](i);
}
for(int r=i;r<=5;r++)
{
[Link](i);
}
}

*
**
***
****
*****
*****
****
***
**
*
for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
[Link](" ");
}
for(int k=1;k<=i;k++)
{
[Link]("*");
}
[Link]();

}
for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
[Link](" ");
}
for(int k=i;k<=5;k++)
{
[Link]("*");

}
[Link]();

Jumping statements

Jumping statements are used to terminate loop and skip the particular iteration of a loop.
Jumping statements are divided into 2 [Link] are
[Link]
[Link]
Jumping Statements must be applied on loops.

[Link]

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

for(int i=1;i<=10;i++)
{
if(i==6)
{
break;
}
else
{
[Link](i);
}
}

[Link]

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
{
[Link](i);
}
}

Arrays

[Link] is a predefine class.[Arrays class is present in [Link] package)


[Link] is non primitive/refernce datatype.
[Link] purpose of Arrays is to store multiple values with same datatype.
[Link] 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;

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

[Link] 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};
[Link](arr[0])=====>2
[Link](arr[2])=====>4
[Link](arr[-3])=====>ArrayIndexOutOfBoundsException

[Link] we print Array directly it will gives memory address.


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

[Link] are 3 ways to print array elements


[Link] loop
[Link] forloop or ForEach loop
[Link]()
[Link] 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
[Link]

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


syntax
-------
datatype varname=[Link];
int l=[Link];
int[] arr={2,3,4,5};
int len=[Link];
[Link](len);========>4

[Link] is by itself an object.

[Link] forloop or ForEach loop


syntax
-------
for(datatype vranme : arrayvarname)
{
Statetement
}
[Link] forloop and enhance forloop

forloop

[Link] Initialization.
[Link] condition.
[Link] updation

enchance forloop

[Link] not contains Initialization.


[Link] not contains condition.
[Link] not contains updation
[Link] forloop is faster(because it is not performing operations like
initilazition,condition,updation)

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

Examples

[Link] Rohit
{
public static void main(String[] args)
{
int[] ab=new int[4];
ab[0]=2;
ab[1]=4;
ab[2]=6;
ab[3]=8;
[Link](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++)
{
[Link](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++)
{
[Link](ab[i]);
}

}
}

class Rohit
{
public static void main(String[] args)
{
int[] ab=new int[4];
ab[-1]=2;
[Link](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++)
{
[Link](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=[Link];
[Link](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<[Link];i++)
{
[Link](ch[i]);
}

}
}

class Sample
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
[Link](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<[Link];i++)
{
[Link](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<[Link];i++)
{
[Link](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)
{
[Link](b);
}

}
}

predefine methods

The methods which are already present in java [Link] methods which are
developed by java developers.

import [Link]

userdefine methods

The methods which are not present in java [Link] methods which are
developed by java programmers.

[Link]()

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

syntax

[Link](arrayvarname);
import [Link];
class Sample
{
public static void main(String[] args)
{
int[] a={6,3,2,1};
[Link](a);
for(int i=0;i<[Link];i++)
{
[Link](a[i]);
}

}
}

[Link]()

toString() is used to print array elements.

syntax

[Link](arrayvarname);

import [Link];
class Demo
{
public static void main(String[] args)
{
int[] a={2,3,1,4};
[Link]([Link](a));======>[2, 3, 1, 4]
}
}

[Link]()

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

syntax
-------
boolean varname=[Link](arrvarnam1,arrvarnam2)

import [Link];
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
int[] b={1,2,3,4};
boolean res=[Link](a,b);
[Link](res);==================>true

}
}
import [Link];
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
int[] b={1,2,3,4,5};
boolean res=[Link](a,b);
[Link](res);============>false

}
}

import [Link];
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
int[] b={1,2,4,3};
boolean res=[Link](a,b);
[Link](res);================>false

}
}

[Link]()

mismatch() returns -1 when both arrayelements are same


returns particular index where element is not matched

syntax
-------
int varname= [Link](arrayvarname1,arrayvarmae2);

import [Link];
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
int[] b={1,2,3,4};
int abc=[Link](a,b);
[Link](abc);==================>-1

}
}

import [Link];
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
int[] b={5,2,3,4};
int abc=[Link](a,b);
[Link](abc);========================>0

}
}

import [Link];
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
int[] b={1,2,8,4};
int abc=[Link](a,b);
[Link](abc);=====================>2

}
}

[Link]()

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

syntax
-------
int varname=[Link](arrayvarname,element);

import [Link];
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
int bhavadeesh=[Link](a,3);
[Link](bhavadeesh);================>2

}
}

import [Link];
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
int bhavadeesh=[Link](a,4);
[Link](bhavadeesh);=================>3

}
}

import [Link];
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
int bhavadeesh=[Link](a,6);===========>-5
[Link](bhavadeesh);

}
}

import [Link];
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
int bhavadeesh=[Link](a,0);
[Link](bhavadeesh);=================>-1

}
}

import [Link];
class Demo
{
public static void main(String[] args)
{
int[] a={2,4,7,8,9,10};
int bhavadeesh=[Link](a,5);
[Link](bhavadeesh);================>-3

}
}

import [Link];
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
int bhavadeesh=[Link](a,5);
[Link](bhavadeesh);=====================>-5

}
}

[Link]()

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

syntax
------
datatype[] varname=[Link](arrayvarname,startindex,endindex);
import [Link];
class Demo
{
public static void main(String[] args)
{
int[] onearray={2,4,7,8,9,10};
int l=[Link];
int[] anotherarr=[Link](onearray,0,l-1);
[Link]([Link](anotherarr));===>[2,4,7,8,9]

}
}

import [Link];
class Demo
{
public static void main(String[] args)
{
int[] onearray={2,4,7,8,9,10};
int l=[Link];
int[] anotherarr=[Link](onearray,0,3);
[Link]([Link](anotherarr));======>[2,4,7]

}
}

import [Link];
class Demo
{
public static void main(String[] args)
{
int[] onearray={2,4,7,8,9,10};
int l=[Link];
int[] anotherarr=[Link](onearray,2,4);
[Link]([Link](anotherarr));=======>7,8

}
}

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

int[] a={2,1,4,5,6};
[Link](a[0]);========================>2
[Link](a[1]);========================>1
[Link](a[[Link]-1]);===============>6
a[5-1]
a[4]==========================>6

[Link] 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[[Link]-1];
[Link](first+last);
[Link] a java program to swap to 1st and last element of an array.
import [Link].*;
class Demo
{
public static void main(String[] args)
{
int[] a={2,1,4,5,6};
int temp=a[0];
a[0]=a[[Link]-1];
a[[Link]-1]=temp;
[Link](a[0]);
[Link](a[[Link]-1]);
[Link]([Link](a));

}
}

[Link] a java program to print array elements.


int[] arr={1,7,6,5};
for(int i=0;i<=[Link]-1;i++)
{
[Link](arr[i]);
}

[Link] a java program to print index values of an array.


int[] arr={1,7,6,5};
for(int i=0;i<=[Link]-1;i++)
{
[Link](i);
}

[Link] a java program to print even elements of an array.


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

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

[Link] 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<[Link];i++)
{
if(arr[i]%2==0)
{
count++;
}
}
[Link](count);

[Link] 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<[Link];i++)
{
sum=sum+a[i];

}
[Link](sum);

[Link] a java program to print prime numbers of an array.


int[] a={1,2,3,4,5,6,7};
for(int i=0;i<[Link];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)
{
[Link](a[i]);
}
}

[Link] a java program to reverse array elements

int[] arr={2,4,3,1};
for(int i=[Link]-1;i>=0;i--)
{
[Link](arr[i]);
}

[Link] a java program to print duplicate elements of an array

int[] a={1,2,3,1};
for(int i=0;i<[Link];i++)
{
for(int j=i+1;j<[Link];j++)
{
if(a[i]==a[j])
{
[Link](a[i]);
}
}
}

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

[Link] a java program to sort an array without predefined methods.

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

[Link] a java program to find maximum number of an array.

[Link] to sort of an array


[Link] 1st and 2nd element
[Link] 1st element is greater than 2nd element
[Link] have to swap.
[Link] swapping the elements will be small to big.
[Link] print 2nd maximum length-1.

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

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

[Link] a java program to find 2nd maximum number of an array.

[Link] to sort of an array


[Link] 1st and 2nd element
[Link] 1st element is greater than 2nd element
[Link] have to swap.
[Link] swapping the elements will be small to big.
[Link] print 2nd maximum length-2.

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

[Link] a java program to copy array elements into another array

int[] a1={1,2,3,4,5};
int[] a2=new int[[Link]];
for(int i=0;i<[Link];i++)
{
a2[i]=a1[i];
[Link](a2[i]);
}

[Link] 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[[Link]];
int evenindex=0;
int oddindex=[Link]-1;
for(int i=0;i<[Link];i++)
{
if(a1[i]%2==0)
{
output[evenindex]=a1[i];
evenindex++;
}
else
{
output[oddindex]=a1[i];
oddindex--;
}
}
for(int anything : output)
{
[Link](anything);
}

[Link] 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<[Link];i++)
{
if(a[i]==target)
{
[Link]("element found");
}

[Link] a java program to shift array elements to left side and first element to last.

import [Link].*;
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4,5};
int first=a[0];
for(int i=0;i<[Link]-1;i++)
{
a[i]=a[i+1];
}
a[[Link]-1]=first;
[Link]([Link](a));
}
}

[Link] a java program to print leader elements of an array.

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

[Link] a java program to merge to arrays and copy into another array.

int[] a={1,2,3};
int[] b={4,5,6};
int l1=[Link];
int l2=[Link];
int[] c=new int[l1+l2];
for(int i=0;i<[Link];i++)
{
c[i]=a[i];
}
int an=l1;
for(int j=0;j<[Link];j++)
{
c[an]=b[j];
an++;
}
[Link]([Link](c));

[Link] a java program to print unique elements of an array

import [Link].*;
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,1,2,1};
for(int i=0;i<[Link];i++)
{
for(int j=i+1;j<[Link];j++)
{
if(a[i]==a[j])
{
a[j]=0;
}
}
}
[Link]([Link](a));
for(int j=0;j<[Link];j++)
{
if(a[j]!=0)
{
[Link](a[j]);
}
}

}
}

[Link] 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<[Link]-1;i++)
{
for(int j=i+1;j<[Link];j++)
{
if(a[i]+a[j]==10) 6,4
{ 9,1
[Link](a[i]+" "+a[j]); 8,2
}
}
}

[Link] a java program to print all subarrays of an array.

int[] a={1,2,3,4,5};
for(int i=0;i<[Link];i++)
{
for(int j=i;j<[Link];j++)
{
for(int k=i;k<=j;k++)
{
[Link](a[k]);
}
[Link]();
}

[Link] 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<[Link];i++)
{
int sum=0;
for(int j=i;j<[Link];j++)
{
sum=sum+a[j];
if(sum==target)
{
for(int k=i;k<=j;k++)
{
[Link](a[k]);
}
[Link]();

}
}

[Link] a java program to print missing number.

int[] a={5,3,1,2};
int n=[Link]+1;
int sum=n*(n+1)/2;
int restSum=0;
for (int i = 0; i < [Link]; i++) {
restSum+=a[i];
}
int missingNumber=sum-restSum;
[Link](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
{
[Link](v[i][j]);
}
[Link]();==================>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++)
{
[Link](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++)
{
[Link](a[i][j]);
}
[Link]();
}
}
}

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

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<[Link];i++)
{
for(int j=0;j<a[i].length;j++)
{
[Link](a[i][j]);
}
[Link]();
}
}
}

[Link] 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<[Link];i++)
{
for(int j=0;j<a[i].length;j++)
{
[Link](a[i][j]+b[i][j]+" ");
}
[Link]();
}

[Link] 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<[Link];i++)
{
for(int j=0;j<a[i].length;j++)
{
[Link](a[i][j]-b[i][j]+" ");
}
[Link]();
}

[Link] 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];

}
[Link](c[i][j]+" ");
}
[Link]();
}

String Handling

[Link]
[Link]
[Link]
[Link]
Note:String,StringBuffer,StringBuilder is present in [Link] package(bydefault).

[Link]

[Link] is a predefine class.


[Link] purpose of String is to store multiple characters enclosed with double quotes.
[Link] value can be stored in 2 ways.
[Link] using directly(literal)
[Link] using new keyword
[Link] is immutable.
[Link] is synchronized.
[Link] is thread safe.

[Link] between literal and new keyword.

[Link] using literal

[Link] literal string data stored in String constant pool(scp) area.


[Link] literal String data is same in 2 variables then it will create one object.

String s1="pawan";
[Link](s1);===============================>pawan
[Link]([Link](s1));==========>359023572
String s2="pawan";
[Link](s2);===============================>pawan
[Link]([Link](s2));==========>359023572

[Link] using new Keyword

[Link] new Keyword string data stored in Heap area.


[Link] new keyword string data is same in 2 variables then it will create 2 objects.

String s1=new String("pawan");


[Link](s1);===============================>pawan
[Link]([Link](s1));==========>359023572
String s2=new String("pawan");
[Link](s2);==============================>pawan
[Link]([Link](s2));========>305808283

[Link] 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";
[Link](s1);
[Link]([Link](s1));
String s2="pawan";
[Link](s2);
[Link]([Link](s2));
[Link]([Link](s2));==============================>true
[Link](s1==s2);=====================================>true
[Link]("===================================");
String s3=new String("pawan");
[Link](s3);
[Link]([Link](s3));
String s4=new String("pawan");
[Link](s4);
[Link]([Link](s4));
[Link]([Link](s4));========================>true
[Link](s3==s4);===============================>false

[Link] between mutable and immutable.


mutable

[Link] means data can be changed.


[Link] classes are may or may not be synchronized.
[Link] and after operations hashCode will be same.

immutable

[Link] means data cannot be changed.


[Link] classes are synchronized.
[Link] and after operations hashCode will be different.

Examples

1.
String sname="Hemanth Kumar";
[Link](sname);===================>Hemanth Kumar

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


[Link](sname);===================>Hemanth Kumar

Predefine methods in String

[Link]()

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

syntax

datatype varname=[Link](index);

String s="Hemanth";
char abc=[Link](3);
[Link](abc);========>a

[Link]()

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

syntax

datatype varname=[Link](character);

String s="Hemanth";
int ad=[Link]('a');
[Link](ad);===============>3

String s="Haemanth";
int ad=[Link]('a');
[Link](ad);===============>1
[Link]()

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

syntax

datatype varname=[Link](character)

String s="Haemanth";
int b=[Link]('a');
[Link](b);================>4

[Link]()

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

syntax

datatype varname=[Link](startindex,endindex);
String s="Hemanth";
int len=[Link]();
[Link](len);
String xyz=[Link](0,len);
[Link](xyz);

String s="Hemanth";

String xyz=[Link](4);
[Link](xyz);============>nth

[Link]()

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

syntax

datatype varname=[Link]();

String s="Hemanth";
int len=[Link]();
[Link](len);=============>7

[Link]()

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

syntax

datatype[] varname=[Link](character);
String s="Heman kuma rah";
String[] abc=[Link](" ");
[Link]([Link](abc));==========>[Heman,kuma,rah]

String s="Hemankumarah";
String[] abc=[Link]("a");
[Link]([Link](abc));==========>[Hem,nkum,r,h]

[Link]()

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

datatype[] varname=[Link]();

String s="Durga";
char[] vn=[Link]();
[Link]([Link](vn));=========>[D,u,r,g,a]

[Link]()

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

syntax

datatype varname=[Link](svn2)

String s1="virat";
String s2="virat";
boolean anc=[Link](s2);
[Link](anc);================>true

String s1="vIrat";
String s2="virat";
boolean anc=[Link](s2);
[Link](anc);=============>false

[Link]()

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

syntax

datatype varname=[Link](svn2)

String s1="virat";
String s2="virat";
boolean anc=[Link](s2);
[Link](anc);================>true

String s1="vIrat";
String s2="virat";
boolean anc=[Link](s2);
[Link](anc);=============>true

[Link]()

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


syntax

datatype varname=[Link]();

String s1="virat";
String s2="kohli";
String fullname=[Link](s2);
[Link](fullname);==============>viratkohli

String s1="virat";
String fullname=[Link]("kohli");
[Link](fullname);==============>viratkohli

[Link]()

parseInt() is used to convert String into int.

syntax

datatype varname=[Link](svn);

String s="123";
[Link](s+5);======>1235
int a=[Link](s);
[Link](a+5);=====>128

String s="onetwothree";
[Link](s);
int a=[Link](s);
[Link](a);=================>NumberFormatException

[Link]()

valueOf() is used to convert int into String.

syntax

datatype varname=[Link](intvarname)

int a=123;
String s=[Link](a);
[Link](s);=============>123

[Link]()

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

syntax

datatype varname=[Link](char);

String s="dhoni";
boolean vn=[Link]("d");
[Link](vn);===========>true
String s="dhoni";
boolean vn=[Link]("dho");
[Link](vn);=========>true

String s="dhoni";
boolean vn=[Link]("ho");
[Link](vn);========>false

[Link]()

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

syntax

datatype varname=[Link](char);

String s="dhoni";
boolean vn=[Link]("i");
[Link](vn);===========>true

String s="dhoni";
boolean vn=[Link]("ni");
[Link](vn);=========>true

String s="dhoni";
boolean vn=[Link]("ho");
[Link](vn);========>false

[Link]()

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

syntax

datatype varname=[Link](oldchar,newchar)

String s="roshan";
String res=[Link]('r','t');
[Link](res);==============>toshan

[Link]()

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

syntax

datatype varname=[Link](oldcharacters,newcharacters)

String s="roshan";
String res=[Link]("ros","tra");
[Link](res);============>trahan

[Link]()

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


String s="roshan";
String s2=[Link]();
[Link](s2);==========>ROSHAN

[Link]()

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

String s="RosHan";
String s2=[Link]();
[Link](s2);===============>roshan

[Link]()

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

syntax

datatype varname=[Link]();

String s="roshan";
int xyz=[Link]();
[Link](xyz);===========>-925204225

[Link]

[Link] is a predefine class.


[Link] purpose of StringBuffer is to store multiple characters enclosed with double quotes("").
[Link] value can be stored in 1 way.
[Link] using new Keyword.
StringBuffer s=new StringBuffer("virat kohli");===========>virat kohli
[Link](s);

StringBuffer s="virat";
[Link](s);==============>error

[Link] is mutable.
[Link] is synchronized.
[Link] is thread safe.

predefine methods in StringBuffer

[Link]()

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

syntax

datatype varname=[Link](string);

StringBuffer s=new StringBuffer("pawan");


StringBuffer s2=[Link]("kalyan");
[Link](s2);=======================>pawankalyan

String s="virat";
String s2=[Link]("kohli");
[Link](s2);========================>error

[Link]()

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

syntax

datatype varname=[Link](index,char);

StringBuffer s=new StringBuffer("Bhavadeesh");


StringBuffer s2=[Link](1,'a');
[Link](s2);==============>Bahavadeesh

[Link]()

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

syntax

datatype varname=[Link](startindex,endindex);
StringBuffer s=new StringBuffer("Bhavadeesh");
StringBuffer s2=[Link](1,4);
[Link](s2);=========>Badeesh

[Link]()

reverse() is used to reverse StringBuffer.

syntax

datatype varname=[Link]();
StringBuffer s=new StringBuffer("Bhavadeesh");
StringBuffer s2=[Link]();
[Link](s2);============>hseedavahB

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

String s="virat";
StringBuffer s2=new StringBuffer(s);
StringBuffer s3=[Link]();
[Link](s3);

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

String s="virat";
[Link]("kohli");
[Link](s);=================================>virat
[Link]("=========================");
StringBuffer s2=new StringBuffer("Mahesh");
[Link]("Babu");
[Link](s2);==============================>Mahesh Babu

String s="virat";
[Link]([Link]());=========================>112216210
String s2=[Link]("kohli");
[Link]([Link]());========================>-2089279825
[Link]("=====================");
StringBuffer s3=new StringBuffer("Rohit");
[Link]([Link]());========================>305808283

StringBuffer s6=new StringBuffer("sharma");


StringBuffer s4=[Link](s6);
[Link]([Link]());========================>305808283

[Link]

[Link] is a predefine class.


[Link] purpose of StringBuilder is to store multiple characters enclosed with double quotes("").
[Link] value can be stored in 1 way.
[Link] using new Keyword.
StringBuilder s=new StringBuilder("virat kohli");===========>virat kohli
[Link](s);

StringBuilder s="virat";
[Link](s);==============>error

[Link] is mutable.
[Link] is not synchronized.
[Link] is not thread safe.

[Link]

[Link] is a predefine class.


[Link] is present in [Link] package.
[Link] purpose of StringTokenizer is used to break or divide the String into tokens.
splitting the data based on delibiter.
[Link] predefine methods
[Link]()
[Link]()

[Link]()(condition)

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

[Link]()(output)

nextElement() is used to print the avialble element.

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


[Link]([Link]());
while([Link]())
{
[Link]([Link]());
}

import [Link].*;
class Demo
{
public static void main(String[] args)
{
StringTokenizer s=new StringTokenizer("vi_ra_ta","_");
[Link]([Link]());
while([Link]())
{
[Link]([Link]());
}
}
}

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

[Link](s);====================================>[Link]@5e265ba
4
}
}

programs on Strings

[Link] a java program to check 1st character is vowel or consonant in String.

String s="virat";
if(([Link](0)=='a')||([Link](0)=='e')||([Link](0)=='i')||
([Link](0)=='o')||([Link](0)=='u')||([Link](0)=='A')||
([Link](0)=='E')||([Link](0)=='I')||([Link](0)=='O')||
([Link](0)=='U'))
{
[Link]("vowel");
}
else
{
[Link]("Not vowel");
}

[Link] a java program to check each character of String is vowel or consonant.

String s="virat";
for(int i=0;i<[Link]();i++)
{
if(([Link](i)=='a')||([Link](i)=='e')||([Link](i)=='i')||
([Link](i)=='o')||([Link](i)=='u')||([Link](i)=='A')||
([Link](i)=='E')||([Link](i)=='I')||([Link](i)=='O')||
([Link](i)=='U'))
{
[Link]("vowel");
}
else
{
[Link]("consonant");
}
}

[Link] 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<[Link]();i++)
{
s2=s2+[Link](i);
}
[Link](s2);

[Link] a java program to reverse a String.

String s1="virat";
String s2="";
for(int i=[Link]()-1;i>=0;i--)
{
s2=s2+[Link](i);
}
[Link](s2);

[Link] a java program to convert 1 character of string into capital.


String s1="virat";
char ch=[Link](0);
int av=ch-32;
char cn=(char)av;
[Link](cn);

[Link] a java program to check string is palindrome or not.

String s1="madam";
String s2="";
for(int i=[Link]()-1;i>=0;i--)
{
s2=s2+[Link](i);
}
if([Link](s2))
{
[Link]("palindrome");
}
else
{
[Link]("Not palindrome");
}

[Link] a java program to check given Strings are anagram or not.


String s1="bhav";
String s2="vhab";
char[] c1=[Link]();
char[] c2=[Link]();
[Link](c1);
[Link](c2);
if([Link](c1,c2))
{
[Link]("Anagarm");
}
else
{
[Link]("Not Anagarm");
}

[Link] 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<[Link]();i++)
{
if(([Link](i)>='a' && [Link](i)<='z') ||([Link](i)>='A'&&
[Link](i)<='Z'))
{
alpha++;
}
else if([Link](i)>='0' && [Link](i)<='9' )
{
digit++;
}
else
{
symbol++;
}

}
[Link](alpha);
[Link](digit);
[Link](symbol);

[Link] a java program to print Ascii values for given string


String s="Bhavi";
for(int i=0;i<[Link]();i++)
{
char ch=[Link](i);
[Link](ch+":"+(int)(ch));
}

[Link] a java program to convert uppercase letters into lowercase in String.

String s="BhavI";
String res="";
for(int i=0;i<[Link]();i++)
{
char ch=[Link](i);
if(ch>='A' && ch<='Z')
{
res=res+(char)+(ch+32);
}
else
{
res=res+ch;
}
}
[Link](res);

[Link] a java program to print length of each word.

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


for(int i=0;i<[Link];i++)
{
String res=s[i];
[Link]([Link]());
}

[Link] a java program to reverse each word of String.

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


for(int i=0;i<[Link];i++)
{
String res=s[i];
for(int j=[Link]()-1;j>=0;j--)
{
[Link]([Link](j));
}
[Link]();
}

[Link] 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<[Link];i++)
{
if(s[i].length()>max)
{
max=s[i].length();
index=i;
}

}
[Link](s[index]);

[Link] a java program to remove spaces.

String s="virat is a king";


String res=[Link](" ","");
[Link](res);
String res1=[Link]("\\s","");
[Link](res1);

[Link] a java program to remove spaces without predefine methods.

String s="virat is a king";


String res="";
for(int i=0;i<[Link]();i++)
{
char ch=[Link](i);
if(ch!=' ')
{
res=res+ch;
}
else
{
res=res+[Link](i+1);
}
}
[Link](res);

[Link] 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<[Link]();i++)
{
char nc=[Link](i);
if(nc==ch)
{
count=count+1;
}
}
if(count>0)
{
[Link](ch+":"+count);
}
}

String s="aabbabcc";
int[] count=new int[256];
for(int i=0;i<[Link]();i++)
{
count[(int)[Link](i)]++;
}
for(int i=0;i<[Link];i++)
{
if(count[i]!=0)
{
[Link]((char)i+" : "+count[i]);
}
}

[Link] 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<[Link]();i++)
{
char nc=[Link](i);
if(nc==ch)
{
count=count+1;
}
}
if(count>1)
{
[Link](ch+":"+count);
}
}

[Link] 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<[Link]();i++)
{
char nc=[Link](i);
if(nc==ch)
{
count=count+1;
}
}
if(count==1)
{
[Link](ch+":"+count);
}
}

[Link] a java program to print characters in aplhabets order.


String s="bhavi";
int asc=96;
for(int i=0;i<[Link]();i++)
{
char ch=[Link](i);
int res=ch-asc;
[Link](ch+":"+res);
}

[Link] 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)
{
[Link](x+" "+y+" "+z);
}
}

}
}
}
}

[Link] a java program to check one string rotation is another String.


String os="aradhya";
String ks="radhyaa";
String ns=[Link](os);
if([Link](ks))
{
[Link]("Rotational string");
}
else
{
[Link]("Not Rotational string");

Scanner

[Link] is a predefine class.


[Link] purpose of Scanner is to take input from console(command prompt) and printing
output in command prompt.
[Link] is present in [Link] package.

Steps to take input from Scanner.

[Link] [Link] package


[Link] object for Scanner class.
[Link]-------->nextInt()
[Link]------>nextFloat()
[Link]----->nextDouble()
[Link]---->nextBoolean()
[Link]------->next().charAt(index)
[Link]----->[Link]()
[Link]()
import [Link];
class Demo
{
public static void main(String[] args)
{
Scanner sc=new Scanner([Link]);

int a=[Link]();
[Link]("output is"+a);============>output is 12
}
}

import [Link].*;
class Sample
{
public static void main(String[] args)
{
Scanner s1=new Scanner([Link]);
[Link]("enter float num=");
float num=[Link]();
[Link](num);
}
}

import [Link];
class Demo
{
public static void main(String[] args)
{
Scanner sc=new Scanner([Link]);
[Link]("enter num=");
int a=[Link]();
[Link]("output is"+a);
}
}

import [Link].*;
class Sample
{
public static void main(String[] args)
{
Scanner s1=new Scanner([Link]);
[Link]("enter double num=");
double num=[Link]();
[Link](num);
}
}

import [Link].*;
class Sample
{
public static void main(String[] args)
{
Scanner s1=new Scanner([Link]);
[Link]("enter boolean value=");
boolean b=[Link]();
[Link](b);
}
}

import [Link].*;
class Demo
{
public static void main(String[] args)
{
Scanner sc=new Scanner([Link]);
[Link]("enter char value=");
char ch=[Link]().charAt(0);
[Link](ch);
}
}

enter char value=


99
9

import [Link].*;
class Demo
{
public static void main(String[] args)
{
Scanner sc=new Scanner([Link]);
[Link]("enter string 1 word=");
String s=[Link]();
[Link](s);
}
}

enter string 1 word=


Ajay is java student
Ajay

enter string 1 word=


Ajay
Ajay

import [Link].*;
class Demo
{
public static void main(String[] args)
{
Scanner sc=new Scanner([Link]);
[Link]("enter string [Link] words=");
String s=[Link]();
[Link](s);
}
}

enter string [Link] words


Hemanth is a good boy
Hemanth is a good boy

Difference between next() and nextLine()


[Link]() is used to take only 1 word
[Link]() is used to take multiple words.
import [Link].*;
public class Demo
{

public static void main(String[] args)


{
Scanner sc=new Scanner([Link]);
[Link]("enter size=");
int size=[Link]();

int[] arr=new int[size];


[Link]("enter elements");
for(int i=0;i<[Link];i++)
{
arr[i]=[Link]();
}
[Link]([Link](arr));3

}
}

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

Methods

[Link] is collection of gruop of statements.


[Link] purpose of method is to perform task and produce code resuabiltity.

[Link] contains 3 parts


[Link] heading
[Link] body
[Link] calling

[Link] heading

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


[Link] body

Method body is a collection group of statements.

[Link] parameters

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

[Link] 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)
{
[Link](a);=======================================>8
}
public static void main(String[] args)
{
Sample s1=new Sample();
[Link](8);

}
}

Methods can define 4 ways.

[Link] formal parameters and without return statement


[Link] formal parameters and without return statement
[Link] formal parameters and with return statement
[Link] formal parameters and with return statement.

void======================>[Link]()
Datatype==================>return

[Link] formal parameters and without return statement

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

}
}

[Link] formal parameters and without return statement

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

}
}

class Sample
{

void add(int a,int b)


{
[Link](a+b);
}
public static void main(String[] args)
{
Sample s1=new Sample();
[Link](6,5);
}
}

[Link] 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=[Link](16);
[Link](res);
}
}

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

}
public static void main(String[] args)
{
Sample s1=new Sample();
float res=[Link](16.6f);
[Link](res);

}
}

[Link] 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=[Link]();
[Link](s);
}
}

import [Link].*;
class Sample
{

void add(int[] a)
{
[Link]([Link](a));

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

}
}
steps to install jdk

[Link] to google and type java oracle india.


[Link]====>64 bit download===>yes===>next===>next===>close
[Link] pc====>c folder===>program files===>java===>jdk 20==>copy path
[Link] bar==>edit environmental variables for your account==>path==>new==>paste path==>move up

class Demo
{
public static void main(String[] args)
{
[Link]("welcome to java");
}

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

C:\Users\heman>cd /

C:\>cd Durga6pm

C:\Durga6pm>javac [Link]

C:\Durga6pm>java Demo
welcome to java

command line arguments

[Link] arguments which will take at command prompt are called command line arguments.
[Link] will take the arguments based on index value.
[Link] default arguments will store on String format.

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

}
}

C:\Durga6pm>javac [Link]
C:\Durga6pm>java First Taj Mahal
TajMahal

class First
{
public static void main(String[] args)
{
int a=[Link](args[0]);
int b=[Link](args[1]);
[Link](a+b);

}
}

C:\Durga6pm>javac [Link]

C:\Durga6pm>java First 3 4
7

C:\Durga6pm>javac [Link]

C:\Durga6pm>java First virat 2


Exception in thread "main" [Link]: 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)
{
[Link](a);
}
public static void main(String[] args)
{
First f1=new First();
[Link](5,6,7);===================>error(expecting only 1 actual argument)
}
}

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

C:\Durga6pm>javac [Link]

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

import [Link].*;
class First

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

C:\Durga6pm>javac [Link]

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

import [Link].*;
class First

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

C:\Durga6pm>javac [Link]

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

import [Link].*;
class First

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

Error because variable llength argument must be last parameter.

Java features

Java features are services or facilities.

[Link] programming language.


[Link] independent programming language.
[Link] typed programming language.
[Link] programming language.
[Link] programming language.
[Link] programming language.
[Link] functional and object oriend programming language.
[Link] programming language.
[Link] programming language.
[Link] programming language.

[Link] programming language.

[Link] is a simple programming language because it contains predefine methods.


[Link] removed complicated topic like pointers.
[Link] contains simple syntax and easy to understand.

[Link] methods

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

Examples

[Link]()
[Link]()
[Link]()
[Link]()

[Link] methods
The methods which are not present in java software(jdk).These methods are developed by
java programmers.

Examples

[Link]()
[Link]()
[Link]()
[Link]()

class Demo
{
public static void main(String[] args)
{
[Link]([Link](49));===================>7.0
[Link]([Link](81));===================>9.0
[Link]([Link](2,3));===================>8.0
}
}

[Link] independent programming language.

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

Examples

[Link]
[Link]

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++

[Link] 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

[Link] 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)


[Link](a);==========>10 normal data (Humans)

[Link] programming language.

A language will takes place with both compilation and execution.

Difference between compiler and interpreter.

compiler

[Link] will converts source code into intermediate code or byte code all at a time

Interpreter

[Link] will execute line by line byte code .


[Link] is present in jvm.

jdk

[Link] stands for java development kit


[Link] jdk both compilation and execution will occurs(develop and run===>developers)
[Link] contains jre,jvm

jre

[Link] stands for java runtime environment.


[Link] jre only execution will occurs(run==>endusers/testers)
[Link] contains jvm.

jvm

[Link] stands for java vitual machine.


[Link] contains interpreter.
[Link] purpose of jvm is to execute line by line byte code or intermediate code.

[Link] programming language

[Link] means strong.


[Link] is robust programming language because strongly typed,Garbage collector and Exception Handling.

[Link] typed
-----------------
Compiler will check each and every declaration and assignments at compile time.

Ex
--
int a="virat kohli";

javac [Link]====>compile time error string data cannot store in int

[Link] Collector
--------------------
The purpose of Garbage collector removes unwanted memory and improves system performance.

[Link] Handling
--------------------
The purpose of Exception Handling is to convert abnormal termination into normal termination.

[Link] 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.

[Link] 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

[Link] programming language.

[Link] provides predefines rich API for Multithreading.


[Link]
[Link]
[Link] using multithreading we can exeutes multiple thread at a time simultaneously,so the application performance
improved and execution can be fastly.

[Link] Programming language

In java [Link] 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
{
[Link]("student class loaded");
}
}

class Test
{
static
{
[Link]("Test class loaded");
}

public static void main(String[] args)


{
[Link]("Hello");

}
}

javac [Link]

java Test
Test class loaded
Hello

class Student
{
static
{
[Link]("student class loaded");
}
}

class Test
{
static
{
[Link]("Test class loaded");
}

public static void main(String[] args)


{
[Link]("Hello");
Student s1=new Student();

}
}

javac [Link]

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 [Link] are

[Link] Literals==================>1,2,3...0,-1,-2....
[Link] point literals===========>1.2,1.6,1.8........
[Link] Literals================>'a','b','c',.......
[Link] Literals==================>true,false
[Link] Literals==================>"virat","dhoni".......
[Link] Literals=================>Null

int a =12;

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

Oops

[Link] standards for object oriented programming system.


[Link] is not a technology.
[Link] is a techniuque or methodlogy.
[Link] contains 4 principles
[Link]
[Link]
[Link]
[Link]
[Link] 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

[Link] is a nonprimitive/refernce datatype.


[Link] 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

[Link] is a instance of class.


[Link] is allocating memory address to the instance variables.
variables

1.A variable is a container.


[Link] purpose of variable is to stote operand(value,variable,expression).
[Link] are 3 types of [Link] are
[Link]/non static variables
[Link] variables
[Link] variables
[Link] is no gloabal variables in java.

[Link]/non static variables

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

object

[Link] contains data.


[Link] object to access instance variables for 1 time.

object refernce

[Link] contains Hashcode.


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

[Link] variable

1.A variable that is defined outside of a method and with static keyword is called static variable.
[Link] variables stored method area.
[Link] variables can be accessed in 4 ways.
[Link] using object
[Link] using object refernce
[Link] using directly.
[Link] using class name
[Link] varibles have default values.
[Link] 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.

[Link] varibles

1.A varible that is defined inside of a method without static keyword is called Local variable.
[Link] parameters are local variables.
[Link] variables stored in stack area.
[Link] varibles are accessed in 1 way.
[Link] using directly.
[Link] is no default values for local variables.
[Link] varibles must be initialize.
[Link] 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();
[Link](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

[Link] is dynamic memory allocator.


[Link] 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();
[Link](s1.a);

}
}

class Student
{
int a=12;

public static void main(String[] args)


{
[Link] (new Student().a);
}
}

class Emp
{
String s="virat";
public static void main(String[] args)
{
Emp e1=new Emp();
[Link](e1.s);
[Link](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();
[Link](e1.s);
[Link](e1.a);
[Link](e1.b);
[Link](e1.c);
[Link](e1.d);

}
}

output

0
null
false
.
o.o

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

}
}

class Emp
{

public static void main(String[] args)


{
int a=12;
[Link](a);

}
}

class Emp
{

public static void main(String[] args)


{
int a;
[Link](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;
[Link](sno+" "+sname+" "+mobile+" "+iname);
}
public static void main(String[] args)
{
StudentInfo s1=new StudentInfo();
[Link](1,"Hemanth",88888);
[Link](2,"Parithosh",88871);
[Link](3,"Ajay",88123);

}
}

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

Methods

[Link] is a collection of group of statemnts.


[Link] purpose of methods is to perform task and produce code resuability.
[Link] are 2 types of [Link] are
[Link] methods.
[Link] methods.

[Link] methods

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

}
}

[Link] methods

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

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

}
}

Blocks

[Link] is collection of group of statments({}).


[Link] are 2 types of blocks.
[Link] blocks.
[Link] blocks.

[Link] blocks.

1.A block which is defined without static keyword.


[Link] blocks can execute when create object or object refernce

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

[Link] blocks.

1.A block which is defined with static keyword.


[Link] blocks can execute whenever class will load.

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


{
static
{
[Link]("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()
{
[Link]("instance method");=========>instance method 6
}
static void m2()
{
[Link]("static method");==============>static method 3
}
{
[Link]("instance block");===========>instance block 4

}
static {
[Link]("static block");=========>static block 1

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

}
}
Inheritance

[Link] process of creating new class of existing class by using extends keyword is called Inheritance.
[Link] class is a super class
[Link] class is a sub class.
[Link] we create object for super class we can access only super class variables or methods.
[Link] we create object for sub class we can access both super and sub class variables and methods.
[Link] purpose of Inheritance is to reuse features(variables and methods) from super class to sub class.
[Link] are 6 types of [Link] are
[Link] Inheritance
[Link] Inheritance
[Link] Inheritance
[Link] Inheritance
[Link] Inheritance
[Link] Inheritance

[Link] Inheritance

1 sub class is derived 1 super class.

[Link] 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

[Link] Inheritance

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

[Link] Inheritance

Multiple sub classes are derived from 1 super class.

[Link] 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

[Link] 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();


[Link]([Link]);===============>600
[Link]([Link]);===============>500
Chiranjeevi c1=new Chiranjeevi();
[Link]([Link]);===============>500
[Link]([Link]);===============>error

}
}
class Vehicle
{
String s="engine";
}
class Car extends Vehicle
{
int price=2000;
public static void main(String[] args)
{
Vehicle v=new Vehicle();
[Link](v.s);===============>engine
Car c=new Car();
[Link]([Link]);===========>2000
[Link](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();
[Link](v.s);
Car c1=new Car();
[Link]([Link]);
[Link](c1.s);
Nexon n=new Nexon();
[Link](n.s);
[Link]([Link]);
[Link]([Link]);

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();
[Link](v.s);
Car c1=new Car();
[Link]([Link]);
[Link](c1.s);
Bike b1=new Bike();
[Link]([Link]);
[Link](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

[Link] is an object refernce or refernce variable.


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

class A
{
int a=7;============>Instance variable
void m1()
{
int x=9;=========>Local variable
[Link](x);============================>9
[Link](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
[Link](a);===============>16
[Link](this.a);==========>12
}
public static void main(String[] args)
{
A a1=new A();
[Link]();

}
}

class A
{
void show()
{
[Link]("show method");
}
void display()
{
[Link]();
[Link]("display method");
}
public static void main(String[] args)
{
A a1=new A();
[Link]();

}
}

class A
{
void show()
{
[Link]("show method");
[Link]();
}
void display()
{

[Link]("display method");
}
public static void main(String[] args)
{
A a1=new A();
[Link]();

}
}

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

}
}

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

}
}

super

[Link] is object refernce or reference variable.


[Link] 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()
{
[Link](b);================>9
[Link](a);================>6
}
public static void main(String[] args)
{
B b1=new B();
[Link]();
}
}

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

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

class A
{
void mahesh()
{
[Link]("Mahesh in super class");
}
}
class B extends A
{
void pawan()
{
[Link]("pawn in sub class");

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

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

}
}

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

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

Modifiers
[Link] are keywords.
[Link] are used to give accessbility and modifies the behaviour of variables,methods
and class.
[Link] are divided into 2 [Link] are
[Link] Modifiers
[Link] Access Modifiers.

[Link] Modifiers

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


There are 4 types of Access [Link] are
[Link]=========>Any where
[Link]======>package and sub class of another package
[Link]========>package
[Link]==========>class

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

[Link]==========>public
[Link]=======>public,protected
[Link]=========>public,protected,default
[Link]=========>No

class A
{
String s="Rajamouli";
}
class B extends A
{
String s2="Maniratnam";
public static void main(String[] args)
{
B b1=new B();
[Link](b1.s2);===========>Maniratname
[Link](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();
[Link](b1.s2);
[Link](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();

[Link](b1.s);====================>Error
}

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

[Link](b1.s2);===================>Maniratnam
}

class A
{
void m1()
{
[Link]("m1 in A");
}
}
class B extends A
{
void m2()
{
[Link]("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()
{
[Link]("m1 in A");
}
}
class B extends A
{
void m2()
{
[Link]("m2 in B");
}
public static void main(String[] args)
{
B b1=new B();
b1.m1();============>error
b1.m2();
}
}

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

class A
{
public void m1()
{
[Link]("m1 in A");
}
}
class B extends A
{
void m2()
{
[Link]("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()
{
[Link]("m1 in A");
}
}
class B extends A
{
void m2()
{
[Link]("m2 in B");
}
public static void main(String[] args)
{
B b1=new B();
b1.m1();=============================>m1 in A
}
}

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

Constructors

[Link] is a one type of special method.


[Link] name and class Name must be same and with no return type including void.
[Link] will execute whenever we create an object.
[Link] purpose of constructors is to initilize instance variables.
[Link] are 3 types of [Link] are
[Link]/Non parameterized constructor.
[Link] Constructor
[Link] Constructor.

[Link]/Non parameterized constructor.


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

[Link] Constructors
----------------------------
The constructor with formal parameters is called parameterized constructors.

[Link] Constructor.
--------------------
The process of copying 1 object refernce or refernce variable into another Onject refernce or
reference variable.

[Link] there is no constructor jvm will provide 1 default constructor.


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

[Link] chaining

[Link] process of calling one constructor to another constructor is called constructor chaining.
[Link] chaining can be possible by this(),super().
[Link]() and super() must be written in first statement.
[Link]() is implicitly present in every class but not this().

[Link]()
---------
this() will call default constructor in current class.

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

[Link]()
---------
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

[Link] purpose of methods is to perform task and produce code resuability.


[Link] will be return type in methods.
[Link] name and class name must not be same.
[Link] will execute whenever we call method.
[Link] arguments is passed in method calling in methods.
[Link] overriding is possible in methods.
[Link] is possible in methods.
[Link]() and super() is not present in methods.

Constructors

[Link] purpose of constructors is to iniatilize instance varaibles.


[Link] will be no return type in constructors.
[Link] name and class name must be same.
[Link] will execute whenever we create object.
[Link] arguments is passed in object creation in constructors.
[Link] ovverriding is not possible in constructors.
[Link] is not possible in constructors.
[Link]() and super() is present in constructors.

class Demo
{
Demo()
{
[Link]("welcome to constructors");==============>Welcome to constructors

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

}
}

class Demo
{
Demo(int a)
{
[Link](a+" parameterized constructors");=========>6 parameterized constructors

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

}
}

class Demo
{
Demo(int a,int b)
{
[Link](" parameterized constructors");==>parameterized constructors
[Link](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;
[Link](a+" "+b);

}
Demo(Demo ref)
{
a=ref.a;
b=ref.b;
[Link](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";
[Link](sno+" "+sname);===========>123 Hemanth

}
Student(Student s3)
{
sno=[Link];
sname=[Link];
[Link](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()
{
[Link](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()
{
[Link](eno+" "+ename);
}
public static void main(String[] args)
{
Emp e1=new Emp(12,"Mohan");
[Link]();

}
}

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
{
[Link](sno+" "+sname);
}
public static void main(String[] args)==================>2 main method call
{
Student s1=new Student(4,"Bhavadeesh");=====>Object refernce==>3
[Link]();===============================>method calling

}
}

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


{
int ino;
String iname;
Institute(int ino,String iname)========>4
{
[Link]=ino;==============>5
[Link]=iname;=========>6
}
void show()================================>8
{
[Link](ino+" "+iname);===========>9 567 Durga
}
public static void main(String[] args)======================>2 main method call
{
Institute i1=new Institute(567,"Durga");===============> 3 object created
[Link]();=============================================>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()
{
[Link]("default con");
}
Demo(int x)
{
[Link]("parameterized con");
}
Demo(int x,String y)
{
[Link](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
{
[Link]("defalut con in super class");
}
}
class B extends A=============>sub class
{
B(int x)=================>parameterized constructor
{
[Link]("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()
{
[Link]("defalut con");
}
B(int x)
{
this();

[Link]("parameterized con");
}
public static void main(String[] args)
{
B b1=new B(7);
}
}

Defalut con
parameterized con

class B
{
B()
{
this(5);
[Link]("defalut con");
}
B(int x)
{

[Link]("parameterized con");
}

public static void main(String[] args)


{
B b1=new B();
}
}

parameterized con
defalut con

class B
{
B()
{

[Link]("defalut con");
this(5);=============================>error
}
B(int x)
{

[Link]("parameterized con");
}

public static void main(String[] args)


{
B b1=new B();
}
}

class A
{
A()
{
[Link]("default con in super class");
}
}
class B extends A
{
B(int x)
{
super();
[Link]("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)
{
[Link]("param con in super class");
}
}
class B extends A
{
B()
{
super(6);
[Link]("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()
{
[Link]("default con in super class");
}
}
class B extends A
{
B(int x)
{

[Link]("parameterized con in sub class");


}
public static void main(String[] args)
{
B b1=new B(7);
}
}
class A
{
A()
{
[Link]("default con in super class");
}
}
class B extends A
{
B(int x)
{
super();

[Link]("parameterized con in sub class");


}
B()
{
this(6);

[Link]("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()
{
[Link]("default con in super class");
}
}
class B extends A
{
B(int x)
{
this();
[Link]("parameterized con in sub class");
}
B()
{

[Link]("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

[Link] means many and morphism means forms.(polymorphism===========>many forms)


[Link] ability to have more than 1 form is called polymorphism.
[Link] are 2 types of [Link] are
[Link]/static polymorphism.
[Link]/dynamic polymorphism.

[Link]/static polymorphism.

The process of binding method heading with method calling at compile time is called compile
time polymorphism.

Ex

[Link],method hiding

[Link]/dynamic polymorphism.

The process of binding method heading with method calling at run time is called runtime
time polymorphism.

Ex

[Link]

[Link] overloading

[Link] process of 2 or more methods name should be same and different formal paramter list.
[Link] parameter list
[Link] Formal parameters
[Link] in order
[Link] in datatype
[Link] overloading is possible in 1 class and multiple classes.
[Link] is not required for method overloading (but possible in Inheritance also).
[Link] methods can be overloaded.
[Link] methods can be overloaded.
[Link] methods can be overloaded.

[Link] overriding

[Link] process of 2 or more methods name should be same and same formal paramter list.
[Link] overriding is not possible in 1class atleast 2 classes is required.
[Link] overriding can be implemented by using inheritance concept.
[Link] 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).

[Link] methods cannot be override because we cannot inherit 1 method of 1 class into another
class.
[Link] methods cannot be ovverride because the purpose of final is to prevent inheritance.

class A
{
void add(int a)
{
[Link]("welcome to java");
}
void add(float b)
{
[Link]("welcome to python");
}
public static void main(String[] args)
{
A a1=new A();
[Link](12);========================================>welcome to java

}
}

class A
{
void add(int a)
{
[Link]("welcome to java");
}
void add(float b)
{
[Link]("welcome to python");
}
public static void main(String[] args)
{
A a1=new A();
[Link](12.6f);===================================>welcome to python

}
}
class A
{
void add(int a)=================================>method 1
{
[Link]("welcome to java");
}
void add(float b)=================================>method 2
{
[Link]("welcome to python");
}
public static void main(String[] args)
{
A a1=new A();
[Link]("mahesh");======================>error

}
}

class A
{
void add(int a,int b)
{
[Link]("welcome to java");
}
void add(int c)
{
[Link]("welcome to python");
}
public static void main(String[] args)
{
A a1=new A();
[Link](1,7);==========================>welcome to java

}
}

class A
{
void add(int a,float b)
{
[Link]("welcome to java");
}
void add(float a,int b)
{
[Link]("welcome to python");
}
void add(int a)
{
[Link]("welcome to c");
}

public static void main(String[] args)


{
A a1=new A();
[Link](6.7f,7);=====================================>welcome to python

}
}
class A
{
void add()
{
[Link]("Virat Kohli");
}

void add()
{
[Link]("Sachin Tendulkar");
}
public static void main(String[] args)
{
A a1=new A();
[Link]();==========================>error because(method overriding is not
possible in 1 class)
}

class A
{
void add()
{
[Link]("Virat kohli");
}

}
class B extends A
{
void add()
{
[Link]("Sachin Tendulkar");
}
public static void main(String[] args)
{
B b1=new B();
[Link]();==========================================>scahin Tendulakar
}

class A
{
void add()
{
[Link]("Virat kohli");
}

}
class B extends A
{
void add()
{
[Link]("Sachin Tendulkar");
}
public static void main(String[] args)
{
A a1=new A();
[Link]();================================>virat kohli

}
}
class B
{
static void m1()
{
[Link]("chicken");
}
void m1(int a)
{
[Link]("mushroom");
}

public static void main(String[] args)


{
B b1=new B();
b1.m1(56);===========================>mushroom
}
}

class A
{
final void display()
{
[Link]("Display in A");
}
}
class B extends A
{
void display()
{
[Link]("Display in B");
}
public static void main(String[] args)
{
A a1=new A();
[Link]();=====================================>error
}
}

class A
{
private void display()
{
[Link]("Display in A");
}
}
class B extends A
{
void display()
{
[Link]("Display in B");
}
public static void main(String[] args)
{
A a1=new A();
[Link]();================================>error
}
}

class A
{
static void display()
{
[Link]("Display in A");
}
}
class B extends A
{
void display()
{
[Link]("Display in B");
}
public static void main(String[] args)
{
A a1=new A();
[Link]();==================================>error
}
}

class B
{
final void display(int a)
{
[Link]("Display in virat");
}
void display()
{
[Link]("Display in B");
}
public static void main(String[] args)
{
B b1=new B();
[Link]();========================>Display in B
}
}

class B
{
private void display(int a)
{
[Link]("Display in virat");
}
void display()
{
[Link]("Display in B");
}
public static void main(String[] args)
{
B b1=new B();
[Link]();========================>Display in B
}
}
class B
{
static void display(int a)
{
[Link]("Display in virat");
}
void display()
{
[Link]("Display in B");
}
public static void main(String[] args)
{
B b1=new B();
[Link]();========================>Display in B
}
}

class Calculator
{
void add(int a,int b)
{
[Link](a+b);
}
void add(int a,int b,int c)
{
[Link](a+b+c);
}
void add(int a,int b,int c,int d)
{
[Link](a+b+c+d);
}
public static void main(String[] args)
{
Calculator c1=new Calculator();
[Link](6,8,9);
}
}

class Sbi
{
void phonePay(int am)
{
[Link](am);
}
}
class PunjabBank extends Sbi
{
void phonePay(int am)
{
[Link](am);
}
public static void main(String[] args)
{
Sbi ajay=new Sbi();
[Link](500);
PunjabBank pari=new PunjabBank();
[Link](700);
}
}

class Anand
{
void love()
{
[Link]("vaishnavi loves Anand");
}
}
class Viraj extends Anand
{
void love()
{
[Link]("vaishnavi loves viraj");
}
public static void main(String[] args)
{
Viraj vaishu=new Viraj();
[Link]();
}

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;
[Link](a);===================>12

final String s="pawan";


[Link](s);===============>pawan

final String s="pawan";


s="kalyan";
[Link](s);==============>error

class B
{
void show()
{
[Link]("show in B");
}
}
class A extends B
{
void show()
{
[Link]("show in A");
}
public static void main(String[] args)
{
B b1=new B();
[Link]();=========================>show in B

}
}

class B
{
final void show()
{
[Link]("show in B");
}
}
class A extends B
{
void show()
{
[Link]("show in A");
}
public static void main(String[] args)
{
B b1=new B();
[Link]();==========================>error

}
}

final class B
{
void show()
{
[Link]("show in B");
}
}
class A extends B===========================>error
{
void display()
{
[Link]("display in A");
}
public static void main(String[] args)
{
B b1=new B();
[Link]();

}
}

class B
{
void show()
{
[Link]("show in B");
}
}
class A extends B
{
void display()
{
[Link]("display in A");
}
public static void main(String[] args)
{
B b1=new B();
[Link]();====================================>show in B

}
}

final int a;
[Link](a);=============>error

upcasting

[Link] process of assigning object or object refernce of sub class to super class.
[Link] done by system implicitly.
[Link] always valid

class A
{
void m1()
{
[Link]("m1 in A");
}
}
class B extends A
{
void m2()
{
[Link]("m2 in B");
}
}
class C extends B
{
void m3()
{
[Link]("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()
{
[Link]("m1 in A");
}
}
class B extends A
{
void m2()
{
[Link]("m2 in B");
}
}
class C extends B
{
void m3()
{
[Link]("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()
{
[Link]("engine in vehicle");
}
}
class Car extends Vehicle
{
void tyres()
{
[Link]("4 tyres in car");
}
}
class Punch extends Car
{
void price()
{
[Link]("10 lakhs punch");
}
}
class Demo
{
public static void main (String[] args)
{
Vehicle v1=new Car();
[Link]();=================>engine in Vehicle
[Link]();==================>error
[Link]();==================>error
Car c1=new Punch();
[Link]();=================>engine in vehicle
[Link]();==================>4 tyres in Car
[Link]();==================>error
Vehicle v2=new Punch();
[Link]();=================>engine in Vehicle
[Link]();==================>error
[Link]();==================>error

Vehicle v3=c1;
[Link]();==================>engine in Vehicle
[Link]();==================>error
[Link]();==================>error

}
}

downcasting

[Link] process of assigning object or object refernce of super class to sub class.
[Link] can be done by programmer explicitly.
[Link] always required upcasting.

class Vehicle
{
void engine()
{
[Link]("engine in vehicle");
}
}
class Car extends Vehicle
{
void tyres()
{
[Link]("4 tyres in car");
}
}
class Punch extends Car
{
void price()
{
[Link]("10 lakhs punch");
}
}
class Demo
{
public static void main (String[] args)
{
Vehicle v1=new Car();
Car c1=(Car)v1;
[Link]();
[Link]();

Car c2=new Punch();


Punch p1=(Punch)c2;
[Link]();
[Link]();
[Link]();

}
}

Object class

[Link] is a predefine class.


[Link] class is a super class for all classes directly or indirectly.
[Link] class is present in [Link] package.
[Link] class contains 11 methods.

[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link](long ms)
[Link](long ms,int s)
[Link]()
[Link]()

[Link]()

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();
[Link](d1);============>Demo@372f7a8d
}
}

Demo@372f7a8d

className@hexdecimaldata

getClass().getName().toHexString().hashCode()

class Demo
{
public static void main(String[] args)
{
Demo d1=new Demo();
[Link](d1);============>Demo@372f7a8d

[Link]([Link]());============>Demo@372f7a8d

}
}

class Demo
{
public static void main(String[] args)
{
[Link]("Happy Friday");=============>Happy Friday
}
}

import [Link].*;
class Demo extends Object
{
public static void main(String[] args)
{
[Link]("Happy Friday");=============>Happy Friday
}
}

class Demo
{
public String toString()
{
return "welcome to java";
}
public static void main(String[] args)
{
Demo d1=new Demo();
[Link](d1);===============>welcome to java
[Link]([Link]());=====>welcome to java
}
}

class Demo
{
int sno;
String sname;
Demo(int sno,String sname)
{
[Link]=sno;
[Link]=sname;
}
public static void main(String[] args)
{
Demo d1=new Demo(7,"Dhoni");
[Link](d1);=========>Demo@372f7a8d===>toString representation
}
}

class Demo
{
int sno;
String sname;
Demo(int sno,String sname)
{
[Link]=sno;
[Link]=sname;
}
public String toString()
{
return sno+" "+sname;
}
public static void main(String[] args)
{
Demo d1=new Demo(7,"Dhoni");
[Link](d1); =========>7 Dhoni
}

class Demo
{ public static void main(String[] args)
{
Demo d1=new Demo();
[Link](d1);
[Link]([Link]());
int hs=[Link]();
[Link](hs);
}
}
Demo@372f7a8d
Demo@372f7a8d
925858445

Relationships

There are 2 types of [Link] are


[Link] a relationship====>Inheritance==>extends
[Link] a relationship===>Association==>no extends

[Link] is a relationship there is a relation between classes.


[Link] purpose of is a relationship is to reuse all the features of one class to another class.
[Link] Has a relationship there is a relation between objects.
[Link] purpose of Has a relationship is to reuse required the features of one class to another class.

Association is divided into 2 [Link] are


[Link]
-------------
[Link] container object(Bharath University) destroy and automatically contained objects(Depts)
is going to destroy.
[Link] object(Bharath University) is strongly associated with contained objects(Depts)
[Link]
[Link] container object(ECE DEPT) destroy and may or may not be contained objects(Proffesors)
is not going to destroy.
[Link] 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()
{
[Link]("sno"+sno+" "+"sname"+sname+" "+"hands"+hands+" "+"legs"+legs);
}
public static void main(String[] args)
{
Student s1=new Student();
[Link]();

}
}
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()
{
[Link](speed+" "+color+" "+dukeprice);
}
public static void main(String[] args)
{
Duke d1=new Duke();
[Link]();
}

Duke is a Bike

120 Black 1000

class Engine
{
void start()
{
[Link]("Bike started");
}
void stop()
{
[Link]("Bike stopped");
}

}
class Bike
{
Engine e1=new Engine();
void work()
{
[Link]();
[Link]("Bike is running......");
[Link]();
}
public static void main(String[] args)
{
Bike b1=new Bike();
[Link]();
}
}

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()
{
[Link](ename+" "+[Link]+" "+[Link]);
}
public static void main(String[] args)
{
Emp e1=new Emp();
[Link]();
}
}
Emp has a Address

Hemanth 12 mythrivanam

Encapsulation

[Link] process of binding/wrapping/grouping/combining variables and methods into single class is


called encapsulation.
[Link] 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.
[Link] purpose of getter methods is to get values.

[Link] purpose of setter methods is to set values.


[Link]:Declare variables as private and methods as public.

class Demo
{
int no=12;
String name="parithosh";
void display()
{
[Link](no+" "+name);
}
public static void main(String[] args)
{
Demo d1=new Demo();
[Link]();
}
}

class Student
{
int sno;
String sname;
String dname;
}

}
class Teacher
{
public static void main(String[] args)
{
Student s1=new Student();
[Link]=123;
[Link]="Mohan";
[Link]="ECE";
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
}
}

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();
[Link]=123;
[Link]="Mohan";
[Link]="ECE";
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
}
}

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)
{
[Link]=sno;
}
public void setSname(String sname)
{
[Link]=sname;
}
public void setDname(String dname)
{
[Link]=dname;
}
public void getSno()
{
[Link](sno);
}
public void getSname()
{
[Link](sname);

}
public void getDname()
{
[Link](dname);

}
class Teacher
{
public static void main(String[] args)
{
Student s1=new Student();
[Link](334);
[Link]("AjayKumar");
[Link]("ECE");
[Link]();
[Link]();
[Link]();

output

334
AjayKumar
ECE

class Student
{
private int sno;
private String sname;
private String dname;
public void setSno(int sno)
{
[Link]=sno;
}
public void setSname(String sname)
{
[Link]=sname;
}
public void setDname(String dname)
{
[Link]=dname;
}
public void getSno()
{
[Link](sno);
}
public void getSname()
{
[Link](sname);

}
public void getDname()
{
[Link](dname);

}
class Teacher
{
public static void main(String[] args)
{
Student s1=new Student();
[Link](-87);
[Link]("AjayKumar");
[Link]("ECE");
[Link]();
[Link]();
[Link]();

output

-87
AjayKumar
ECE

class Student
{
private int sno;
private String sname;
private String dname;
public void setSno(int sno)
{
[Link]=sno;
}
public void setSname(String sname)
{
[Link]=sname;
}
public void setDname(String dname)
{
[Link]=dname;
}
public void getSno()
{
if(sno>0)
{
[Link]("valid"+sno);
}
else
{
[Link]("Invalid donot use ultra pro knowledge");

}
}
public void getSname()
{
[Link](sname);

}
public void getDname()
{
[Link](dname);

}
class Teacher
{
public static void main(String[] args)
{
Student s1=new Student();
[Link](-87);
[Link]("AjayKumar");
[Link]("ECE");
[Link]();
[Link]();
[Link]();

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)
{
[Link]=sno;
}
public void setSname(String sname)
{
[Link]=sname;
}
public void setDname(String dname)
{
[Link]=dname;
}
public void getSno()
{
if(sno>0)
{
[Link]("valid"+sno);
}
else
{
[Link]("Invalid donot use ultra pro knowledge");

}
}
public void getSname()
{
[Link](sname);

}
public void getDname()
{
[Link](dname);

}
class Teacher
{
public static void main(String[] args)
{
Student s1=new Student();
[Link](97);
[Link]("AjayKumar");
[Link]("ECE");
[Link]();
[Link]();
[Link]();

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()
{
[Link]("m1 in imple");
}
public void m2()
{
[Link]("m2 in imple");
}
public void m3()
{
[Link]("m3 in imple");
}
public void m4()
{
[Link]("m4 in imple");
}
public void m5()
{
[Link]("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()
{
[Link]("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()
{
[Link]("Telugu =92");
[Link]("Hindi =94");
[Link]("English =92");
[Link]("Maths =99");
[Link]("Physics =93");
[Link]("Chemistry =94");
}
public static void main(String[] args)
{
Test t1=new Test();
[Link]();
}

output

Telugu =92
Hindi =94
English =92
Maths =99
Physics =93
Chemistry =94
enum(Enumuration)

[Link] is our own datatype


[Link] enum will behave like class.
[Link] purpose of enum is to store constant values(fixed universal values).
[Link] enum by default public static final is provided to the constants.
[Link] can be accessed by using enum name.
[Link] byitself an object.
[Link] can be declare inside class and outside class.
[Link] method allowed in inside enum and outside enum.
[Link]()

The purpose of values() is to list out the total number of constansts in enum.
[Link]()

The purpose of ordinal() is to give ordinal value from 0 to length-1 to the enum constants.

[Link] is ordinal based ordinal starts from 0 and ends with length-1.
[Link] allows variables,methods,constructors.

enum Week
{
Sun,Mon,Tue,Wed,Thu,Fri,Sat
}
class Test
{
public static void main(String[] args)
{
Week w1=[Link];
[Link](w1);
Week w2=[Link];
[Link](w2);
Week w3=[Link];
[Link](w3);
Week w4=[Link];
[Link](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=[Link];
[Link](w1);
Week w2=[Link];
[Link](w2);
Week w3=[Link];
[Link](w3);
Week w4=[Link];
[Link](w4);

}
}

output

Sun
Mon
Tue
Wed

enum Directions
{
East,West,North,South;
public static void main(String[] args)
{
Directions d1=[Link];
[Link](d1);
Directions d2=[Link];
[Link](d2);
Directions d3=[Link];
[Link](d3);
Directions d4=[Link];
[Link](d4);

}
}

enum Directions
{
East,West,North,South;
public static void main(String[] args)
{
Directions[] d1=[Link]();
for(Directions d2:d1)
{
[Link](d2+"......"+[Link]());
}

}
}

output
East......0
West......1
North......2
South......3

enum Directions
{
East,West,North,South;
Directions()
{
[Link]("constructor");
}
public static void main(String[] args)
{
Directions d1=[Link];
}
}

output

constructor
constructor
constructor
constructor

enum Beer
{
kf(100),Bw(70),Ko(85);
int getPrice;
Beer(int getPrice)
{
[Link]=getPrice;
}

int getRates()
{
return getPrice;
}

}
class Test
{
public static void main(String[] args)
{
Beer[] b1=[Link]();
for(Beer b2:b1)
{
[Link](b2+"....."+[Link]());
}

}
}

output

kf.....100
Bw.....70
Ko.....85
enum Beer
{
kf(100),Bw(70),Ko(85),BB;
int getPrice;
Beer(int getPrice)
{
[Link]=getPrice;
}
Beer()
{
getPrice=200;

int getRates()
{
return getPrice;
}

}
class Test
{
public static void main(String[] args)
{
Beer[] b1=[Link]();
for(Beer b2:b1)
{
[Link](b2+"....."+[Link]());
}

}
}

output

kf.....100
Bw.....70
Ko.....85
BB.....200

Annotations

[Link] are used to give errors and information in compilation.


[Link] are begin with @ symbol.
[Link] are applied to variables,methods,constructors,class,interfaces.......
[Link] are divided into 2 [Link] are
[Link]/standard annotations
[Link]/custom annotations

[Link]/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 [Link] are
[Link] purpose annotations.
[Link] annotations.
[Link] purpose annotations.

General purpose annotations will give information to the compiler.


General purpose annotations are present in [Link] package
Ex
--
@override
@Depricated
@FunctionalInterface
@SuppressWarnings

[Link] Annotations

Meta annotations give information about general purpose annotations.


Meta annotations are present in [Link] 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)
[Link]====>class

[Link]====>Method

[Link]====>variable

2.@Retention

@Retention annotation will decide scope for an annotation. (SOURCE,CLASS,RUNTIME)

[Link]
[Link]
[Link]

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.

[Link]/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()
{
[Link]("sending money from sbi");
}
}
class Axis extends Sbi
{

void sendMoneyToCustomer()

{
[Link]("sending money from Axis");
}
}
class Test
{
public static void main(String[] args)
{
Axis bhavadeesh=new Axis();
[Link]();
}
}

output

sending money from sbi

class Sbi
{
void sendMoneyToCustome()
{
[Link]("sending money from sbi");
}
}
class Axis extends Sbi
{

@Override
void sendMoneyToCustomer()

{
[Link]("sending money from Axis");
}
}
class Test
{
public static void main(String[] args)
{
Axis bhavadeesh=new Axis();
[Link]();
}
}

output

error: method does not override or implement a method from a supertype


@Override

class Sbi
{
void sendMoneyToCustomer()
{
[Link]("sending money from sbi");
}
}
class Axis extends Sbi
{

@Override
void sendMoneyToCustomer()

{
[Link]("sending money from Axis");
}
}
class Test
{
public static void main(String[] args)
{
Axis bhavadeesh=new Axis();
[Link]();
}
}
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)


{
[Link]("Before ycp govt");
}
void getSalary(int basic,int hra,int jtax)
{
[Link]("After ycp govt");
}

class Test
{
public static void main(String[] args)
{
Tcs t1=new Tcs();
[Link](2000,1200);

}
}

output

Before Ycp govt

class Tcs
{
@Deprecated
void getSalary(int basic,int hra)
{
[Link]("Before ycp govt");
}
void getSalary(int basic,int hra,int jtax)
{
[Link]("After ycp govt");
}
}
class Test
{
public static void main(String[] args)
{
Tcs t1=new Tcs();
[Link](2000,1200);

}
}

output

Note: [Link] uses or overrides a deprecated API.


Note: Recompile with -Xlint:deprecation for details.

@FunctionalInterface

[Link] normal interface contains multiple abstract methods.


[Link] interface which contains no variables and methods is called marker interface
[Link] 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 [Link].*;
class Test
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
[Link](1);
[Link](1.2);
[Link]("venky");
[Link](al);
}

Note: [Link] uses unchecked or unsafe operations.


Note: Recompile with -Xlint:unchecked for details.

import [Link].*;
class Test
{
@SuppressWarnings("unchecked")
public static void main(String[] args)
{
ArrayList al=new ArrayList();
[Link](1);
[Link](1.2);
[Link]("venky");
[Link](al);
}

output

[1,1.2,venky]

import [Link].*;
@Inherited
@Documented
@Target([Link])
@Retention([Link])
@interface Bank
{
int bno();
String bname();
}

@Bank(bno=4567,bname="HDFC")
class Account
{
int acno;
String aname;
Account(int acno,String aname)
{
[Link]=acno;
[Link]=aname;
}
void display()
{
[Link](acno);
[Link](aname);
}
}
class Test
{
@SuppressWarnings("unchecked")
public static void main(String[] args)
{
Account a1=new Account(23,"parithosh");
[Link]();
Class c1=[Link]();
Annotation a2=[Link]([Link]);
Bank b1=(Bank)a2;
[Link]([Link]());
[Link]([Link]());
}
}

import [Link].*;
@Inherited
@Documented
@Target([Link])
@Retention([Link])

@interface School
{
int slno();
String schname();
}
@School(slno=345,schname="Durga")
class Student
{

int sno;
String sname;
Student(int sno,String sname)
{
[Link]=sno;
[Link]=sname;
}
void display()
{
[Link](sno);
[Link](sname);
}
}

class Test
{
@SuppressWarnings("unchecked")
public static void main(String[] args)
{
Student s1=new Student(12,"Venky");
[Link]();
Class c1=[Link]();
Annotation a1=[Link]([Link]);
School s2=(School)a1;
[Link]([Link]());
[Link]([Link]());

}
}

output

12
Venky
345
Durga

import [Link].*;
@Inherited
@Documented
@Target([Link])
@Retention([Link])
@interface Bank
{
int bno();
String bname();
}

@Bank(bno=4567,bname="HDFC")
class Account
{
int acno;
String aname;
Account(int acno,String aname)
{
[Link]=acno;
[Link]=aname;
}
void display()
{
[Link](acno);
[Link](aname);
}
}
class Dept extends Account
{
}
class Test
{
@SuppressWarnings("unchecked")
public static void main(String[] args)
{
Account a1=new Account(23,"parithosh");
[Link]();
Class c1=[Link]();
Annotation a2=[Link]([Link]);
Bank b1=(Bank)a2;
[Link]([Link]());
[Link]([Link]());
}
}

interface

[Link] is a collection of public static final variables and public abstract methods.
[Link] interface public static final is implicitly present to the variables.
[Link] interface public abstarct is implicitly present to the methods.
[Link] 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
[Link] 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.
[Link] methods must be override with public access modifier in implementation class.
[Link] methods cannot be static
[Link] methods cannot be private
[Link] methods cannot be final
[Link] cannot be final.
[Link] are not possible in interfaces.
[Link] interfaces we can achieve multiple inheritance.

Difference between abstract class and interfaces.


abstract class

[Link] class contains concrete methods and abstract methods


[Link] abstract class abstract methods are not public abstract implicitly.
[Link] inheritance is not possible in abstarct class.
[Link] are allowed in abstract class.
[Link] method is possible in abstract class.
6. implemented class can extends only 1 abstract class.

interfaces

[Link] contains only abstract methods.


[Link] interface abstract methods are public abstract implicitly.
[Link] inheritance is possible in interface.
[Link] 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()
{
[Link](a);
[Link]("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()
{
[Link](a);
[Link]("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()
{
[Link](a);
[Link]("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()
{
[Link](itr+" ruppes interest for HomeLoan");
}
}
class EducationLoan implements Loan
{
public void getLoan()
{
[Link](itr+" ruppes interest for EducationLoan");
}
}
class GoldLoan implements Loan
{
public void getLoan()
{
[Link](itr+" ruppes interest for GoldLoan");
}
}
class User
{
public static void main(String[] args)
{
Loan bhavi=new HomeLoan();
[Link]();
Loan Hemanth=new EducationLoan();
[Link]();
Loan venky=new GoldLoan();
[Link]();
}
}

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()
{
[Link]("67 marks in physics");
}
public void getchMarks()
{
[Link]("87 marks in chemistry");
}

}
class User
{
public static void main(String[] args)
{
[Link]();
[Link]();
Physics p2=new Student();
[Link]();
Chemistry p3=new Student();
[Link]();
}
}
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()
{
[Link]("m1 in D");
}
public void m2()
{
[Link]("m2 in D");
}
public void m3()
{
[Link]("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

[Link] process of defining 1 class in another class is called Inner classes.


[Link] purpose of inner classes will provide more readable and maintabable code because it logically
group into classes and interfaces into single unit.
[Link] class private features we can access into another class.
[Link] are 4 types of inner [Link] are
[Link] class.
[Link] class.
[Link] class.
[Link] class.

[Link] 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()
{
[Link]("m2 in outer");
}

class Inner
{
void m1()
{
[Link]("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()
{
[Link]("m2 in outer");
}

class Inner
{
void m1()
{
[Link]("m1 in Inner");
}
}
public static void main(String[] args)
{
Outer o1=new Outer();
o1.m2();
new Outer().m2();
[Link] i1=[Link] Inner();
i1.m1();
}
}

output

m2 in outer
m2 in outer
m1 in inner

class Outer
{
void m2()
{
[Link]("m2 in outer");
}

class Inner
{
void m1()
{
[Link]("m1 in Inner");
}
}
public static void main(String[] args)
{
Outer o1=new Outer();
[Link] i1=[Link] Inner();
i1.m1();
[Link] 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()
{
[Link]("m2 in outer");
}

class Inner
{
int y=7;
void m1()
{
[Link](y);
[Link](x);

[Link]("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()
{
[Link]("m2 in outer");
}

class Inner
{
int y=7;
void m1()
{
[Link](y);
[Link](x);
[Link](z);

[Link]("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()
{
[Link](x);
[Link](y);
[Link](z);

}
public static void main(String[] args)
{
new Outer().new Inner().m1();
}
}
output

4
9
18

static class

[Link] class which is defined with static keyword is called static class.
[Link] 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()
{
[Link]("m2 in Inner");
}

}
public static void main(String[] args)
{
Outer o1=new Outer();
Inner i1=new [Link]();
i1.m2();

}
}

output

m2 in Inner

class Outer
{
static class Inner
{
int x=7;
void m2()
{
[Link](x);
[Link]("m2 in Inner");
}
}
public static void main(String[] args)
{
Outer o1=new Outer();
Inner i1=new [Link]();
i1.m2();
new [Link]().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()
{
[Link](y);
[Link](z);
[Link](u);

[Link](x);
[Link]("m2 in Inner");
}

}
public static void main(String[] args)
{
new [Link]().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()
{
[Link](y);
[Link](z);===============>error
[Link](u);==============>error

[Link](x);
[Link]("m2 in Inner");
}

}
public static void main(String[] args)
{
new [Link]().m2();

}
}

[Link] 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()
{
[Link]("m1 in Inner");
}

}
Inner i1=new Inner();
i1.m1();

}
}

class Outer
{
void m1()
{
[Link]("m1 in Outer");
class Inner
{
void m2()
{
[Link]("m2 in Inner");
}

}
new Inner().m2();

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

[Link] class

[Link] class is a one type of local class without name


[Link] class is a sub class of abstract class and interface.
[Link] purpose of anonymous class will reduce the code by removing implementation class.

Note:
[Link],protected,static is not allowed for outer class.
[Link],public,protected,private is not allowed for local class and anonymous class.
[Link] 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()
{
[Link]("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()
{
[Link]("m1 in imple class");
}
};
a1.m1();
}
}

Explain public static void main(String[] args)

[Link]

public is an access modifier.


jvm can access main method anywhere because of public

[Link]

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[]

[Link] order is not important

static public void main(String[] args)


public static void main(String[] args)

[Link] modifiers:public static


optional modifiers:final,synchronized,strictfp

[Link] void main(String[] args)================>invalid (static)


[Link] void main(String[] args)===============>invalid(public)
[Link] static int main(String[] args)========>invalid(void)
[Link] static void mainVenky(String[] args)==>invalid(main)
[Link] public void main(String[] args)========>valid
[Link] static void main(String... args)=======>valid
[Link] static void main(String... venky)======>valid
[Link] method can be overloaded but bydefault it will takes data in the form String .
[Link] method cannot be ovverride because main method is static.
[Link] length arguments allowed in main method.

[Link] Demo
{
public static void main(String venky[])
{
String s=venky[0];
[Link](s);
}
}

class Demo
{
public static void main(String venky[])
{
String s=venky[0];
[Link](s);
}
}

javac [Link]
java Demo Dhoni

Dhoni

class Demo
{
public static void main(String[] args)
{
[Link]("string data");
}
public static void main(int[] args)
{
[Link]("int data");
}

output

String data
Abstraction

[Link] process of hiding uncessesary details and showing necessary details is called Abstaraction.
[Link] process of hiding implementation code and showing only functinality to the user.
[Link] can be achieved in 2 [Link] are
[Link] class
[Link]

[Link] class

1.A class which is defined with abstract keyword then that is called a abstract class.
[Link] class is a collection of concrete methods and abstract methods.

abstract class A
{
}

concrete methods

[Link] methods which have body then that is called a concrete method.
[Link] 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.
[Link] purpose of abstract method is give different funtionality to the implementation classes.
[Link] methods can be defined in abstract classes only.
Important points on Abstarction

[Link] 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.

[Link] we want perform Abstarction Inheritance is required.


[Link] methods must be ovveride.
[Link] methods cannot be private.
[Link] methods cannot be static.
[Link] methods cannot be final.
[Link] class cannot be final.
[Link] methods can be static.
[Link] class can have main method also.
[Link] class can have constructors.

Ex
--
abstract void m1();

abstract class A
{
void m1()
{
[Link]("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()
{
[Link]("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()
{
[Link]("welcome to concrete");
}
abstract void m2();
}
class Test extends A
{
void m2()
{
[Link]("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()
{
[Link]("Youtube is playing in Realme");
}
abstract void sendSms();
}
class Airtel extends RealMe
{
void sendSms()
{
[Link]("sending sms from Airtel");
}
}
class Jio extends RealMe
{
void sendSms()
{
[Link]("sending sms from Jio");
}
}
class User
{
public static void main(String[] args)
{
RealMe bhavadeesh1=new Airtel();
[Link]();
[Link]();
RealMe bhavadeesh2=new Jio();
[Link]();
[Link]();

}
}

Youtube is playing in Realme


sending sms from Airtel
Youtube is playing in Realme
sending sms from Jio

abstract class A
{
void m1()
{
[Link]("m1 in A");
}
abstract private void m2();

}
class B extends A
{
void m2()
{
[Link]("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()
{
[Link]("m1 in A");
}
abstract final void m2();

}
class B extends A
{
void m2()
{
[Link]("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()
{
[Link]("m1 in A");
}
abstract void m2();

}
class B extends A
{
void m2()
{
[Link]("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()
{
[Link]("m1 in A");
}
abstract void m2();
}
class B extends A
{
void m2()
{
[Link]("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)
{
[Link]("welcome to abstract class");
}
}

welcome to abstract class

abstract class Demo


{
Demo()
{
[Link]("constrcutors in abstract class");
}
void m1()
{
[Link]("concrete without static in abstract class");
}
static void m2()
{
[Link]("concrete with static in abstract class");
}
abstract void m3();
}
class B extends Demo
{
void m3()
{
[Link]("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

[Link] is a medium or channel.


[Link] purpose of Stream is to carry data from input devices to output devices and
output devices to input devices.
[Link] are divided into 2 [Link] are
[Link] Streams
[Link] Streams

Note:Streams are present in [Link] package

[Link] Streams

Byte Streams stores the data in binary format like text,audio,video,pictures..etc

ByteStreams are divided into 2 [Link] are


[Link]
[Link]

[Link]

The purpose of InputStream is to carry the data from source file(java file) to target file([Link])
Ex
---
[Link]
[Link]
[Link]

[Link]

The purpose of OutputStream is to carry the data from target file([Link]) to source file([Link])

Ex
---
[Link]
[Link]
[Link]

[Link] Streams

Character Streams stores the data in characters format like text.


Character Streams are divided into 2 [Link] are
[Link]
[Link]

[Link]

Reader is used to carry the character data from input devices to java application
Ex
--
[Link]
[Link]

[Link]

Writer is used to carry the character data from java applications to output devices.

[Link]
[Link]
[Link]

PrinWriter

[Link] is predefine class.


[Link] converts primitive data(byte,short,int,float,char...) into text format.

Methods in PrintWriter

[Link]===>print() is used to print the data from source file([Link]) to target file([Link])in same line.

[Link]===>println() is used to print the data from source file to target file in new line.
[Link]===>printf() is used to print the formatting data from source file to target file.

import [Link].*;
class FileOutput
{
public static void main(String[] args)throws Exception
{
FileOutputStream fos=new FileOutputStream("[Link]",);
String s1="virat";
byte[] b=[Link]();
[Link](b);
[Link]();
}
}

[Link]=============>String s1="virat";
virat

[Link]=============>String s1="kohli";
kohli

FileOutputStream fos=new FileOutputStream("[Link]",true);


String s1="virat";
byte[] b=[Link]();
[Link](b);
[Link]();

[Link]=============>String s1="virat";
virat

[Link]=============>String s1="kohli";
viratkohli

import [Link].*;
class FileOutput
{
public static void main(String[] args)throws Exception
{
FileInputStream fis=new FileInputStream("[Link]");
int size=[Link]();
byte[] b=new byte[size];
[Link](b);
String s=new String(b);
[Link](s);
[Link]();
}
}

viratkohli

import [Link].*;
class Demo
{
public static void main(String[] args)throws Exception
{
FileWriter fw=new FileWriter("[Link]");
String data="Hello everyone";
char[] ch=[Link]();
[Link](data);
[Link]();

}
}

import [Link].*;
class Demo
{
public static void main(String[] args)throws Exception
{
FileReader fr=new FileReader("[Link]");
String data="";
int av=[Link]();
while(av!=-1)
{
data=data+(char)av;
av=[Link]();
}
[Link](data);
[Link]();
}
}

import [Link].*;
class Demo
{
public static void main(String[] args)throws Exception
{
FileInputStream fis=new FileInputStream("[Link]");
int size=[Link]();
byte[] b=new byte[size];
[Link]();
[Link]();

FileOutputStream fos=new FileOutputStream("c:/fs/[Link]");


[Link](b);
[Link]("Image is copied into virat to dhonifriend");
[Link]();

}
}

import [Link].*;
class Demo
{
public static void main(String[] args)throws Exception
{
PrintWriter pw=new PrintWriter("[Link]");
[Link]("virat");
[Link]("kohli");
[Link]("is champ");
[Link]("in the world");

int a=5;
[Link]("value of a is %d",a);
[Link]("printing in console");
[Link]();

}
}

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 [Link] are

[Link]
[Link]
[Link]

[Link] 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.

[Link] 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)

[Link]======>nextInt()
[Link]=====>nextByte()
[Link]=====>nextShort()
[Link]======>nextLong()
[Link]=====>nextFloat()
[Link]====>nextDouble()
[Link]======>next().charAt(0)
[Link]====>next(),nextLine()

next() is used to take only single word.


nextLine() is used to take multiple words(String line).

[Link] 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 [Link].*;
class Demo
{
public static void main(String[] args)throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
[Link]("enter data 1st:");
String s1=[Link]();
[Link]("enter data 2nd:");
int av=[Link]();
[Link]("first data:"+s1);
[Link]("second data:"+av+(char)av);
}
}

enter data 1st:


Bhavadeesh
enter data 2nd:
Bhavadeesh
first data:Bhavadeesh
second data:66B

import [Link].*;
class Demo
{
public static void main(String[] args)throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
[Link]("enter a value: ");
String a=[Link]();
[Link]("enter b value: ");
String b=[Link]();
[Link](a+b);
int fn=[Link](a);
int sn=[Link](b);
[Link](fn+sn);
}
}

enter a value:
5
enter b value:
6
56
11

import [Link].*;
import [Link].*;
class Demo
{
public static void main(String[] args)throws Exception
{
Scanner sc=new Scanner([Link]);
[Link]("enter username: ");
String uname=[Link]();
[Link]("enter password: ");
String pd=[Link]();
[Link](uname);
[Link](pd);

}
}

enter username:
Bhavadeesh
enter password:
Bhavi
Bhavadeesh
Bhavi

import [Link].*;
class Demo
{
public static void main(String[] args)throws Exception
{
Console c=[Link]();
[Link]("enter username: ");
String uname=[Link]();
[Link]("enter password: ");
char[] pwd=[Link]();
String pd=new String(pwd);
[Link](uname);
[Link](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.

[Link] an object to file


[Link] an object from file
[Link] an object to Network
[Link] 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 [Link].*;
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("[Link]");
ObjectOutputStream oos=new ObjectOutputStream(fs);
[Link](e1);
[Link]();
[Link]();

FileInputStream fis=new FileInputStream("[Link]");


ObjectInputStream ois=new ObjectInputStream(fis);
Emp e2=(Emp)[Link]();
[Link]([Link]+" "+[Link]);
[Link]();
[Link]();

}
}

packages

[Link] is a folder structure.


[Link] is a collection of classes,interfaces,enums,annotations,errors,Exceptions.
[Link] are divided into 2 [Link] are
[Link] packages
[Link] packages

[Link] packages

A package which is already present in java software(jdk).These packages are developed by java
developers.
[Link] is a bydefault package in java.

There are 14 predefine packages in java.


[Link]
[Link]
[Link].......

[Link] packages

A package which is not present in java software(jdk).These packages are developed by java
programmers.

package conventions

[Link]==================>domain name

[Link]======================>reverse domain

[Link]

[Link]=====>domain
bank========>project
withdraw====>module

[Link] module1
[Link] module2
[Link] module3
[Link] module4

syntax
------
package packagename;
class ClassName
{
}
interface InterfaceName
{
}
enum EnumName
{
}

Advantages of packages

[Link] we can develop project


[Link] resuability across folders.
[Link] removes naming conflicts
[Link] easy and readibility improved

package [Link];
class Sample
{
public static void main(String[] args)
{
[Link]("welcome to packages");
}
}
interface I1
{
}

javac [Link]
Sample
I1

java Sample

error

compilation of packages

javac -d . [Link]

Here
-d====================>directory
.====================>current directory

com
|---tcs
|--bank
|--account
|-I1
|-Sample

Execution of packages

java fullname
java [Link]

package [Link];
class Sample
{
public static void main(String[] args)
{
[Link]("welcome to packages");
}
}
interface I1
{
}

javac -d . [Link]

java [Link]
welcome to packages

package [Link];
class Sample
{
public static void main(String[] args)
{
[Link]("packages easy");
}
}

javac -d . [Link]

java [Link]
packages easy
com
|--tcs
|--bank
|--withdraw
|-Sample

import

[Link] is a keyword in java.


[Link] 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 [Link];
public class Info
{
public void apInfo()
{
[Link]("jai ap");
}
public void tsInfo()
{
[Link]("jai ts");
}

package [Link];
import [Link];

class Client
{
public static void main(String[] args)
{
Info i1=new Info();
[Link]();
[Link]();
}
}

javac -d . [Link]

javac -d . [Link]

java [Link]
jai ap
jai ts
package [Link];
public class Info
{
public void apInfo()
{
[Link]("jai ap");
}
public void tsInfo()
{
[Link]("jai ts");
}

package [Link];

class Client
{
public static void main(String[] args)
{
[Link] i1=new [Link]();
[Link]();
[Link]();
}
}

javac -d . [Link]

javac -d . [Link]

java [Link]
jai ap
jai ts

[Link] Introduction
[Link] of Multitasking
[Link] class and Runnable Interface
[Link] and setting names for Threads
[Link] of Thread
[Link](),yield(),sleep()
[Link] and Asynchronization
[Link] Threads
[Link] communication
[Link] and starvation

Multitasking

[Link] process of executing multiple tasks a time(simultaneously/parallely/concurrently)


[Link] is divided into 2 [Link] are
[Link] based tasking
[Link] based tasking(Multithreading)

[Link] based tasking

The process of executing multiple tasks [Link] 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

[Link] based tasking(Multithreading)

The process of executing multiple tasks [Link] 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


[Link] we will get fastest execution.

Realtime applications for Multithreading

1. Video games applications.


2. Animations applications.
[Link] graphics applications.

Thread

[Link] is a flow of control or piece of code.


[Link] are divided into 2 [Link] are
[Link] Threads(single Thread)
[Link] Threads(Multiple Threads)
[Link] java Thread is defined in 2 [Link] are
[Link] extending Thread class
[Link] implementing Runnable interface

Note:1 class extends 1 class


1 class implements multiple interfaces
1 interface extends multiple interface

Thread

[Link] is a predefine class.


[Link] class contains start() and run()
Runnable

[Link] is a predefine interface.


[Link] 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.

[Link] 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.

[Link] 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


[Link]()

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

[Link](MINPRI TO MAXPRI) ===============> 1 to 10


[Link] Priority=======================>5

[Link]:If we set priorities more than 10 and less than 1 then it will give
IllegalArgumentException

[Link] we increase or decrease priorities for main thread it will be same for child thread.

[Link] we increase or decrease priorities for child thread it will be differnt for main thread.

[Link] priorities will be same for both threads main(5) and child(5) threads
So we not able to predict output.

[Link] 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.

[Link] 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++)
{
[Link]("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
{
[Link]("Userdefine Thread");====>UserThread is Exceuting
}

}
public static void main(String[] args)
{
AjayThread a=new AjayThread();=====>UserdefineThread is born
[Link]();=======================>Userdefine Thread is ready to run

for(int i=1;i<=10;i++)
{
[Link]("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++)
{
[Link]("Userdefine Thread");
}

}
public static void main(String[] args)
{
AjayThread a=new AjayThread();
[Link]();

for(int i=1;i<=10;i++)
{
[Link]("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()
{
[Link]("car is going");
[Link]("=================");

}
public static void main(String[] args)
{
Car c1=new Car();
[Link]();
Car c2=new Car();
[Link]();
Car c3=new Car();
[Link]();

}
}

car is going

car is going

car is going

class UserDefineThread implements Runnable


{
public void run()
{
[Link]("userdefinethread");
}
public static void main(String[] args)
{
UserDefineThread u=new UserDefineThread();
Thread t1=new Thread(u);
[Link]();

}
}

userdefinethread
interface I1
{
}
class UserDefineThread implements Runnable,I1
{
public void run()
{
[Link]("userdefinethread with multiple inheritance");

}
public static void main(String[] args)
{
UserDefineThread u=new UserDefineThread();
Thread t1=new Thread(u);
[Link]();

}
}

userdefinethread with multiple inheritance

class Venky
{
}
class UserDefineThread extends Thread,Venky
{
public void run()
{
[Link]("userdefinethread with multiple inheritance");

}
public static void main(String[] args)
{
UserDefineThread u=new UserDefineThread();
[Link]();

}
}

Error
UserDefineThread extends Thread,Venky

class VenkyThread extends Thread


{
public static void main(String[] args)
{
[Link]([Link]().getName());==>main
[Link]().setName("PawanThread");
[Link]([Link]().getName());==>PawanThread

}
}
class VenkyThread extends Thread
{
public void run()
{
}
public static void main(String[] args)
{
[Link]([Link]().getName());
[Link]().setName("PawanThread");
[Link]([Link]().getName());
[Link]("================================");
VenkyThread v=new VenkyThread();
[Link]([Link]());
[Link]("MaheshThread");
[Link]([Link]());

}
}

main
PawanThread

Thread-0
MaheshThread

class VenkyThread extends Thread


{
public void run()
{
[Link]([Link]().getName());
[Link]().setName("ManjuThread");
[Link]([Link]().getName());

}
public static void main(String[] args)
{
[Link]([Link]().getName());
[Link]().setName("AjayThread");
[Link]([Link]().getName());
VenkyThread v=new VenkyThread();
[Link]();

}
}

main
AjayThread
Thread-0
ManjuThread

class VenkyThread extends Thread


{
public void run()
{
[Link]([Link]().getName());
[Link]([Link]().getPriority());

}
public static void main(String[] args)
{
[Link]([Link]().getName());
[Link]([Link]().getPriority());
[Link]("============================");
VenkyThread v=new VenkyThread();
[Link]();

}
}

main
5

Thread-0
5

class VenkyThread extends Thread


{
public void run()
{
[Link]([Link]().getName());
[Link]([Link]().getPriority());

}
public static void main(String[] args)
{
[Link]([Link]().getName());
[Link]([Link]().getPriority());
[Link]().setPriority(7);
[Link]([Link]().getPriority());

[Link]("============================");
VenkyThread v=new VenkyThread();
[Link]();

}
}

main
5
7

Thread-0
7

class VenkyThread1 extends Thread


{
public void run()
{
for(int i=1;i<=5;i++)
{
[Link]("child thread");
}

}
public static void main(String[] args)
{
[Link]([Link]().getName());
[Link]([Link]().getPriority());
[Link]("================================");
VenkyThread1 v=new VenkyThread1();

[Link]([Link]());
[Link](8);
[Link]([Link]());

[Link]();

for(int i=1;i<=5;i++)
{
[Link]("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)


{
[Link]([Link]().getPriority());
[Link]().setPriority(33);==>.IllegalArgumentException
[Link]([Link]().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++)
{
[Link]("Ajay thread");
try
{
[Link](2000);

}
catch(InterruptedException e)
{
}

}
}
public static void main(String[] args)throws InterruptedException
{
Demo d=new Demo();
[Link]();
[Link]();
for(int i=1;i<=10;i++)
{
[Link]("Mohan thread");
}

}
}

[Link]()

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

[Link](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++)
{
[Link]("Ajay thread");

}
}
public static void main(String[] args)throws InterruptedException
{
Demo d=new Demo();
[Link]();
[Link]();
for(int i=1;i<=10;i++)
{
[Link]("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

[Link] process of executing one by one thread among multiple threads.


[Link] purpose of synchronization is to achieve data consistency.
[Link] can be applied by using synchronized.
[Link] can be applied to the methods and blocks
[Link] case of synchronized method synchronization is applied to the entire method

[Link] 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++)
{
[Link](i+" class is taking by : "+faculty);
try
{
[Link](2000);
}
catch(InterruptedException e)
{
}
}
}
}
class UserThread extends Thread
{
ClassRoom c1;
String faculty;
UserThread(ClassRoom c1,String faculty)
{
this.c1=c1;
[Link]=faculty;
}
public void run()
{
[Link](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");
[Link]();
[Link]();

}
}

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)
{
[Link]("1st 100 lines");
synchronized(this){

for(int i=1;i<=10;i++)
{
[Link](i+" class is taking by : "+faculty);
try
{
[Link](2000);
}
catch(InterruptedException e)
{
}
}
}
[Link]("last 20 lines");

}
}
class UserThread extends Thread
{
ClassRoom c1;
String faculty;
UserThread(ClassRoom c1,String faculty)
{
this.c1=c1;
[Link]=faculty;
}
public void run()
{
[Link](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");
[Link]();
[Link]();

}
}

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

[Link] process of executing all threads at a time among multiple threads.


[Link] Asynchronization data inconsistency will come.

class ClassRoom
{
void takeClass(String faculty)
{
for(int i=1;i<=10;i++)
{
[Link](i+" class is taking by : "+faculty);
try
{
[Link](2000);
}
catch(InterruptedException e)
{
}
}
}
}
class UserThread extends Thread
{
ClassRoom c1;
String faculty;
UserThread(ClassRoom c1,String faculty)
{
this.c1=c1;
[Link]=faculty;
}
public void run()
{
[Link](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");
[Link]();
[Link]();

}
}

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.
[Link] purpose of Daemon Thread is to provide support or services to non DaemonThreads.
[Link] cannot create Daemon thread for main thread(predefine thread).

[Link] can create Daemon thread for child thread(userdefine thread).


[Link] cycle of Daemon thread :Daemon thread will execute based on another thread
(main thread)

Examples

[Link] 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

[Link] final void setDaemon(boolean)


-------------------------------------
setDaemon() is used to set Daemon thread for non Daemon thread.
[Link] 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()
{
[Link]("child Thread");===================>child Thread
[Link]([Link]().isDaemon());===>true
}
public static void main(String[] args)throws IllegalThreadStateException
{
UserDefineThread u1=new UserDefineThread();
[Link](true);

[Link]();
[Link]("main thread");==============>main thread

}
}

class UserDefineThread extends Thread


{
public void run()
{
for(int i=1;i<=10;i++)
{
[Link]("child thread");
try
{
[Link](2000);
}
catch(InterruptedException e)
{
}
}

}
public static void main(String[] args)
{
UserDefineThread u1=new UserDefineThread();
[Link]();
[Link]("main thread");

}
}
[Link](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)
{
[Link]([Link]().isDaemon());
[Link]().setDaemon(true);==>IllegalThreadStateException
[Link]([Link]().isDaemon());

}
}

InterThread communication

[Link] process of communicating one thread with another thread.


[Link] communication can be perform by using
[Link]()
[Link]()
[Link]()
[Link] communication is applied to the only synchronized threads.

[Link]()

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.

[Link]()

when a thread is sending or giving updation or notification to the single waiting thread then we have to use notify().

[Link]()

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();
[Link]();
[Link]([Link]);

}
}

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)
{
[Link]("child thread got chance 2nd");
int sum=0;
for(int i=1;i<=100;i++)
{
sum=sum+i;
}
[Link]("performed all logic and giving upd to main");
[Link]();

}
}
}
class Demo
{
public static void main(String[] args)throws Exception
{
AjayThread a1=new AjayThread();
[Link]();
synchronized(a1)
{
[Link]("main got chance 1st and waiting");
[Link]();
[Link]("main got updation");
[Link]([Link]);

}
}
}

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
{
[Link]();
}
catch(InterruptedException e)
{
}
for(int i=1;i<=10;i++)
{
[Link]("child Thread");
}

}
}
class Demo
{
public static void main(String[] args)throws Exception
{
[Link] =[Link]();
AjayThread a1=new AjayThread();
[Link]();
for(int i=1;i<=10;i++)
{
[Link]("main Thread");
[Link](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
{
[Link]();
}
catch(InterruptedException e)
{
}
for(int i=1;i<=10;i++)
{
[Link]("child Thread");
}
}
}
class Demo
{
public static void main(String[] args)throws Exception
{
[Link] =[Link]();
AjayThread a1=new AjayThread();
[Link]();
[Link]();
for(int i=1;i<=10;i++)
{
[Link]("main Thread");
[Link](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)
{
[Link]("Thread1 starts execution of d1 method");
try
{
[Link](2000);
}
catch(Exception e)
{
}
[Link]("Thread1 trying to call bis last method");
[Link]();
}
public synchronized void last()
{
[Link]("Inside A last method");
}
}
class B
{
public synchronized void d2(A a)
{
[Link]("Thread2 starts execution of d2 method");
try
{
[Link](2000);
}
catch(Exception e)
{
}
[Link]("Thread2 trying to call Ais last method");
[Link]();
}
public synchronized void last()
{
[Link]("Inside B last method");
}
}
class MyThread extends Thread
{
A a=new A();
B b=new B();
public void m1()
{
[Link]();
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