All in One Java Notes
All in One Java Notes
java Introduction
1.java is a popular programming language.
2.Father of java is James’s gosling.
3.Java 1st version (1.0) was introduced by Sun microsystem in 1996.
4.At present java was owned by oracle corporation.
1. j2se
1.j2se stands for java 2 standard edition.
2.In j2se we will learn java fundamentals.
3.By using j2se we will develop standalone/desktop/window-based App
2. j2ee
1.j2ee stands for java 2 enterprise edition.
2.In j2ee we will learn server-side programming.
3.By using j2ee we will develop enterprise/distributed app.
3. j2me
1.j2me stands for java 2 micro edition.
2.In j2me we will learn micro side programming.
3.By using j2me we will develop mobile based App
___________________________________________________________
Basic java program syntax
INPUT:
class ClassName
{
public static void main(String[] args)
{
statements
}
}
class Demo
{
public static void main(String[] args)
{
System.out.println("welcome to java");
}
}
OUTPUT:
welcome to java
___________________________________________________________
Literals
1.Literals are input values.
2.Literals are divided into 6 types:
1.Integer Literals========================>-12,0,12...
2.Floating Point Literals=================>-1.2f,1.0f,2.5f...
3.Character Literals======================>'a','z','1',...
4.String Literals=========================>"Excelr","Trainer"...
5.Boolean Literals========================>true, false
6.Object Literals=========================>null
Variables
1.A variable is a container.
2.The purpose of variable is to store operand(value,variable,expression).
3.variable declaration
datatype varname;==========>variable declaration
varname=value==============>assigning
int a;
a=5;
4.variable Initialization
datatype varname=value;
int a=2;
5.int a=5=======>value
6.int b=a========>variable
7.int c=6+3======>expression
Rules
1.A variable must be a alphabet (lowercase)(a-z), UpperCase(A-Z), Digit(0-9) and special symbols (_,$).
2.A variable 1st letter must not starts with digit(0-9).
3.A variable does not allow special symbols except(_ $).
4.Keywords must not use as variables.
5.Variable size is unlimited but according to industry standards do not use variable size more than 16 digits.
6.Variable is case sensitive.
7.true and false are not keywords but do not use as variables.
Examples
int abcB12_$=10; ======>valid
int 1ba=10; ==========>invalid
int a*5=10; ==========>invalid
int a@b=9 ;===========>invalid
int _ab=10; ===========>valid
Identifiers
1.Identifier is a one type of variable.
2.The purpose of identifier is to identify package, subpackage, class, interface, method....
package
1.package must be written in lowercase.
2.A package before there is no dot(.) then that is called package.
3.A package before there is dot(.) then that is called subpackage.
class
A class 1st letter must start with capital from each word onwards.
interface
An interface 1st letter must start with capital from each word onwards.
Method
A method 1st letter must start with capital from second word onwards and ends with ().
Examples
java.lang=====>java(package) lang(sub package)
java.io=======>java(package) io(sub package)
java.util.Arrays==>java(package) util(subpackage) Arrays(class)
LinkedList======>class
lastIndexOf()===>method
List============>interface
Set=============>interface
Map=============>interface
Comparator======>interface
Comparable=====>interface
Keywords
1.Keywords are set of reserved words.
2.Reserved words will have particular functionality.
3.At present there are 50 keywords in java including assert, strictfp, enum.
4.Keywords must be written in lowercase.
5.goto and const are not using in java.
6.true and false are not keywords but do not use as variables.
Examples
byte, short, int, long, float, double, char, Boolean, if, else, else if, for, while, do, break, continue, public private,
protected, switch, static, final, this, super, abstract, transient, synchronized, volatile, extends implements, return,
void...
Datatypes
Datatype determines what type of value we can store.
Datatypes are divided into 2 types:
1.primitive
2.Non primitive/reference datatype
1.primitive Datatypes
Primitive datatypes are predefine datatypes.
primitive datatypes store 1 value at a time
There are 8 primitive datatypes in java.
1.byte
2.short
3.int
4.long
5.float
6.double
7.char
8.boolean
2.Non-primitive datatypes
Non-Primitive datatypes are user-define datatypes.
Non-primitive datatypes store multiple values at a time
Example:
Arrays
String
class
class
object
1.byte
byte datatype will store both positive and negative values without decimals.
Examples:
byte a=10;
System.out.println(a); ==>10
byte a=-10;
System.out.println(a); ===>-10
byte a=1.2;
System.out.println(a); ===>error
byte a=129;
System.out.println(a); ===>error
2.short
short datatype will store both positive and negative values without decimals.
Examples:
short a=10;
System.out.println(a); ==>10
short a=-10;
System.out.println(a); ===>-10
short a=1.2;
System.out.println(a); ===>error
3.int
int datatype will store both positive and negative values without decimals.
Examples:
int a=10;
System.out.println(a); ==>10
int a=-10;
System.out.println(a); ===>-10
int a=1.2;
System.out.println(a); ===>error
4.long
long datatype will store both positive and negative values without decimals.
If we store more than max value of int in long we must ends with l or L.
Examples
long a=10;
System.out.println(a); ==>10
long a=-10;
System.out.println(a); ===>-10
long a=1.2;
System.out.println(a); ===>error
System.out.println(Byte.SIZE);
long a=21474836478;
System.out.println(a); ===>error
long a=21474836478l;
System.out.println(a); ===>21474836478
Sr.NO DATATYPE SIZE RANGE (Min to max)
1. byte 8 -128 to 127
2. short 16 -32768 TO 32767
3. int 32 -2147483648 TO 2147483647
4. long 64 -9223372036854775808 To -9223372036854775807
1.System.out.println(Byte.SIZE);
2.System.out.println(Byte.MIN_VALUE);
2.System.out.println(Byte.MAX_VALUE);
Examples
int a=10; ======>Normal data
int a=0b1010; ==>Binary data
int a=0B1111; ===>Binary data
int a=0b234; ====>error
int a=0123; =====>Octal
int a=0x123; ===>Hexadecimal
int a=0b1010;
System.out.println(a); ==============>10
int a=012;
System.out.println(a); ======>10
int a=0x12;
System.out.println(a); =========>18
int a=10;
System.out.println(a); ===========>10
String b=Integer.toBinaryString(a);
System.out.println(b); ===========>1010
int a=10;
System.out.println(a); //10
String b=Integer.toOctalString(a);
System.out.println(b); //12
int a=10;
System.out.println(a); //10
String b= Integer.toHexString(a);
System.out.println(b); //a
1.float
1.float datatype stores both positive and negative values with decimal and without decimal.
2.float values must be ends with f or F.
3.In float datatype after decimal we can store 7 digits.
Examples
1.>float ab=1.2;====>error
System.out.println(ab);
2.>float ab=1.2f;
System.out.println(ab);===>1.2
3.>float ab=-1.2f;
System.out.println(ab);===>-1.2
4.>float ab=1f;
System.out.println(ab);===>1.0
1. float a=3e2f;
System.out.println(a);=======>300.0
1. float a=7e2f;
System.out.println(a);========>700.0
2
3*10===========>3*100==========>300============>300.0
2
7e2f=====>7*10===>7*100======>700==========>700.0
6.double
1.double datatype stores both positive and negative values with decimal and without decimal.
2.double values must not be ends with f or F.
3.In double datatype after decimal we can store 16 digits.
4.double datatype also stores scientific data.
Examples
1.>double ab=1.2;
System.out.println(ab);====>1.2
2.>double ab=-1.2;
System.out.println(ab);===>-1.2
3.>double ab=1;
System.out.println(ab);===>1.0
7.char
1.char datatype store single character and enclosed with single quotes('').
2.If we store ascii value in char datatype we need not to enclose with single quotes('')
ASCII VALUES
Examples
1.char ch='a';=====>valid
System.out.println(ch);===================>a
2.char ch='ab';=====>invalid
System.out.println(ch);===================>error
3.char ch=a;=====>invalid
System.out.println(ch);===================>error
4.char ch='9';
System.out.println(ch);==========>9
5.char ch='19';
System.out.println(ch);==========>error
6.char ch=97;
System.out.println(ch);=====>a
7.char ch=65;
System.out.println(ch);=====>A
8.char ch='97';
System.out.println(ch);====>error
8.boolean
Examples
1.boolean b=true
System.out.println(b);=========>true
2.boolean b=false
System.out.println(b);=========>false
3.boolean b=0
System.out.println(b);=========>error
4.boolean b=1
System.out.println(b);=========>error
Type conversions
1.The process of converting one datatype into another datatype is called type conversion.
2.At present total 56 type conversions in java.
3.Type conversions are divided into 2 types.They are
1.widening type conversions.(19)
2.Narrowing type conversions.(23)
4.14 type conversions are not possible boolean cannot be converted into any other datatype and
any other datatype cannot be converted into boolean.
Examples
1.boolean b=true;
int a=b;
Sytem.out.println(a);==============>error
2.boolean b=true;
float a=b;
Sytem.out.println(a);==============>error
3.int a=5;
boolean b=a;
System.out.println(b);=======>error
1. byte a=12;
short b=a;
System.out.println(b);=========>12
2. byte a=112;
int b=a;
System.out.println(b);========>112
3 int a=12;
float b=a;
System.out.println(b);========>12.0
4. char ch='a';
int b=ch;
System.out.println(b);========>97
byte======>char==========================>1
short=====>byte,char=====================>2
int=======>byte,short,char================>3
long======>byte,short,int,char============>4
float=====>byte,short,int,long,char=======>5
double=====>byte,short,int,long,float,char=>6
char======>byte,short=======================>2
char ch='A';
byte bh=ch;
System.out.println(bh);=========>error
char ch='A';
byte bh=(byte)ch;
System.out.println(bh);==============>65
int a=122;
char ch=(char)a;
System.out.println(ch);==============>z
Operations
byte,short,int,char + byte,short,int,char===>int
byte,short,int,char + long=================>long
byte,short,int,long,char + float=================>float
byte,short,int,long,float,char + double=================>double
Any datatype + String==================>String
1.byte a=7;
int b=6;
System.out.println(a+b);===========>13
2.int a=6;
char b=97;
System.out.println(a+b);======>103
3.int a=6;
char b='a';
System.out.println(a+b);===>103
4.int a=6;
String s="virat";
System.out.println(a+s)====>6s
5.System.out.println(6+"virat"+7);===>6virat7
Operators
1.operator is a symbol.
2.The purpose of operators is to perform operations
1.Arithmetic operators(+,-,*,/,%)
Examples
1.System.out.println(1+2);==========>3
2.System.out.println(3-2);==================>1
3.System.out.println(6*2);==================>12
4.System.out.println(6/2);=================>3(quotient)
5.System.out.println(6%2);=================>0(remainder)
Order of precedence
1.()
2./,%,*
3.+,_
class First
{
public static void main(String[] args)
{
int a=5;
int b=6;
int c=3;
System.out.println(a+b+(b+c));======================>20
}
}
int a=5;
int b=6;
int c=3;
int d=7;
System.out.println(a*b+b-d-a+c);====================>27
2.>Assignment operators(=)
operands
Examples
int a=5;
int a=5;====>value
int b=a;====>variable
int c=5+6;===>expression
3.Relational operators(<,>,<=,>=,==,!=)
Relational operators are used to compare 2 values and returns either true or false.
Examples
1.System.out.println(5>3);=============>true
2.System.out.println(5>11);============>false
3.System.out.println(5>11<2);==========>error
4.System.out.println(5<2);=============>false
5.System.out.println(5<21);=============>true
6.System.out.println(5<=6);=============>true
7.System.out.println(6<6);===============>false
8.System.out.println(6<=6);==============>true
9.System.out.println(2>=2);===============>true
10.System.out.println(2==2);===============>true
11.System.out.println(2==3);===============>false
12.System.out.println(2!=3);==============>true
13.System.out.println(2!=2);==============>false
4.Logical operators
Logical operators are used to compare multiple conditions and returns either true
or false.
Increment/Decrement operators
1.pre increment(++var)
1.post increment(var++)
Examples
1. int a=5;
++a;
System.out.println(a);====>6
2. int a=5;
a++;
System.out.println(a);===>6
3. int a=5;
System.out.println(++a);===>6
4. int a=5;
System.out.println(a++);===>5
5. int a=5;
System.out.println(++a + ++a);====>13
6. int a=5;
System.out.println(a++ + ++a);
7. int a=5;
System.out.println(a++ + a++);===>11
8. int a=5;
System.out.println(a++ + ++a + a++);======>19
1.pre Decrement(--var)
1.post Decrement(var--)
Examples
int a=5;
System.out.println(a++ + --a + a++);=====>15
int a=5;
System.out.println(a-- + --a + a++);====>11
Bitwise Operators
Bitwise operators are work on binary data and returns integer value.
There are 6typesof Bitwise Operators
1.Bitwise LeftShift(<<)
2.Bitwise RightShift(>>)
3.Bitwise Complementary(~)
4.Bitwise AND(&)
5.Bitwise OR(|)
6.Bitwise XOR(^)
1.Bitwise LeftShift(<<)
b
FORMULA a*2
Examples
int a=12;
int b=3;
System.out.println(a<<b);===>96
2.Bitwise RightShift(>>)
FORMULA a
__
b
2
Examples
int a=12;
int b=3;
System.out.println(a>>b);===>1
3.Bitwise Complementary(~)
Formula ~n=-(n+1)
int a=12;
System.out.println(~a);===>-13
4.Bitwise AND(&)(multiply)
int a=9;
int b=7;
System.out.println(a&b);===>1
5.Bitwise OR(|)(addition)
int a=9;
int b=7;
System.out.println(a|b);===>15
a(9)======>1001
b(7)======>0111
1111===>15
6.Bitwise XOR(^)
int a=9;
int b=7;
System.out.println(a^b);
a(9)======>1001
b(7)======>0111
11 10
7.Conditional operator
Syntax
5>2 ? 2 : 3
true 2
5>12 ? 2 : 3
false 3
1.System.out.println(5>2?2:3);====>2
2.System.out.println(5>12?2:3);=====>3
3.System.out.println(5>12?"Excelr institute":"tcs");====>tcs
int a=5;
int b=2;
float res=5>2?1.2f:1.6f;
System.out.println(res);
int a=5;
int b=12;
String res=(a>b)?"super":(b>a)?"Excellent":"Bad";
System.out.println(res);===>Excellent
8.Compound operator
int a=-5;
int b=-a;
System.out.println(b);========>5
int a=5;
int b=2;
a=a+b;
System.out.println(a);=====>7
int a=5;
int b=2;
a+=b;===========>a=a+b===>5+2
System.out.println(a);====>7
int a=5;
int b=2;
a-=b;===>a=a-b
System.out.println(a);==>3
int a=5;
int b=2;
a*=b;
System.out.println(a);====>10
int a=5;
int b=2;
a/=b;
System.out.println(a);==>2
int a=5;
int b=2;
a%=b;
System.out.println(a);===>1
Unary operator
The operator which will work on 1 operand
++a
a++
++5
Binary operator
Ternary operator
cond?trueexp:false
(a>b)?a:b
(5>2)?5:2
Statements
1.Simple Statements
class Demo
{
public static void main(String[] args)
{
int a=5;============>input Statement
System.out.println(a);=====>out Statement========>5
}
}
2.Conditional Statements
1.Simple if
Syntax
if(cond)
{
------------
Statements
------------
}
int a=5;
if(a>2)
{
System.out.println("positive num");=============>positive num
}
int a=5;
if(a>12)
{
System.out.println("positive num");================>No ouput
}
2.if else
Syntax
if(cond)
{
--------
-------
}
else
{
-------
-------
}
int a=5;
int b=2;
if(a>b)
{
System.out.println(a+" is big num");
}
else
{
System.out.println(a+" is not big num");
int a=5;
int b=12;
if(a>b)
{
System.out.println(a+" is big num");
}
else
{
System.out.println(a+" is not big num");
syntax
if(cond)
{
}
else if(cond)
{
}
else if(cond)
{
}
------
------
else
{
}
int marks=90;
if(marks>90)
{
System.out.println("A grade");
}
else if((marks>80) && (marks<90))
{
System.out.println("B grade");
}
else if((marks>70) && (marks<80))
{
System.out.println("C grade");
}
else
{
System.out.println("Fail");
}
output====>Fail
int marks=90;
if(marks>90)
{
System.out.println("A grade");
}
else if((marks>80) && (marks<90))
{
System.out.println("B grade");
}
else if((marks>70) && (marks<80))
{
System.out.println("C grade");
}
No ouput
4.Multiple if
if(cond)
{
}
if(cond)
{
}
if(cond)
{
}
----
----
else
{
}
int marks=87;
if(marks>90)
{
System.out.println("A grade");
}
if((marks>80) && (marks<90))
{
System.out.println("B grade");
}
if((marks>70) && (marks<80))
{
System.out.println("C grade");
}
else
{
System.out.println("Fail");
}
output
B grade
Fail
int marks=87;
if(marks>90)
{
System.out.println("A grade");
}
if((marks>80) && (marks<90))
{
System.out.println("B grade");
}
if((marks>70) && (marks<80))
{
System.out.println("C grade");
}
Output
B grade
if(5>2)
{
System.out.println("java");
}
if(15>2)
{
System.out.println("python");
}
if(17>2)
{
System.out.println("ruby");
}
Output
java
python
ruby
if(5>2)
{
System.out.println("java");
}
else if(15>2)
{
System.out.println("python");
}
else if(17>2)
{
System.out.println("ruby");
}
Output
java
Note:In if else if multiple conditions are satisfied then 1st true block will execute
In multiple if multiple conditions are satisfied the all the block willexecute
Nested if
Syntax
if(cond)
{
if(cond)
{
---
}
}
if(15>2)
{
if(6>1)
{
System.out.println("Nested if");
}
}
Output===>Nested if
if(15>2)====>1(true)
{
if(6>11)====>2(false)
{
System.out.println("Nested if");
}
else===>3
{
System.out.println("else in nested if");==>4
}
}
output:else in nested if
if(15>22)=======>1(false)
{
if(6>11)
{
System.out.println("Nested if");
}
else
{
System.out.println("else in nested if");
}
}
else====>2
{
if(12>6)====>3(true)
{
System.out.println("if in else");===>4
}
else
{
System.out.println("else in else");
}
}
Output:if in else
switch
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid day");
}
}
}
Even Number
Odd Number
int first=12;
int second=16;
if(first>second)
{
System.out.println(first+"is a big num");
}
else
{
System.out.println(second+"is a big num");
}
int first=12;
int second=16;
int third=11;
if((first>second) && (first>third))
{
System.out.println(first+" is a big num");
}
else if((second>first) && (second>third))
{
System.out.println(second+" is a big num");
}
else
{
System.out.println(third+" is a big num");
int first=12;
int second=16;
int third=11;
int four=17;
if((first>second) && (first>third) && (first>four))
{
System.out.println(first+" is a big num");
}
else if((second>first) && (second>third) && (second>four))
{
System.out.println(second+" is a big num");
}
else if((third>first) && (third>second) && (third>four))
{
System.out.println(third+" is a big num");
}
else
{
System.out.println(four+" is a big num");
Note:Lowercase (character>='a')&&(character<='z')
Upperercase (character>='A')&&(character<='Z')
Digit (character>='0')&&(character<='9')
char ch='B';
if((ch>='a') && (ch<='z'))
{
System.out.println(ch+"is a lowercase");
}
else
{
System.out.println(ch+"is a uppercase");
char ch='v';
if((ch>='a') && (ch<='z'))
{
System.out.println(ch+"is a lowercase");
}
else if((ch>='A') && (ch<='Z'))
{
System.out.println(ch+"is a uppercase");
}
else
{
System.out.println(ch+"is a digit");
char ch='*';
if((ch>='a') && (ch<='z'))
{
System.out.println(ch+"is a lowercase");
}
else if((ch>='A') && (ch<='Z'))
{
System.out.println(ch+"is a uppercase");
}
else if((ch>='0') && (ch<='9'))
{
System.out.println(ch+"is a digit");
}
else
{
System.out.println(ch+"is a special symbol");
vowel======>a,e,i,o,u,A,E,I,O,U
consonants===>b,c,d,f,g,h,j,k,l,m,n,p,q,r,s,t,v,w,x,y,z
char ch='e';
if((ch=='a') ||(ch=='e')||(ch=='i')||(ch=='o')||(ch=='u'))
{
System.out.println("vowel");
}
else
{
System.out.println("consononat");
char ch='E';
if((ch=='a') ||(ch=='e')||(ch=='i')||(ch=='o')||(ch=='u')||
(ch=='A') ||(ch=='E')||(ch=='I')||(ch=='O')||(ch=='U'))
{
System.out.println("vowel");
}
else
{
System.out.println("consononat");
char ch='b';
System.out.println(ch);
int val=ch-32;
System.out.println(val);
char ori=(char)val;
System.out.println(ori);
char ch='b';
System.out.println(ch);
int val=ch+32;
System.out.println(val);
char ori=(char)val;
System.out.println(ori);
int first=10;
int second=20;
System.out.println("Before Swapping");
System.out.println("first is"+first);
System.out.println("second is"+second);
System.out.println("===================");
System.out.println("After Swapping");
int temp=first;
System.out.println("temp is"+temp);
first=second;
System.out.println("first is"+first);
second=temp;
System.out.println("second is"+second);
int first=10;
int second=20;
System.out.println("Before Swapping");
System.out.println("first is"+first);
System.out.println("second is"+second);
System.out.println("===================");
System.out.println("After Swapping");
first=first*second;
System.out.println(first);
second=first/second;
System.out.println(second);
first=first/second;
System.out.println(first);
Non century leap year must be divisible by 4 and not divisible by 100.(1988,1992,1996)
Century leap year must be divisible by 100(1600,2000)
int year=1996;
if (((year % 4 == 0) && (year % 100!= 0)) || (year%400 == 0))
{
System.out.println(" leap year");
}
else
{
System.out.println(" not a leap year");
}
Looping Statemets.
Loopig Statements are used to execute multiple statements until condition become false
For Loop
For loop is used to execute multiple statements until condition become false
When we know number of iterations go for for loop.
For Loop Execution
1.Initialization====>Starting value
2.Condition=========>Ending value
3.Enter into block (execute statements)
4.Updation(inc/dec)
Synatx
for(initialization;condition;inc/dec)
{
---------------------
---------------------
}
Write a java program to print 1 to 10 numbers.
for(int i=1;i<=10;i++)
{
System.out.println(i);
}
2.While Loop
while loop is used to execute multiple statements until condition become false
When we DONOT know number of iterations go for while loop.
syntax
initialization
while(cond)
{
---------------
---------------
inc/dec
int i=0;
while(i<11)
{
System.out.println(i);
i++;
}
}
do while loop is used to execute multiple statements until condition become false
intialization
do
{
--------------
-------------
inc/dec
}
while(cond);
int i=5;
do
{
System.out.println(i);
i++;
}
while(i<=10);
Nested Loops
int num=123;
int cd=0;
while(num>0)
{
int rem=num%10;
cd=cd+1;
num=num/10;
}
System.out.println(cd);
int num=123;
int sum=0;
while(num>0)
{
int rem=num%10;
sum=sum+rem;
num=num/10;
}
System.out.println(sum);
int num=123;
int rev=0;
while(num>0)
{
int rem=num%10;
rev=(rev*10)+rem;
num=num/10;
}
System.out.println(rev);
int num=5;
int i=1;
while(i<=10)
{
System.out.println(num+"*"+i+"="+num*i);
i++;
}
Palindrome Number
int num=1221;
int ori=num;
int rev=0;
while(num>0)
{
int rem=num%10;
rev=rev*10+rem;
num=num/10;
}
if(ori==rev)
{
System.out.println("palindrome");
}
else
{
System.out.println("Not palindrome");
Sum of nth power of each digit of a number and that is equal to the original number.
int num=153;
int ori=num;
int sum=0;
while(num>0)
{
int rem=num%10;
sum=sum+(rem*rem*rem);
num=num/10;
}
if(ori==sum)
{
System.out.println("Armstrong");
}
else
{
System.out.println("Not Armstrong");
class Armstrong
{
public static void main(String[] args)
{
int num=153;
int t1=num;
int len=0;
while(t1>0)
{
len=len+1;
t1=t1/10;
}
System.out.println(len);
int t2=num;
int sum=0;
while(t2>0)
{
int mul=1;
int rem=t2%10;
for(int i=1;i<=len;i++)
{
mul=mul*rem;
}
sum=sum+mul;
}
if(sum==num)
{
System.out.println("Armstrong");
}
else
{
System.out.println("Not Armstrong");
int num=1634;
int temp=num;
int sum=0;
int count=0;
while(temp>0)
{
temp=temp/10;
count=count+1;
}
temp=num;
while(temp>0)
{
int rem=temp%10;
sum+=(Math.pow(rem,count));
temp=temp/10;
}
if(num==sum)
{
System.out.println("Armstrong");
}
else
{
System.out.println("Not Armstrong");
Strong Number
Sum of factorial of a digit is equal to the given number is called strong number.
int n=145;
int sum=0;
int ori=n;
while(ori>0)
{
int rem=ori%10;
int f=1;
for(int i=1;i<=rem;i++)
{
f=f*i;
}
sum=sum+f;
ori=ori/10;
}
if(n==sum)
{
System.out.println("Strong");
}
else
{
System.out.println("Not Strong");
}
int n=123;
int sum=0;
while(n>0)
{
int rem=n%10;
sum=sum+(rem*rem);
n=n/10;
}
System.out.println(sum);===>14
int n=123;
int sum=0;
while(n>0)
{
int rem=n%10;
sum=sum+(rem*rem*rem);
n=n/10;
}
System.out.println(sum);===>14
10.>Write a java program to print sum of first and last digits of a number.
int n=45678;
int last=n%10;
while(n>=10)
{
n=n/10;
}
System.out.println(last+n);=======>12
Programs on forloop
Factor
A number that divides a given number exactly the remainder is zero is called factor.
int n=6;
for(int i=1;i<=n;i++)
{
if(n%i==0)
{
System.out.println(i);
}
}
2.>Write a java program to print factorial of number.
Factorial of Number
Factorial of Number is a product of 1 to given number.
int n=7;
int factorial=1;
for(int i=1;i<=n;i++)
{
factorial=factorial*i;
}
System.out.println(factorial);
Prime Number
int n=9;
int count=0;
for(int i=1;i<=n;i++)
{
if(n%i==0)
{
count=count+1;
}
}
if(count==2)
{
System.out.println("prime");
}
else
{
System.out.println("Not prime");
Perfect Number
int n=6;
int ori=n;
int sum=0;
for(int i=1;i<n;i++)
{
if(n%i==0)
{
sum=sum+i;
}
}
if(sum==ori)
{
System.out.println("perfect");
}
else
{
System.out.println("Not perfect");
Fibonacci Series
The sum of 1st and 2nd and then 2nd number will become 1st and sum will become 2nd.
int first=0;
int second=1;
System.out.println(first);
System.out.println(second);
for(int i=2;i<=10;i++)
{
int sum=first+second;
System.out.println(sum);
first=second;
second=sum;
}
pattern programs
1>Square
*****
*****
*****
*****
*****
for(int i=1;i<=5;i++)
{
for(int j=1;j<=5;j++)
{
System.out.print("*");
}
System.out.println();
}
2.Incrementing Traingle
*
**
***
****
*****
for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print("*");
}
System.out.println();
}
3.>Decrementing Traingle
*****
****
***
**
*
for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
System.out.print("*");
}
System.out.println();
}
1
12
123
1234
12345
for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(j);
}
System.out.println();
}
1
22
333
4444
55555
for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(i);
}
System.out.println();
}
1
23
456
78910
1112131415
int c=1;
for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(c);
c++;
}
System.out.println();
}
1
21
321
4321
54321
for(int i=1;i<=5;i++)
{
for(int j=i;j>=1;j--)
{
System.out.print(j);
}
System.out.println();
}
5
54
543
5432
54321
for(int i=5;i>=1;i--)
{
for(int j=5;j>=i;j--)
{
System.out.print(j);
}
System.out.println();
}
5
44
333
2222
11111
for(int i=5;i>=1;i--)
{
for(int j=5;j>=i;j--)
{
System.out.print(i);
}
System.out.println();
}
5
45
345
2345
12345
for(int i=5;i>=1;i--)
{
for(int j=i;j<=5;j++)
{
System.out.print(j);
}
System.out.println();
}
12345
2345
345
45
5
for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
System.out.print(j);
}
System.out.println();
}
11111
2222
333
44
5
for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
System.out.print(i);
}
System.out.println();
}
*
**
***
****
*****
for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
System.out.print(" ");
}
for(int k=1;k<=i;k++)
{
System.out.print("*");
}
System.out.println();
}
1
12
123
1234
12345
for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
System.out.print(" ");
}
for(int k=1;k<=i;k++)
{
System.out.print(k);
}
System.out.println();
}
1
22
333
4444
55555
for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
System.out.print(" ");
}
for(int k=1;k<=i;k++)
{
System.out.print(i);
}
System.out.println();
}
1
21
321
4321
54321
for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
System.out.print(" ");
}
for(int k=i;k>=1;k--)
{
System.out.print(k);
}
System.out.println();
}
12345*
2345**
345***
45****
5*****
for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
System.out.print(j);
}
for(int k=1;k<=i;k++)
{
System.out.print("*");
}
System.out.println();
}
123451
234512
345123
451234
512345
for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
System.out.print(j);
}
for(int k=1;k<=i;k++)
{
System.out.print(i);
}
System.out.println();
}
*
***
*****
*******
*********
for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
System.out.print(" ");
}
for(int k=1;k<i;k++)
{
System.out.print("*");
}
for(int r=1;r<=i;r++)
{
System.out.print("*");
}
System.out.println();
*
1**
12***
123****
1234*****
for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
System.out.print(" ");
}
for(int k=1;k<i;k++)
{
System.out.print(k);
}
for(int r=1;r<=i;r++)
{
System.out.print("*");
}
System.out.println();
1
*12
**123
***1234
****12345
for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
System.out.print(" ");
}
for(int k=1;k<i;k++)
{
System.out.print("*");
}
for(int r=1;r<=i;r++)
{
System.out.print(r);
}
System.out.println();
1
112
12123
1231234
123412345
for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
System.out.print(" ");
}
for(int k=1;k<i;k++)
{
System.out.print("*");
}
for(int r=1;r<=i;r++)
{
System.out.print(r);
}
System.out.println();
1
222
33333
4444444
555555555
for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
System.out.print(" ");
}
for(int k=1;k<i;k++)
{
System.out.print(i);
}
for(int r=1;r<=i;r++)
{
System.out.print(i);
}
System.out.println();
*********
*******
*****
***
*
for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(" ");
}
for(int k=i;k<5;k++)
{
System.out.print("*");
}
for(int r=i;r<=5;r++)
{
System.out.print("*");
}
System.out.println();
}
1234*****
234****
34***
4**
*
for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(" ");
}
for(int k=i;k<5;k++)
{
System.out.print(k);
}
for(int r=i;r<=5;r++)
{
System.out.print("*");
}
System.out.println();
}
****12345
***2345
**345
*45
5
for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(" ");
}
for(int k=i;k<5;k++)
{
System.out.print("*");
}
for(int r=i;r<=5;r++)
{
System.out.print(r);
}
System.out.println();
}
123412345
2342345
34345
445
5
for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(" ");
}
for(int k=i;k<5;k++)
{
System.out.print(k);
}
for(int r=i;r<=5;r++)
{
System.out.print(r);
}
System.out.println();
}
111111111
2222222
33333
444
5
for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(" ");
}
for(int k=i;k<5;k++)
{
System.out.print(i);
}
for(int r=i;r<=5;r++)
{
System.out.print(i);
}
}
*
**
***
****
*****
*****
****
***
**
*
for(int i=1;i<=5;i++)
{
for(int j=i;j<=5;j++)
{
System.out.print(" ");
}
for(int k=1;k<=i;k++)
{
System.out.print("*");
}
System.out.println();
}
for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(" ");
}
for(int k=i;k<=5;k++)
{
System.out.print("*");
}
System.out.println();
Jumping statements
Jumping statements are used to terminate loop and skip the particular iteration of a loop.
Jumping statements are divided into 2 types.They are
1.break
2.continue
Jumping Statements must be applied on loops.
1.break
for(int i=1;i<=10;i++)
{
if(i==6)
{
break;
}
else
{
System.out.println(i);
}
}
2.continue
continue statement is used to skip the iteration(element) and executes remaining elements.
for(int i=1;i<=10;i++)
{
if(i==6)
{
continue;
}
else
{
System.out.println(i);
}
}
Arrays
2.Array Initialization
datatype[] arrayvarname={ele1,ele2,ele3,.....};
int[] arr={2,3,4,5};
5.Arrays is index based it supports only positive index starts from 0 and
size-1.
Negative index is not supports===>ArrayIndexOutOfBoundsException
int[] arr={2,3,4,5};
System.out.println(arr[0])=====>2
System.out.println(arr[2])=====>4
System.out.println(arr[-3])=====>ArrayIndexOutOfBoundsException
forloop
1.contains Initialization.
2.contains condition.
3.contains updation
enchance forloop
import java.util.Arrays;
Here java===>package
util===>sub package
Arrays==>class.
Examples
1.class Rohit
{
public static void main(String[] args)
{
int[] ab=new int[4];
ab[0]=2;
ab[1]=4;
ab[2]=6;
ab[3]=8;
System.out.println(ab);============>[I@372f7a8d
}
}
class Rohit
{
public static void main(String[] args)
{
int[] ab=new int[4];
ab[0]=2;
ab[1]=4;
ab[2]=6;
ab[3]=8;
for(int i=0;i<=3;i++)
{
System.out.println(ab[i]);
}
}
}
class Rohit
{
public static void main(String[] args)
{
int[] ab=new int[4];
ab[0]=2;
ab[1]=4;
ab[2]=6;
ab[3]=8;
ab[4]=10;======>ArrayIndexOutOfBoundsException
for(int i=0;i<=3;i++)
{
System.out.println(ab[i]);
}
}
}
class Rohit
{
public static void main(String[] args)
{
int[] ab=new int[4];
ab[-1]=2;
System.out.println(ab[-1]);===>ArrayIndexOutOfBoundsException
}
}
class Rohit
{
public static void main(String[] args)
{
byte[] b=new byte[3];
b[0]=4;
b[1]=1;
b[2]=6;
for(int i=0;i<=2;i++)
{
System.out.println(b[i]);
}
}
}
class Sample
{
public static void main(String[] args)
{
int[] ab=new int[3];
ab[0]=2;
ab[1]=3;
ab[2]=4;
int l=ab.length;
System.out.println(l);
}
}
class Sample
{
public static void main(String[] args)
{
int[] ch=new int[4];
ch[0]=6;
ch[1]=2;
ch[2]=4;
ch[3]=7;
for(int i=0;i<ch.length;i++)
{
System.out.println(ch[i]);
}
}
}
class Sample
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
System.out.println(a);===>[I@372f7a8d
}
}
}
}
program to print index of an array.
class Sample
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
for(int i=0;i<a.length;i++)
{
System.out.println(i);
}
}
}
}
}
predefine methods
The methods which are already present in java software.The methods which are
developed by java developers.
import java.util.Arrays
userdefine methods
The methods which are not present in java software.The methods which are
developed by java programmers.
1.sort()
syntax
Arrays.sort(arrayvarname);
import java.util.Arrays;
class Sample
{
public static void main(String[] args)
{
int[] a={6,3,2,1};
Arrays.sort(a);
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
}
}
2.toString()
syntax
Arrays.toString(arrayvarname);
import java.util.Arrays;
class Demo
{
public static void main(String[] args)
{
int[] a={2,3,1,4};
System.out.println(Arrays.toString(a));======>[2, 3, 1, 4]
}
}
3.equals()
syntax
-------
boolean varname=Arrays.equals(arrvarnam1,arrvarnam2)
import java.util.Arrays;
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
int[] b={1,2,3,4};
boolean res=Arrays.equals(a,b);
System.out.println(res);==================>true
}
}
import java.util.Arrays;
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
int[] b={1,2,3,4,5};
boolean res=Arrays.equals(a,b);
System.out.println(res);============>false
}
}
import java.util.Arrays;
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
int[] b={1,2,4,3};
boolean res=Arrays.equals(a,b);
System.out.println(res);================>false
}
}
4.mismatch()
syntax
-------
int varname= Arrays.mismatch(arrayvarname1,arrayvarmae2);
import java.util.Arrays;
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
int[] b={1,2,3,4};
int abc=Arrays.mismatch(a,b);
System.out.println(abc);==================>-1
}
}
import java.util.Arrays;
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
int[] b={5,2,3,4};
int abc=Arrays.mismatch(a,b);
System.out.println(abc);========================>0
}
}
import java.util.Arrays;
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
int[] b={1,2,8,4};
int abc=Arrays.mismatch(a,b);
System.out.println(abc);=====================>2
}
}
5.binarySearch()
syntax
-------
int varname=Arrays.binarySearch(arrayvarname,element);
import java.util.Arrays;
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
int bhavadeesh=Arrays.binarySearch(a,3);
System.out.println(bhavadeesh);================>2
}
}
import java.util.Arrays;
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
int bhavadeesh=Arrays.binarySearch(a,4);
System.out.println(bhavadeesh);=================>3
}
}
import java.util.Arrays;
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
int bhavadeesh=Arrays.binarySearch(a,6);===========>-5
System.out.println(bhavadeesh);
}
}
import java.util.Arrays;
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
int bhavadeesh=Arrays.binarySearch(a,0);
System.out.println(bhavadeesh);=================>-1
}
}
import java.util.Arrays;
class Demo
{
public static void main(String[] args)
{
int[] a={2,4,7,8,9,10};
int bhavadeesh=Arrays.binarySearch(a,5);
System.out.println(bhavadeesh);================>-3
}
}
import java.util.Arrays;
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4};
int bhavadeesh=Arrays.binarySearch(a,5);
System.out.println(bhavadeesh);=====================>-5
}
}
6.copyOfRange()
copyOfRange() is used to copy array elements from 1 array into another array.
syntax
------
datatype[] varname=Arrays.copyOfRange(arrayvarname,startindex,endindex);
import java.util.Arrays;
class Demo
{
public static void main(String[] args)
{
int[] onearray={2,4,7,8,9,10};
int l=onearray.length;
int[] anotherarr=Arrays.copyOfRange(onearray,0,l-1);
System.out.println(Arrays.toString(anotherarr));===>[2,4,7,8,9]
}
}
import java.util.Arrays;
class Demo
{
public static void main(String[] args)
{
int[] onearray={2,4,7,8,9,10};
int l=onearray.length;
int[] anotherarr=Arrays.copyOfRange(onearray,0,3);
System.out.println(Arrays.toString(anotherarr));======>[2,4,7]
}
}
import java.util.Arrays;
class Demo
{
public static void main(String[] args)
{
int[] onearray={2,4,7,8,9,10};
int l=onearray.length;
int[] anotherarr=Arrays.copyOfRange(onearray,2,4);
System.out.println(Arrays.toString(anotherarr));=======>7,8
}
}
int[] a={2,1,4,5,6};
System.out.println(a[0]);========================>2
System.out.println(a[1]);========================>1
System.out.println(a[a.length-1]);===============>6
a[5-1]
a[4]==========================>6
2.write a java program to print to add 1st and last element of an array.
int[] a={2,1,4,5,6};
int first=a[0];
int last=a[a.length-1];
System.out.println(first+last);
3.write a java program to swap to 1st and last element of an array.
import java.util.*;
class Demo
{
public static void main(String[] args)
{
int[] a={2,1,4,5,6};
int temp=a[0];
a[0]=a[a.length-1];
a[a.length-1]=temp;
System.out.println(a[0]);
System.out.println(a[a.length-1]);
System.out.println(Arrays.toString(a));
}
}
int[] arr={1,2,3,4,5};
for(int i=0;i<arr.length;i++)
{
if(arr[i]%2!=0)
{
System.out.println(arr[i]);
}
}
int[] arr={1,7,6,5,2,4};
int count=0;
for(int i=0;i<arr.length;i++)
{
if(arr[i]%2==0)
{
count++;
}
}
System.out.println(count);
int[] a={1,2,3};
int sum=0;
for(int i=0;i<a.length;i++)
{
sum=sum+a[i];
}
System.out.println(sum);
}
}
if(count==2)
{
System.out.println(a[i]);
}
}
int[] arr={2,4,3,1};
for(int i=arr.length-1;i>=0;i--)
{
System.out.println(arr[i]);
}
int[] a={1,2,3,1};
for(int i=0;i<a.length;i++)
{
for(int j=i+1;j<a.length;j++)
{
if(a[i]==a[j])
{
System.out.println(a[i]);
}
}
}
int[] a={1,2,3,1,2,1};
for(int i=0;i<a.length;i++)
{
for(int j=i+1;j<a.length;j++)
{
if((a[i]!=0)&&(a[i]==a[j]))
{
System.out.println(a[i]);
a[j]=0;
break;
}
}
}
int[] a={1,2,3,1,2,1};
for(int i=0;i<a.length;i++)
{
int x=a[i];
boolean f=false;
for(int j=i+1;j<a.length;j++)
{
if(x!=9292 && a[i]==a[j])
{
a[j]=9292;
f=true;
}
}
if(f==true)
{
System.out.println(a[i]);
}
}
int[] a={5,4,1,2};
for(int i=0;i<a.length;i++)
{
for(int j=i+1;j<a.length;j++)
{
if(a[i]>a[j])
{
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
for(int k=0;k<a.length;k++)
{
System.out.println(a[k]);
}
int[] a={1,5,4,3,2};
for(int i=0;i<a.length;i++)
{
for(int j=i+1;j<a.length;j++)
{
if(a[i]>a[j])
{
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
System.out.println(a[a.length-1]);
int[] a={2,1,3,5,6};
int max=a[0];
for(int i=1;i<a.length;i++)
{
if(a[i]>max)
{
max=a[i];
}
}
System.out.println(max);
int[] a={1,5,4,3,2};
for(int i=0;i<a.length;i++)
{
for(int j=i+1;j<a.length;j++)
{
if(a[i]>a[j])
{
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
System.out.println(a[a.length-2]);
int[] a1={1,2,3,4,5};
int[] a2=new int[a1.length];
for(int i=0;i<a1.length;i++)
{
a2[i]=a1[i];
System.out.println(a2[i]);
}
16.write a java program to print even numbers in left side and odd numbers in right
side.
int[] a1={1,2,3,4,5,6,7,8,9,10};
int[] output=new int[a1.length];
int evenindex=0;
int oddindex=a1.length-1;
for(int i=0;i<a1.length;i++)
{
if(a1[i]%2==0)
{
output[evenindex]=a1[i];
evenindex++;
}
else
{
output[oddindex]=a1[i];
oddindex--;
}
}
for(int anything : output)
{
System.out.println(anything);
}
18.Write a java program to shift array elements to left side and first element to last.
import java.util.*;
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,4,5};
int first=a[0];
for(int i=0;i<a.length-1;i++)
{
a[i]=a[i+1];
}
a[a.length-1]=first;
System.out.println(Arrays.toString(a));
}
}
int[] a={7,9,10,11,2};
int max=a[a.length-1];
System.out.println(max);
for(int i=a.length-2;i>=0;i--)
{
if(a[i]>max)
{
System.out.println(a[i]);
max=a[i];
}
}
20.Write a java program to merge to arrays and copy into another array.
int[] a={1,2,3};
int[] b={4,5,6};
int l1=a.length;
int l2=b.length;
int[] c=new int[l1+l2];
for(int i=0;i<a.length;i++)
{
c[i]=a[i];
}
int an=l1;
for(int j=0;j<b.length;j++)
{
c[an]=b[j];
an++;
}
System.out.println(Arrays.toString(c));
import java.util.*;
class Demo
{
public static void main(String[] args)
{
int[] a={1,2,3,1,2,1};
for(int i=0;i<a.length;i++)
{
for(int j=i+1;j<a.length;j++)
{
if(a[i]==a[j])
{
a[j]=0;
}
}
}
System.out.println(Arrays.toString(a));
for(int j=0;j<a.length;j++)
{
if(a[j]!=0)
{
System.out.println(a[j]);
}
}
}
}
22.Write a java program to print all pair of elements whose sum equals to 10.
int[] a={6,3,9,1,2,8,4,5};
for(int i=0;i<a.length-1;i++)
{
for(int j=i+1;j<a.length;j++)
{
if(a[i]+a[j]==10) 6,4
{ 9,1
System.out.println(a[i]+" "+a[j]); 8,2
}
}
}
int[] a={1,2,3,4,5};
for(int i=0;i<a.length;i++)
{
for(int j=i;j<a.length;j++)
{
for(int k=i;k<=j;k++)
{
System.out.print(a[k]);
}
System.out.println();
}
24.Write a java program to print possible sub arrays where target sum=9
int[] a={1,2,3,4,5};
int target=9;
int max=Integer.MIN_VALUE;
for(int i=0;i<a.length;i++)
{
int sum=0;
for(int j=i;j<a.length;j++)
{
sum=sum+a[j];
if(sum==target)
{
for(int k=i;k<=j;k++)
{
System.out.print(a[k]);
}
System.out.println();
}
}
int[] a={5,3,1,2};
int n=a.length+1;
int sum=n*(n+1)/2;
int restSum=0;
for (int i = 0; i < a.length; i++) {
restSum+=a[i];
}
int missingNumber=sum-restSum;
System.out.println(missingNumber);
Multidimensional Arary
class Demo
{
public static void main(String[] args)
{ r c
int[][] v=new int[3][3];
for(int i=0;i<3;i++)=================>rows
{
for(int j=0;j<3;j++)=============>columns
{
System.out.print(v[i][j]);
}
System.out.println();==================>000
} 000
} 000
}
class Demo
{
public static void main(String[] args)
{
int[][] v=new int[3][3];
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.println(v[i][j]);=================>
}
}
}
}
0
0
0
0
0
0
0
0
0
class Demo
{
public static void main(String[] args)
{
int[][] a=new int[2][3];
a[0][0]=1;
a[0][1]=2;
a[0][2]=3;
a[1][0]=4;
a[1][1]=5;
a[1][2]=6;
for(int i=0;i<2;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(a[i][j]);
}
System.out.println();
}
}
}
class Demo
{
public static void main(String[] args)
{
int[][] a={{1,2,3},{4,5,6}};
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[i].length;j++)
{
System.out.print(a[i][j]);
}
System.out.println();
}
}
}
jagged Array
class Demo
{
public static void main(String[] args)
{
int[][] a={{1,2,3,7},{4,5,6}};
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[i].length;j++)
{
System.out.print(a[i][j]);
}
System.out.println();
}
}
}
int[][] a={{1,2},{3,4}};
int[][] b={{5,6},{7,8}};
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[i].length;j++)
{
System.out.print(a[i][j]+b[i][j]+" ");
}
System.out.println();
}
int[][] a={{5,6},{7,8}};
int[][] b={{1,2},{2,4}};
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[i].length;j++)
{
System.out.print(a[i][j]-b[i][j]+" ");
}
System.out.println();
}
int[][] a={{1,2},{3,4}};
int[][] b={{1,1},{1,1}};
int[][] c=new int[2][2];
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
c[i][j]=0;
for(int k=0;k<2;k++)
{
c[i][j]+=a[i][k]*b[j][k];
}
System.out.print(c[i][j]+" ");
}
System.out.println();
}
String Handling
1.String
2.StringBuffer
3.StringBuilder
4.StringTokenizer
Note:String,StringBuffer,StringBuilder is present in java.lang package(bydefault).
1.String
String s1="pawan";
System.out.println(s1);===============================>pawan
System.out.println(System.identityHashCode(s1));==========>359023572
String s2="pawan";
System.out.println(s2);===============================>pawan
System.out.println(System.identityHashCode(s2));==========>359023572
String s1="pawan";
System.out.println(s1);
System.out.println(System.identityHashCode(s1));
String s2="pawan";
System.out.println(s2);
System.out.println(System.identityHashCode(s2));
System.out.println(s1.equals(s2));==============================>true
System.out.println(s1==s2);=====================================>true
System.out.println("===================================");
String s3=new String("pawan");
System.out.println(s3);
System.out.println(System.identityHashCode(s3));
String s4=new String("pawan");
System.out.println(s4);
System.out.println(System.identityHashCode(s4));
System.out.println(s3.equals(s4));========================>true
System.out.println(s3==s4);===============================>false
immutable
Examples
1.
String sname="Hemanth Kumar";
System.out.println(sname);===================>Hemanth Kumar
1.charAt()
syntax
datatype varname=stringvarname.charAt(index);
String s="Hemanth";
char abc=s.charAt(3);
System.out.println(abc);========>a
2.indexOf()
syntax
datatype varname=svn.indexOf(character);
String s="Hemanth";
int ad=s.indexOf('a');
System.out.println(ad);===============>3
String s="Haemanth";
int ad=s.indexOf('a');
System.out.println(ad);===============>1
3.lastIndexOf()
syntax
datatype varname=svn.lastIndexOf(character)
String s="Haemanth";
int b=s.lastIndexOf('a');
System.out.println(b);================>4
4.substring()
substring() is used to get particular characters by passing startindex and end index.
syntax
datatype varname=svn.substring(startindex,endindex);
String s="Hemanth";
int len=s.length();
System.out.println(len);
String xyz=s.substring(0,len);
System.out.println(xyz);
String s="Hemanth";
String xyz=s.substring(4);
System.out.println(xyz);============>nth
5.length()
syntax
datatype varname=svn.length();
String s="Hemanth";
int len=s.length();
System.out.println(len);=============>7
6.split()
syntax
datatype[] varname=svn.split(character);
String s="Heman kuma rah";
String[] abc=s.split(" ");
System.out.println(Arrays.toString(abc));==========>[Heman,kuma,rah]
String s="Hemankumarah";
String[] abc=s.split("a");
System.out.println(Arrays.toString(abc));==========>[Hem,nkum,r,h]
7.toCharArray()
datatype[] varname=svn.toCharArray();
String s="Durga";
char[] vn=s.toCharArray();
System.out.println(Arrays.toString(vn));=========>[D,u,r,g,a]
8.equals()
syntax
datatype varname=svn1.equals(svn2)
String s1="virat";
String s2="virat";
boolean anc=s1.equals(s2);
System.out.println(anc);================>true
String s1="vIrat";
String s2="virat";
boolean anc=s1.equals(s2);
System.out.println(anc);=============>false
9.equalsIgnoreCase()
syntax
datatype varname=svn1.equals(svn2)
String s1="virat";
String s2="virat";
boolean anc=s1.equalsIgnoreCase(s2);
System.out.println(anc);================>true
String s1="vIrat";
String s2="virat";
boolean anc=s1.equalsIgnoreCase(s2);
System.out.println(anc);=============>true
10.concat()
datatype varname=svn.concat();
String s1="virat";
String s2="kohli";
String fullname=s1.concat(s2);
System.out.println(fullname);==============>viratkohli
String s1="virat";
String fullname=s1.concat("kohli");
System.out.println(fullname);==============>viratkohli
11.parseInt()
syntax
datatype varname=Integer.parseInt(svn);
String s="123";
System.out.println(s+5);======>1235
int a=Integer.parseInt(s);
System.out.println(a+5);=====>128
String s="onetwothree";
System.out.println(s);
int a=Integer.parseInt(s);
System.out.println(a);=================>NumberFormatException
12.valueOf()
syntax
datatype varname=String.valueOf(intvarname)
int a=123;
String s=String.valueOf(a);
System.out.println(s);=============>123
13.startsWith()
startsWith() returns either true(if sequence of characters are matched) or false(if sequence of characters are not
matched)
syntax
datatype varname=svn.startsWith(char);
String s="dhoni";
boolean vn=s.startsWith("d");
System.out.println(vn);===========>true
String s="dhoni";
boolean vn=s.startsWith("dho");
System.out.println(vn);=========>true
String s="dhoni";
boolean vn=s.startsWith("ho");
System.out.println(vn);========>false
13.endsWith()
endsWith() returns either true(if sequence of characters are matched) or false(if sequence of characters are not
matched)
syntax
datatype varname=svn.startsWith(char);
String s="dhoni";
boolean vn=s.endsWith("i");
System.out.println(vn);===========>true
String s="dhoni";
boolean vn=s.endsWith("ni");
System.out.println(vn);=========>true
String s="dhoni";
boolean vn=s.endsWith("ho");
System.out.println(vn);========>false
14.replace()
syntax
datatype varname=svn.replace(oldchar,newchar)
String s="roshan";
String res=s.replace('r','t');
System.out.println(res);==============>toshan
15.replaceAll()
syntax
datatype varname=svn.replaceAll(oldcharacters,newcharacters)
String s="roshan";
String res=s.replaceAll("ros","tra");
System.out.println(res);============>trahan
16.toUpperCase()
17.toLowerCase()
String s="RosHan";
String s2=s.toLowerCase();
System.out.println(s2);===============>roshan
18.hashCode()
syntax
datatype varname=svn.hashCode();
String s="roshan";
int xyz=s.hashCode();
System.out.println(xyz);===========>-925204225
2.StringBuffer
StringBuffer s="virat";
System.out.println(s);==============>error
4.StringBuffer is mutable.
5.StringBuffer is synchronized.
6.StringBuffer is thread safe.
1.append()
syntax
datatype varname=sbvn.append(string);
String s="virat";
String s2=s.append("kohli");
System.out.println(s2);========================>error
2.insert()
syntax
datatype varname=sbvn.insert(index,char);
3.delete()
syntax
datatype varname=sbvn.delete(startindex,endindex);
StringBuffer s=new StringBuffer("Bhavadeesh");
StringBuffer s2=s.delete(1,4);
System.out.println(s2);=========>Badeesh
4.reverse()
syntax
datatype varname=sbvn.reverse();
StringBuffer s=new StringBuffer("Bhavadeesh");
StringBuffer s2=s.reverse();
System.out.println(s2);============>hseedavahB
String s="virat";
StringBuffer s2=new StringBuffer(s);
StringBuffer s3=s2.reverse();
System.out.println(s3);
Write a java program to prove that String is immutable and StringBuffer is mutable
String s="virat";
s.concat("kohli");
System.out.println(s);=================================>virat
System.out.println("=========================");
StringBuffer s2=new StringBuffer("Mahesh");
s2.append("Babu");
System.out.println(s2);==============================>Mahesh Babu
String s="virat";
System.out.println(s.hashCode());=========================>112216210
String s2=s.concat("kohli");
System.out.println(s2.hashCode());========================>-2089279825
System.out.println("=====================");
StringBuffer s3=new StringBuffer("Rohit");
System.out.println(s3.hashCode());========================>305808283
3.StringBuilder
StringBuilder s="virat";
System.out.println(s);==============>error
4.StringBuilder is mutable.
5.StringBuilder is not synchronized.
6.StringBuilder is not thread safe.
4.StringTokenizer
1.hasMoreElements()(condition)
2.nextElement()(output)
import java.util.*;
class Demo
{
public static void main(String[] args)
{
StringTokenizer s=new StringTokenizer("vi_ra_ta","_");
System.out.println(s.countTokens());
while(s.hasMoreElements())
{
System.out.println(s.nextElement());
}
}
}
import java.util.*;
class Demo
{
public static void main(String[] args)
{
StringTokenizer s=new StringTokenizer("virat");
System.out.println(s);====================================>java.util.StringTokenizer@5e265ba
4
}
}
programs on Strings
String s="virat";
if((s.charAt(0)=='a')||(s.charAt(0)=='e')||(s.charAt(0)=='i')||
(s.charAt(0)=='o')||(s.charAt(0)=='u')||(s.charAt(0)=='A')||
(s.charAt(0)=='E')||(s.charAt(0)=='I')||(s.charAt(0)=='O')||
(s.charAt(0)=='U'))
{
System.out.println("vowel");
}
else
{
System.out.println("Not vowel");
}
String s="virat";
for(int i=0;i<s.length();i++)
{
if((s.charAt(i)=='a')||(s.charAt(i)=='e')||(s.charAt(i)=='i')||
(s.charAt(i)=='o')||(s.charAt(i)=='u')||(s.charAt(i)=='A')||
(s.charAt(i)=='E')||(s.charAt(i)=='I')||(s.charAt(i)=='O')||
(s.charAt(i)=='U'))
{
System.out.println("vowel");
}
else
{
System.out.println("consonant");
}
}
3.Write a java program to take 1 string data store in s1 and take empty string s2 copy s1 data in
s2.
String s1="virat";
String s2="";
for(int i=0;i<s1.length();i++)
{
s2=s2+s1.charAt(i);
}
System.out.println(s2);
String s1="virat";
String s2="";
for(int i=s1.length()-1;i>=0;i--)
{
s2=s2+s1.charAt(i);
}
System.out.println(s2);
String s1="madam";
String s2="";
for(int i=s1.length()-1;i>=0;i--)
{
s2=s2+s1.charAt(i);
}
if(s1.equals(s2))
{
System.out.println("palindrome");
}
else
{
System.out.println("Not palindrome");
}
}
System.out.println(alpha);
System.out.println(digit);
System.out.println(symbol);
String s="BhavI";
String res="";
for(int i=0;i<s.length();i++)
{
char ch=s.charAt(i);
if(ch>='A' && ch<='Z')
{
res=res+(char)+(ch+32);
}
else
{
res=res+ch;
}
}
System.out.println(res);
}
System.out.println(s[index]);
String s="ababac";
for(char ch='a';ch<='z';ch++)
{
int count=0;
for(int i=0;i<s.length();i++)
{
char nc=s.charAt(i);
if(nc==ch)
{
count=count+1;
}
}
if(count>0)
{
System.out.println(ch+":"+count);
}
}
String s="aabbabcc";
int[] count=new int[256];
for(int i=0;i<s.length();i++)
{
count[(int)s.charAt(i)]++;
}
for(int i=0;i<count.length;i++)
{
if(count[i]!=0)
{
System.out.println((char)i+" : "+count[i]);
}
}
String s="ababac";
for(char ch='a';ch<='z';ch++)
{
int count=0;
for(int i=0;i<s.length();i++)
{
char nc=s.charAt(i);
if(nc==ch)
{
count=count+1;
}
}
if(count>1)
{
System.out.println(ch+":"+count);
}
}
String s="ababac";
for(char ch='a';ch<='z';ch++)
{
int count=0;
for(int i=0;i<s.length();i++)
{
char nc=s.charAt(i);
if(nc==ch)
{
count=count+1;
}
}
if(count==1)
{
System.out.println(ch+":"+count);
}
}
class Demo
{
public static void main(String[] args)
{
String s="abc";
for(char x='a';x<='c';x++)
{
for(char y='a';y<='c';y++)
{
for(char z='a';z<='c';z++)
{
if(x!=y && y!=z && z!=x)
{
System.out.println(x+" "+y+" "+z);
}
}
}
}
}
}
Scanner
int a=sc.nextInt();
System.out.println("output is"+a);============>output is 12
}
}
import java.util.*;
class Sample
{
public static void main(String[] args)
{
Scanner s1=new Scanner(System.in);
System.out.println("enter float num=");
float num=s1.nextFloat();
System.out.println(num);
}
}
import java.util.Scanner;
class Demo
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("enter num=");
int a=sc.nextInt();
System.out.println("output is"+a);
}
}
import java.util.*;
class Sample
{
public static void main(String[] args)
{
Scanner s1=new Scanner(System.in);
System.out.println("enter double num=");
double num=s1.nextDouble();
System.out.println(num);
}
}
import java.util.*;
class Sample
{
public static void main(String[] args)
{
Scanner s1=new Scanner(System.in);
System.out.println("enter boolean value=");
boolean b=s1.nextBoolean();
System.out.println(b);
}
}
import java.util.*;
class Demo
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("enter char value=");
char ch=sc.next().charAt(0);
System.out.println(ch);
}
}
import java.util.*;
class Demo
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("enter string 1 word=");
String s=sc.next();
System.out.println(s);
}
}
import java.util.*;
class Demo
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("enter string no.of words=");
String s=sc.nextLine();
System.out.println(s);
}
}
}
}
enter size=
3
enter elements
2
4
6
[2, 4, 6]
Methods
1.method heading
3.Formal parameters
4.Actual Arguments
Actual arguments purpose is to send values to(variables) formal parameters in method heading
void
syntax
statements
class Sample
{
void suresh(int a)
{
System.out.println(a);=======================================>8
}
public static void main(String[] args)
{
Sample s1=new Sample();
s1.suresh(8);
}
}
void======================>System.out.println()
Datatype==================>return
class Demo
{
void parithosh(String s)
{
System.out.println(s);
}
public static void main(String[] args)
{
Demo d1=new Demo();
d1.parithosh("virat");
}
}
class Demo
{
void parithosh()
{
System.out.println("method topic started");
}
public static void main(String[] args)
{
Demo d1=new Demo();
d1.parithosh();
}
}
class Sample
{
class Sample
{
int venky(int a)
{
return a;
}
public static void main(String[] args)
{
Sample s1=new Sample();
int res=s1.venky(16);
System.out.println(res);
}
}
class Sample
{
float venky(float a)
{
return a;
}
public static void main(String[] args)
{
Sample s1=new Sample();
float res=s1.venky(16.6f);
System.out.println(res);
}
}
class Sample
{
String hemanth()
{
return "virat is a champ";
}
public static void main(String[] args)
{
Sample s1=new Sample();
String s=s1.hemanth();
System.out.println(s);
}
}
import java.util.*;
class Sample
{
void add(int[] a)
{
System.out.println(Arrays.toString(a));
}
public static void main(String[] args)
{
Sample s1=new Sample();
int[] b={1,2,3,4};
s1.add(b);
}
}
steps to install jdk
class Demo
{
public static void main(String[] args)
{
System.out.println("welcome to java");
}
C:\Users\heman>cd C:
C:\Users\heman
C:\Users\heman>cd /
C:\>cd Durga6pm
C:\Durga6pm>javac Demo.java
C:\Durga6pm>java Demo
welcome to java
1.The arguments which will take at command prompt are called command line arguments.
2.It will take the arguments based on index value.
3.By default arguments will store on String format.
class First
{
public static void main(String[] args)
{
String s1=args[0];
String s2=args[1];
System.out.println(s1+s2);
}
}
C:\Durga6pm>javac First.java
C:\Durga6pm>java First Taj Mahal
TajMahal
class First
{
public static void main(String[] args)
{
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
System.out.println(a+b);
}
}
C:\Durga6pm>javac First.java
C:\Durga6pm>java First 3 4
7
C:\Durga6pm>javac First.java
class First
{
void sample(int a)
{
System.out.println(a);
}
public static void main(String[] args)
{
First f1=new First();
f1.sample(5,6,7);===================>error(expecting only 1 actual argument)
}
}
class First
{
void sample(int... a)
{
System.out.println(a);
}
public static void main(String[] args)
{
First f1=new First();
f1.sample(5,6,7);
}
}
C:\Durga6pm>javac First.java
C:\Durga6pm>java First
[I@372f7a8d
import java.util.*;
class First
{
void sample(int... a)
{
System.out.println(Arrays.toString(a));
}
public static void main(String[] args)
{
First f1=new First();
f1.sample(5,6,7);
}
}
C:\Durga6pm>javac First.java
C:\Durga6pm>java First
[5,6,7]
import java.util.*;
class First
{
void sample(int b,int... a)
{
System.out.println(Arrays.toString(a));
System.out.println(b);
}
public static void main(String[] args)
{
First f1=new First();
f1.sample(5,6,7);
}
}
C:\Durga6pm>javac First.java
C:\Durga6pm>java First
[6, 7]
5
import java.util.*;
class First
{
void sample(int...a,int b)
{
System.out.println(Arrays.toString(a));
System.out.println(b);
}
public static void main(String[] args)
{
First f1=new First();
f1.sample(5,6,7);
}
}
Java features
2.predefine methods
The methods which are already present in java software(jdk).These methods are developed by
java developers.
Examples
1.sqrt()
2.add()
3.max()
4.min()
3.Userpredefine methods
The methods which are not present in java software(jdk).These methods are developed by
java programmers.
Examples
1.bhavadeesh()
2.virat()
3.dhoni()
4.pawan()
class Demo
{
public static void main(String[] args)
{
System.out.println(Math.sqrt(49));===================>7.0
System.out.println(Math.sqrt(81));===================>9.0
System.out.println(Math.pow(2,3));===================>8.0
}
}
A language where we can write program on one platform and we can execute in any platform.
Examples
1.java
2.python
A language where we can write program on one platform and we can execute in same platform.
Examples
1.c
2.c++
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
If we give input in machine understandale language it will gives output in human understandable
language.
Examples
java
python
compiler
1.compiler will converts source code into intermediate code or byte code all at a time
Interpreter
jdk
jre
jvm
1.Strongly typed
-----------------
Compiler will check each and every declaration and assignments at compile time.
Ex
--
int a="virat kohli";
2.Garbage Collector
--------------------
The purpose of Garbage collector removes unwanted memory and improves system performance.
3.Exception Handling
--------------------
The purpose of Exception Handling is to convert abnormal termination into normal termination.
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.
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
In java all.class files wont be loaded at begining and whenever .class file is required then
it is going to load.
The main advantage is program will always get latest version of .class file.
class Student
{
static
{
System.out.println("student class loaded");
}
}
class Test
{
static
{
System.out.println("Test class loaded");
}
}
}
javac Test.java
java Test
Test class loaded
Hello
class Student
{
static
{
System.out.println("student class loaded");
}
}
class Test
{
static
{
System.out.println("Test class loaded");
}
}
}
javac Test.java
java Test
Test class loaded
Hello
Student class loaded
Literals
1.Integer Literals==================>1,2,3...0,-1,-2....
2.Flaoting point literals===========>1.2,1.6,1.8........
3.Character Literals================>'a','b','c',.......
4.Boolean Literals==================>true,false
5.String Literals==================>"virat","dhoni".......
6.Object Literals=================>Null
int a =12;
int=====>datatype
a=======>variable
12======>value
Oops
A language which supports both inheritance and runtime polymorphism then it is called a
object oriented language.
Examples
java,c++,python,.net...........
A language which does not supports inheritance and runtime polymorphism then it is called a
object based language.
Examples
javascript,vbscript........
class
syntax
class classname
{
variables....
methods......
class Demo
{
int a=5;
int b=6;
public static void main(String[] args)
{
}
}
object
1.A variable that is defined outside of a method and without static keyword is called
Instance/non static variable.
2.Instance variables stored in Heap area.
3.Instance varibles can be accessed in 2 ways.
1.By using object
2.By using object refernce
4.Instance variables have default values.
5.The purpose of instance variables is to store different values.
object
object refernce
2.static variable
1.A variable that is defined outside of a method and with static keyword is called static variable.
2.Static variables stored method area.
3.Static variables can be accessed in 4 ways.
1.By using object
2.By using object refernce
3.By using directly.
4.By using class name
4.static varibles have default values.
5.The purpose of static variables is to store common values.
By classname
when static variable name and local variable name both are same if we want to access static
variables then use classname.
When static variables are present multiple classes access by using classname.
3.Local varibles
1.A varible that is defined inside of a method without static keyword is called Local variable.
2.Formal parameters are local variables.
3.Local variables stored in stack area.
4.Local varibles are accessed in 1 way.
1.By using directly.
5.There is no default values for local variables.
6.Local varibles must be initialize.
7.The purpose of local variables is to perform opertions or task.
class Emp
{
int a=12;
}
}
Note:
syntax
Anonymous/unrefernce object
new classname()
new
}
}
class Student
{
int a=12;
}
}
class Student
{
int a=12;
class Emp
{
String s="virat";
public static void main(String[] args)
{
Emp e1=new Emp();
System.out.println(e1.s);
System.out.println(new Emp().s);
}
}
class Emp
{
int s;
String a;
boolean b;
char c;
float d;
public static void main(String[] args)
{
Emp e1=new Emp();
System.out.println(e1.s);
System.out.println(e1.a);
System.out.println(e1.b);
System.out.println(e1.c);
System.out.println(e1.d);
}
}
output
0
null
false
.
o.o
class Emp
{
static int a=56;
public static void main(String[] args)
{
Emp e1=new Emp();
System.out.println(e1.a);
System.out.println (new Emp().a);
System.out.println(a);
System.out.println(Emp.a);
}
}
class Emp
{
}
}
class Emp
{
class StudentInfo
{
static String iname="Durga";
int sno;
String sname;
long mobile;
}
}
class A
{
static int a=6;
}
class B
{
static int c=9;
public static void main(String[] args)
{
System.out.println(c);
System.out.println(A.a);
}
}
Methods
1.Instance methods
1.The methods which is defined without static keyword then it is called Instance method.
2.The purpose of Instance methods is to perform different task and produce code resuability.
3.Instance methods can be accessed in 2ways.
1.By using object
2.By using object refernce.
class Demo
{
void m1()
{
System.out.println("welcome to instance");
}
public static void main(String[] args)
{
Demo d1=new Demo();
d1.m1();
new Demo().m1();
}
}
2.static methods
1.The methods which is defined with static keyword then it is called static method.
2.The purpose of static methods is to perform common task and produce code resuability.
3.static methods can be accessed in 4 ways.
1.By using object
2.By using object refernce.
3.By using directly.
4.By using classname.
class Demo
{
static void m1()
{
System.out.println("welcome to static");
}
public static void main(String[] args)
{
Demo.m1();
m1();
}
}
Blocks
1.Instance blocks.
class Demo
{
{
System.out.println("welcome to instance block");
}
public static void main(String[] args)
{
Demo d1=new Demo();
new Demo();
}
}
2.static blocks.
}
}
}
static {
System.out.println("static block");=========>static block 1
}
public static void main(String[] args)========>main method call
{
int c=14;
System.out.println(c);==================>14 2
m2();
Demo d1=new Demo();
System.out.println(d1.a);=============>12 5
d1.m1();
}
}
Inheritance
1.The process of creating new class of existing class by using extends keyword is called Inheritance.
2.Existing class is a super class
3.New class is a sub class.
4.If we create object for super class we can access only super class variables or methods.
5.If we create object for sub class we can access both super and sub class variables and methods.
6.The purpose of Inheritance is to reuse features(variables and methods) from super class to sub class.
7.They are 6 types of Inheritance.They are
1.Single Inheritance
2.Multiple Inheritance
3.Multilvel Inheritance
4.Hierarchical Inheritance
5.Multipath Inheritance
6.Hybrid Inheritance
1.Single Inheritance
2.Multiple Inheritance
3.Multilevel Inheritance
1 sub class derived from 1 intermediate class and that intermediate class is derived from 1 super class.
4.Hierarchical Inheritance
5.Multipath Inheritance
1 sub is derived from multiple intermediate classes and that intermediate classes are derived from 1 super class.
Hierarchical Inheritance is not possible because it follows multiple Inheritance
6.Hybrid Inheritance
single Inheritance
class Chiranjeevi
{
int chiamount=500;
}
class Ramcharan extends Chiranjeevi
{
int ramamount=600;
public static void main(String[] args)
{
}
}
class Vehicle
{
String s="engine";
}
class Car extends Vehicle
{
int price=2000;
public static void main(String[] args)
{
Vehicle v=new Vehicle();
System.out.println(v.s);===============>engine
Car c=new Car();
System.out.println(c.price);===========>2000
System.out.println(c.s);===============>engine
Multilevel Inheritance
class Vehicle
{
String s="engine";
}
class Car extends Vehicle
{
int ctyres=4;
}
class Nexon extends Car
{
int price=100000;
public static void main(String[] args)
{
Vehicle v=new Vehicle();
System.out.println(v.s);
Car c1=new Car();
System.out.println(c1.ctyres);
System.out.println(c1.s);
Nexon n=new Nexon();
System.out.println(n.s);
System.out.println(n.ctyres);
System.out.println(n.price);
Hierarchical Inheritance
class Vehile
{
String s="engine";
}
class Car extends Vehile
{
int ct=4;
}
class Bike extends Vehile
{
int bt=2;
public static void main(String[] args)
{
Vehicle v=new Vehicle();
System.out.println(v.s);
Car c1=new Car();
System.out.println(c1.ct);
System.out.println(c1.s);
Bike b1=new Bike();
System.out.println(b1.bt);
System.out.println(b1.s);
}
}
class A
{
int a=6;
}
class C
{
int c=8;
}
class B extends A,C==========================>error
{
int b=7;
public static void main(String[] args)
{
}
}
this
class A
{
int a=7;============>Instance variable
void m1()
{
int x=9;=========>Local variable
System.out.println(x);============================>9
System.out.println(this.a);=======================>7
}
public static void main(String[] args)
{
A a1=new A();
a1.m1();
}
}
class A
{
int a=12;======================>Instance var
void display()
{
int a=16;===================>Local var
System.out.println(a);===============>16
System.out.println(this.a);==========>12
}
public static void main(String[] args)
{
A a1=new A();
a1.display();
}
}
class A
{
void show()
{
System.out.println("show method");
}
void display()
{
this.show();
System.out.println("display method");
}
public static void main(String[] args)
{
A a1=new A();
a1.display();
}
}
class A
{
void show()
{
System.out.println("show method");
this.display();
}
void display()
{
System.out.println("display method");
}
public static void main(String[] args)
{
A a1=new A();
a1.show();
}
}
class A
{
static int a=9;
void show()
{
int a=6;
System.out.println(a);=======================>6
System.out.println(this.a);==================>9
}
public static void main(String[] args)
{
A a1=new A();
a1.show();
}
}
class A
{
static int a=9;
static void show()
{
int a=6;
System.out.println(a);
System.out.println(this.a);==================>error
}
public static void main(String[] args)
{
A a1=new A();
a1.show();
}
}
super
Note:static methods does not refer this and super keyword anyway.
static variables can refer by this and super keyword
class A
{
int a=6;
}
class B extends A
{
int b=9;
void display()
{
System.out.println(b);================>9
System.out.println(a);================>6
}
public static void main(String[] args)
{
B b1=new B();
b1.display();
}
}
class A
{
int a=6;
}
class B extends A
{
int a=9;
void display()
{
System.out.println(a);=======================>9
System.out.println(super.a);================>6
}
public static void main(String[] args)
{
B b1=new B();
b1.display();
}
}
class A
{
void mahesh()
{
System.out.println("Mahesh in super class");
}
}
class B extends A
{
void pawan()
{
System.out.println("pawn in sub class");
}
public static void main(String[] args)
{
B b1=new B();
b1.mahesh();
b1.pawan();
}
}
class A
{
void mahesh()
{
System.out.println("Mahesh in super class");
}
}
class B extends A
{
void mahesh()
{
System.out.println("pawan in sub class");===================>pawan in sub class
super.mahesh();=============================================>Mahesh in super class
}
public static void main(String[] args)
{
B b1=new B();
b1.mahesh();
}
}
class A
{
String m="ntr";
void mahesh()
{
System.out.println(m);
System.out.println("Mahesh in super class");
}
}
class B extends A
{
String va="prabhas";
void mahesh()
{
System.out.println(va);
super.mahesh();
System.out.println("pawan in sub class");
}
public static void main(String[] args)
{
B b1=new B();
b1.mahesh();
}
}
class A
{
static int a=7;
}
class B extends A
{
int a=8;
void display()
{
System.out.println(a);===========================>8
System.out.println(super.a);=====================>7
}
public static void main(String[] args)
{
B b1=new B();
b1.display();
}
}
class A
{
int a=7;
}
class B extends A
{
int a=8;
static void display()
{
System.out.println(a);
System.out.println(super.a);=======================>error
}
public static void main(String[] args)
{
B b1=new B();
b1.display();
}
}
Modifiers
1.Modifiers are keywords.
2.Modifiers are used to give accessbility and modifies the behaviour of variables,methods
and class.
3.Modifiers are divided into 2 types.They are
1.Access Modifiers
2.Non Access Modifiers.
1.Access Modifiers
We can increase the accessibility but donot decrease the accessibility to the access modifiers.
1.public==========>public
2.protected=======>public,protected
3.default=========>public,protected,default
4.private=========>No
class A
{
String s="Rajamouli";
}
class B extends A
{
String s2="Maniratnam";
public static void main(String[] args)
{
B b1=new B();
System.out.println(b1.s2);===========>Maniratname
System.out.println(b1.s);============>Rajamouli
}
class A
{
private String s="Rajamouli";
}
class B extends A
{
String s2="Maniratnam";
public static void main(String[] args)
{
B b1=new B();
System.out.println(b1.s2);
System.out.println(b1.s);===================>error
}
}
class A
{
private String s="Rajamouli
}
class B extends A
{
String s2="Maniratnam";
public static void main(String[] args)
{
A b1=new A();
System.out.println(b1.s);====================>Error
}
class B
{
private String s2="Maniratnam";
public static void main(String[] args)
{
B b1=new B();
System.out.println(b1.s2);===================>Maniratnam
}
class A
{
void m1()
{
System.out.println("m1 in A");
}
}
class B extends A
{
void m2()
{
System.out.println("m2 in B");
}
public static void main(String[] args)
{
B b1=new B();
b1.m1();
b1.m2();
}
}
output
m1 in A
m2 in B
class A
{
private void m1()
{
System.out.println("m1 in A");
}
}
class B extends A
{
void m2()
{
System.out.println("m2 in B");
}
public static void main(String[] args)
{
B b1=new B();
b1.m1();============>error
b1.m2();
}
}
private class A
{
void m1()
{
System.out.println("m1 in A");
}
}
class B extends A=================================>ERROR
{
void m2()
{
System.out.println("m2 in B");
}
public static void main(String[] args)
{
B b1=new B();
b1.m1();
b1.m2();
}
}
class A
{
public void m1()
{
System.out.println("m1 in A");
}
}
class B extends A
{
void m2()
{
System.out.println("m2 in B");
}
public static void main(String[] args)
{
B b1=new B();
b1.m1();===========================>m1 in A
b1.m2();===========================>m2 in B
}
}
class A
{
protected void m1()
{
System.out.println("m1 in A");
}
}
class B extends A
{
void m2()
{
System.out.println("m2 in B");
}
public static void main(String[] args)
{
B b1=new B();
b1.m1();=============================>m1 in A
}
}
class A
{
void m1()
{
System.out.println("m1 in A");
}
}
class B extends A
{
void m2()
{
System.out.println("m2 in B");
}
public static void main(String[] args)
{
B b1=new B();
b1.m1();===========================>m1 in A
}
}
Constructors
2.Parameterized Constructors
----------------------------
The constructor with formal parameters is called parameterized constructors.
3.Copy Constructor.
--------------------
The process of copying 1 object refernce or refernce variable into another Onject refernce or
reference variable.
8.Constructor chaining
1.The process of calling one constructor to another constructor is called constructor chaining.
2.Constructor chaining can be possible by this(),super().
3.this() and super() must be written in first statement.
4.super() is implicitly present in every class but not this().
3.this()
---------
this() will call default constructor in current class.
this(int x)
-----------
this(int x) will parameterized constructor in current class.
4.super()
---------
super() will call default constructor in super class
super(int x)
---------
super(int x) will call parameterized constructor in super class
Methods
Constructors
class Demo
{
Demo()
{
System.out.println("welcome to constructors");==============>Welcome to constructors
}
public static void main(String[] args)
{
Demo d1=new Demo();
}
}
class Demo
{
Demo(int a)
{
System.out.println(a+" parameterized constructors");=========>6 parameterized constructors
}
public static void main(String[] args)
{
Demo d1=new Demo(6);
}
}
class Demo
{
Demo(int a,int b)
{
System.out.println(" parameterized constructors");==>parameterized constructors
System.out.println(a+" "+b);===>6 8
}
public static void main(String[] args)
{
Demo d1=new Demo(6,8);
}
}
class Demo
{
int a;
int b;
Demo()
{
a=6;
b=7;
System.out.println(a+" "+b);
}
Demo(Demo ref)
{
a=ref.a;
b=ref.b;
System.out.println(a+" "+b);
}
public static void main(String[] args)
{
Demo d1=new Demo();
Demo d2=new Demo(d1);
}
}
class Student
{
int sno;
String sname;
Student()
{
sno=123;
sname="Hemanth";
System.out.println(sno+" "+sname);===========>123 Hemanth
}
Student(Student s3)
{
sno=s3.sno;
sname=s3.sname;
System.out.println(sno+" "+sname);==========>123 Hemanth
}
public static void main(String[] args)
{
Student s1=new Student();
Student s2=new Student(s1);
}
}
class Emp
{
int eno=12;
String ename="Parithosh";
Emp()
{
System.out.println(eno+" "+ename);==================>12 Parithosh
}
public static void main(String[] args)
{
Emp e1=new Emp();
}
}
class Emp
{
int eno;
String ename;
Emp(int empno,String empname)
{
eno=empno;
ename=empname;
}
void display()
{
System.out.println(eno+" "+ename);
}
public static void main(String[] args)
{
Emp e1=new Emp(12,"Mohan");
e1.display();
}
}
}
}
}
}
class Demo
{
}
}
No output
-------------------------------------------------------
class Demo
{
Demo()
{
}
}
}
No output
class Demo
{
Demo()
{
System.out.println("default con");
}
Demo(int x)
{
System.out.println("parameterized con");
}
Demo(int x,String y)
{
System.out.println(x+" "+y);
}
}
}
}
public static void main(String[] args)
{
B b1=new B();==================>created object for sub class for executing default constructor
}
}
error
class B
{
B()
{
System.out.println("defalut con");
}
B(int x)
{
this();
System.out.println("parameterized con");
}
public static void main(String[] args)
{
B b1=new B(7);
}
}
Defalut con
parameterized con
class B
{
B()
{
this(5);
System.out.println("defalut con");
}
B(int x)
{
System.out.println("parameterized con");
}
parameterized con
defalut con
class B
{
B()
{
System.out.println("defalut con");
this(5);=============================>error
}
B(int x)
{
System.out.println("parameterized con");
}
class A
{
A()
{
System.out.println("default con in super class");
}
}
class B extends A
{
B(int x)
{
super();
System.out.println("parameterized con in sub class");
}
public static void main(String[] args)
{
B b1=new B(6);
}
}
class A
{
A(int x)
{
System.out.println("param con in super class");
}
}
class B extends A
{
B()
{
super(6);
System.out.println("default con in sub class");
}
public static void main(String[] args)
{
B b1=new B();
}
}
class A
{
A()
{
System.out.println("default con in super class");
}
}
class B extends A
{
B(int x)
{
class A
{
A()
{
System.out.println("default con in super class");
}
}
class B extends A
{
B(int x)
{
this();
System.out.println("parameterized con in sub class");
}
B()
{
polymorphism
1.compiletime/static polymorphism.
The process of binding method heading with method calling at compile time is called compile
time polymorphism.
Ex
1.overloading,method hiding
2.Runtime/dynamic polymorphism.
The process of binding method heading with method calling at run time is called runtime
time polymorphism.
Ex
1.overriding
1.Method overloading
1.The process of 2 or more methods name should be same and different formal paramter list.
2.Formal parameter list
1.No.of Formal parameters
2.change in order
3.change in datatype
3.Method overloading is possible in 1 class and multiple classes.
4.Inheritance is not required for method overloading (but possible in Inheritance also).
5.static methods can be overloaded.
6.private methods can be overloaded.
7.final methods can be overloaded.
2.Method overriding
1.The process of 2 or more methods name should be same and same formal paramter list.
2.Method overriding is not possible in 1class atleast 2 classes is required.
3.Method overriding can be implemented by using inheritance concept.
4.static methods cannot be override because (The purpose of static methods is to perform commom
task if we override static methods it will lost common task so thats why not possible).
5.private methods cannot be override because we cannot inherit 1 method of 1 class into another
class.
6.final methods cannot be ovverride because the purpose of final is to prevent inheritance.
class A
{
void add(int a)
{
System.out.println("welcome to java");
}
void add(float b)
{
System.out.println("welcome to python");
}
public static void main(String[] args)
{
A a1=new A();
a1.add(12);========================================>welcome to java
}
}
class A
{
void add(int a)
{
System.out.println("welcome to java");
}
void add(float b)
{
System.out.println("welcome to python");
}
public static void main(String[] args)
{
A a1=new A();
a1.add(12.6f);===================================>welcome to python
}
}
class A
{
void add(int a)=================================>method 1
{
System.out.println("welcome to java");
}
void add(float b)=================================>method 2
{
System.out.println("welcome to python");
}
public static void main(String[] args)
{
A a1=new A();
a1.add("mahesh");======================>error
}
}
class A
{
void add(int a,int b)
{
System.out.println("welcome to java");
}
void add(int c)
{
System.out.println("welcome to python");
}
public static void main(String[] args)
{
A a1=new A();
a1.add(1,7);==========================>welcome to java
}
}
class A
{
void add(int a,float b)
{
System.out.println("welcome to java");
}
void add(float a,int b)
{
System.out.println("welcome to python");
}
void add(int a)
{
System.out.println("welcome to c");
}
}
}
class A
{
void add()
{
System.out.println("Virat Kohli");
}
void add()
{
System.out.println("Sachin Tendulkar");
}
public static void main(String[] args)
{
A a1=new A();
a1.add();==========================>error because(method overriding is not
possible in 1 class)
}
class A
{
void add()
{
System.out.println("Virat kohli");
}
}
class B extends A
{
void add()
{
System.out.println("Sachin Tendulkar");
}
public static void main(String[] args)
{
B b1=new B();
b1.add();==========================================>scahin Tendulakar
}
class A
{
void add()
{
System.out.println("Virat kohli");
}
}
class B extends A
{
void add()
{
System.out.println("Sachin Tendulkar");
}
public static void main(String[] args)
{
A a1=new A();
a1.add();================================>virat kohli
}
}
class B
{
static void m1()
{
System.out.println("chicken");
}
void m1(int a)
{
System.out.println("mushroom");
}
class A
{
final void display()
{
System.out.println("Display in A");
}
}
class B extends A
{
void display()
{
System.out.println("Display in B");
}
public static void main(String[] args)
{
A a1=new A();
a1.display();=====================================>error
}
}
class A
{
private void display()
{
System.out.println("Display in A");
}
}
class B extends A
{
void display()
{
System.out.println("Display in B");
}
public static void main(String[] args)
{
A a1=new A();
a1.display();================================>error
}
}
class A
{
static void display()
{
System.out.println("Display in A");
}
}
class B extends A
{
void display()
{
System.out.println("Display in B");
}
public static void main(String[] args)
{
A a1=new A();
a1.display();==================================>error
}
}
class B
{
final void display(int a)
{
System.out.println("Display in virat");
}
void display()
{
System.out.println("Display in B");
}
public static void main(String[] args)
{
B b1=new B();
b1.display();========================>Display in B
}
}
class B
{
private void display(int a)
{
System.out.println("Display in virat");
}
void display()
{
System.out.println("Display in B");
}
public static void main(String[] args)
{
B b1=new B();
b1.display();========================>Display in B
}
}
class B
{
static void display(int a)
{
System.out.println("Display in virat");
}
void display()
{
System.out.println("Display in B");
}
public static void main(String[] args)
{
B b1=new B();
b1.display();========================>Display in B
}
}
class Calculator
{
void add(int a,int b)
{
System.out.println(a+b);
}
void add(int a,int b,int c)
{
System.out.println(a+b+c);
}
void add(int a,int b,int c,int d)
{
System.out.println(a+b+c+d);
}
public static void main(String[] args)
{
Calculator c1=new Calculator();
c1.add(6,8,9);
}
}
class Sbi
{
void phonePay(int am)
{
System.out.println(am);
}
}
class PunjabBank extends Sbi
{
void phonePay(int am)
{
System.out.println(am);
}
public static void main(String[] args)
{
Sbi ajay=new Sbi();
ajay.phonePay(500);
PunjabBank pari=new PunjabBank();
pari.phonePay(700);
}
}
class Anand
{
void love()
{
System.out.println("vaishnavi loves Anand");
}
}
class Viraj extends Anand
{
void love()
{
System.out.println("vaishnavi loves viraj");
}
public static void main(String[] args)
{
Viraj vaishu=new Viraj();
vaishu.love();
}
final
int a=6;
a=8;
a=12;
System.out.println(a);===================>12
class B
{
void show()
{
System.out.println("show in B");
}
}
class A extends B
{
void show()
{
System.out.println("show in A");
}
public static void main(String[] args)
{
B b1=new B();
b1.show();=========================>show in B
}
}
class B
{
final void show()
{
System.out.println("show in B");
}
}
class A extends B
{
void show()
{
System.out.println("show in A");
}
public static void main(String[] args)
{
B b1=new B();
b1.show();==========================>error
}
}
final class B
{
void show()
{
System.out.println("show in B");
}
}
class A extends B===========================>error
{
void display()
{
System.out.println("display in A");
}
public static void main(String[] args)
{
B b1=new B();
b1.show();
}
}
class B
{
void show()
{
System.out.println("show in B");
}
}
class A extends B
{
void display()
{
System.out.println("display in A");
}
public static void main(String[] args)
{
B b1=new B();
b1.show();====================================>show in B
}
}
final int a;
System.out.println(a);=============>error
upcasting
1.The process of assigning object or object refernce of sub class to super class.
2.Upcasting done by system implicitly.
3.Upcasting always valid
class A
{
void m1()
{
System.out.println("m1 in A");
}
}
class B extends A
{
void m2()
{
System.out.println("m2 in B");
}
}
class C extends B
{
void m3()
{
System.out.println("m3 in c");
}
}
class Test
{
public static void main(String[] args)
{
A a1=new B();
a1.m1();================>m1 in A
a1.m2();================>error
}
}
class A
{
void m1()
{
System.out.println("m1 in A");
}
}
class B extends A
{
void m2()
{
System.out.println("m2 in B");
}
}
class C extends B
{
void m3()
{
System.out.println("m3 in c");
}
}
class Test
{
public static void main(String[] args)
{
A a1=new B();
a1.m1();=====================>m1 in A
B b1=new C();
b1.m1();====================>m1 in A
b1.m2();====================>m2 in B
A a2=new C();
a2.m1();====================>m1 in A
a2.m2();==================>error
}
}
class Vehicle
{
void engine()
{
System.out.println("engine in vehicle");
}
}
class Car extends Vehicle
{
void tyres()
{
System.out.println("4 tyres in car");
}
}
class Punch extends Car
{
void price()
{
System.out.println("10 lakhs punch");
}
}
class Demo
{
public static void main (String[] args)
{
Vehicle v1=new Car();
v1.engine();=================>engine in Vehicle
v1.tyres();==================>error
v1.price();==================>error
Car c1=new Punch();
c1.engine();=================>engine in vehicle
c1.tyres();==================>4 tyres in Car
c1.price();==================>error
Vehicle v2=new Punch();
v2.engine();=================>engine in Vehicle
v2.tyres();==================>error
v2.price();==================>error
Vehicle v3=c1;
v3.engine();==================>engine in Vehicle
v3.tyres();==================>error
v3.price();==================>error
}
}
downcasting
1.The process of assigning object or object refernce of super class to sub class.
2.Downcasting can be done by programmer explicitly.
3.Downcasting always required upcasting.
class Vehicle
{
void engine()
{
System.out.println("engine in vehicle");
}
}
class Car extends Vehicle
{
void tyres()
{
System.out.println("4 tyres in car");
}
}
class Punch extends Car
{
void price()
{
System.out.println("10 lakhs punch");
}
}
class Demo
{
public static void main (String[] args)
{
Vehicle v1=new Car();
Car c1=(Car)v1;
c1.engine();
c1.tyres();
}
}
Object class
1.toString()
2.hashCode()
3.equals()
4.finalize()
5.getClass()
6.clone()
7.wait()
8.wait(long ms)
9.wait(long ms,int s)
10.notify()
11.notifyAll()
1.toString()
class Demo
{
public static void main(String[] args)
{
Demo d1=new Demo();
System.out.println(d1);============>Demo@372f7a8d
}
}
Demo@372f7a8d
className@hexdecimaldata
getClass().getName().toHexString().hashCode()
class Demo
{
public static void main(String[] args)
{
Demo d1=new Demo();
System.out.println(d1);============>Demo@372f7a8d
System.out.println(d1.toString());============>Demo@372f7a8d
}
}
class Demo
{
public static void main(String[] args)
{
System.out.println("Happy Friday");=============>Happy Friday
}
}
import java.lang.*;
class Demo extends Object
{
public static void main(String[] args)
{
System.out.println("Happy Friday");=============>Happy Friday
}
}
class Demo
{
public String toString()
{
return "welcome to java";
}
public static void main(String[] args)
{
Demo d1=new Demo();
System.out.println(d1);===============>welcome to java
System.out.println(d1.toString());=====>welcome to java
}
}
class Demo
{
int sno;
String sname;
Demo(int sno,String sname)
{
this.sno=sno;
this.sname=sname;
}
public static void main(String[] args)
{
Demo d1=new Demo(7,"Dhoni");
System.out.println(d1);=========>Demo@372f7a8d===>toString representation
}
}
class Demo
{
int sno;
String sname;
Demo(int sno,String sname)
{
this.sno=sno;
this.sname=sname;
}
public String toString()
{
return sno+" "+sname;
}
public static void main(String[] args)
{
Demo d1=new Demo(7,"Dhoni");
System.out.println(d1); =========>7 Dhoni
}
class Demo
{ public static void main(String[] args)
{
Demo d1=new Demo();
System.out.println(d1);
System.out.println(d1.toString());
int hs=d1.hashCode();
System.out.println(hs);
}
}
Demo@372f7a8d
Demo@372f7a8d
925858445
Relationships
class Person
{
int hands=2;
int legs=2;
}
class Student extends Person
{
int sno=12;
String sname="Hemanth Babu";
void getStudent()
{
System.out.println("sno"+sno+" "+"sname"+sname+" "+"hands"+hands+" "+"legs"+legs);
}
public static void main(String[] args)
{
Student s1=new Student();
s1.getStudent();
}
}
Student is a person
class Bike
{
int speed=120;
String color="Black";
}
class Duke extends Bike
{
int dukeprice=1000;
void getDuke()
{
System.out.println(speed+" "+color+" "+dukeprice);
}
public static void main(String[] args)
{
Duke d1=new Duke();
d1.getDuke();
}
Duke is a Bike
class Engine
{
void start()
{
System.out.println("Bike started");
}
void stop()
{
System.out.println("Bike stopped");
}
}
class Bike
{
Engine e1=new Engine();
void work()
{
e1.start();
System.out.println("Bike is running......");
e1.stop();
}
public static void main(String[] args)
{
Bike b1=new Bike();
b1.work();
}
}
Bike started
Bike is running......
Bike stopped
class Address
{
int dno=12;
String stname="mythrivanam";
}
class Emp
{
Address a1=new Address();
String ename="Hemanth";
void getEmp()
{
System.out.println(ename+" "+a1.dno+" "+a1.stname);
}
public static void main(String[] args)
{
Emp e1=new Emp();
e1.getEmp();
}
}
Emp has a Address
Hemanth 12 mythrivanam
Encapsulation
class Demo
{
int no=12;
String name="parithosh";
void display()
{
System.out.println(no+" "+name);
}
public static void main(String[] args)
{
Demo d1=new Demo();
d1.display();
}
}
class Student
{
int sno;
String sname;
String dname;
}
}
class Teacher
{
public static void main(String[] args)
{
Student s1=new Student();
s1.sno=123;
s1.sname="Mohan";
s1.dname="ECE";
System.out.println(s1.sno);
System.out.println(s1.sname);
System.out.println(s1.dname);
}
}
output
123
Mohan
ECE
class Student
{
private int sno;
private String sname;
private String dname;
}
}
class Teacher
{
public static void main(String[] args)
{
Student s1=new Student();
s1.sno=123;
s1.sname="Mohan";
s1.dname="ECE";
System.out.println(s1.sno);
System.out.println(s1.sname);
System.out.println(s1.dname);
}
}
output
class Student
{
private int sno;
private String sname;
private String dname;
public void setSno(int sno)
{
this.sno=sno;
}
public void setSname(String sname)
{
this.sname=sname;
}
public void setDname(String dname)
{
this.dname=dname;
}
public void getSno()
{
System.out.println(sno);
}
public void getSname()
{
System.out.println(sname);
}
public void getDname()
{
System.out.println(dname);
}
class Teacher
{
public static void main(String[] args)
{
Student s1=new Student();
s1.setSno(334);
s1.setSname("AjayKumar");
s1.setDname("ECE");
s1.getSno();
s1.getSname();
s1.getDname();
output
334
AjayKumar
ECE
class Student
{
private int sno;
private String sname;
private String dname;
public void setSno(int sno)
{
this.sno=sno;
}
public void setSname(String sname)
{
this.sname=sname;
}
public void setDname(String dname)
{
this.dname=dname;
}
public void getSno()
{
System.out.println(sno);
}
public void getSname()
{
System.out.println(sname);
}
public void getDname()
{
System.out.println(dname);
}
class Teacher
{
public static void main(String[] args)
{
Student s1=new Student();
s1.setSno(-87);
s1.setSname("AjayKumar");
s1.setDname("ECE");
s1.getSno();
s1.getSname();
s1.getDname();
output
-87
AjayKumar
ECE
class Student
{
private int sno;
private String sname;
private String dname;
public void setSno(int sno)
{
this.sno=sno;
}
public void setSname(String sname)
{
this.sname=sname;
}
public void setDname(String dname)
{
this.dname=dname;
}
public void getSno()
{
if(sno>0)
{
System.out.println("valid"+sno);
}
else
{
System.out.println("Invalid donot use ultra pro knowledge");
}
}
public void getSname()
{
System.out.println(sname);
}
public void getDname()
{
System.out.println(dname);
}
class Teacher
{
public static void main(String[] args)
{
Student s1=new Student();
s1.setSno(-87);
s1.setSname("AjayKumar");
s1.setDname("ECE");
s1.getSno();
s1.getSname();
s1.getDname();
output
class Student
{
private int sno;
private String sname;
private String dname;
public void setSno(int sno)
{
this.sno=sno;
}
public void setSname(String sname)
{
this.sname=sname;
}
public void setDname(String dname)
{
this.dname=dname;
}
public void getSno()
{
if(sno>0)
{
System.out.println("valid"+sno);
}
else
{
System.out.println("Invalid donot use ultra pro knowledge");
}
}
public void getSname()
{
System.out.println(sname);
}
public void getDname()
{
System.out.println(dname);
}
class Teacher
{
public static void main(String[] args)
{
Student s1=new Student();
s1.setSno(97);
s1.setSname("AjayKumar");
s1.setDname("ECE");
s1.getSno();
s1.getSname();
s1.getDname();
output
valid 97
AjayKumar
ECE
Adopter class
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.
Note:If we want access only m2() in normal interfaces with implememtation class we have ovveride
all the methods and we have to write logic for only required (m2) methods.
interface A
{
void m1();
void m2();
void m3();
void m4();
void m5();
}
class B implements A
{
public void m1()
{
System.out.println("m1 in imple");
}
public void m2()
{
System.out.println("m2 in imple");
}
public void m3()
{
System.out.println("m3 in imple");
}
public void m4()
{
System.out.println("m4 in imple");
}
public void m5()
{
System.out.println("m5 in imple");
}
}
class Test
{
public static void main(String[] args)
{
A a1=new B();
a1.m2();
}
}
output
m2 in imple
interface A
{
void m1();
void m2();
void m3();
void m4();
void m5();
}
class B implements A
{
public void m1()
{
}
public void m2()
{
}
public void m3()
{
}
public void m4()
{
}
public void m5()
{
}
class Test extends B
{
public void m2()
{
System.out.println("m2 in Test class");
}
public static void main(String[] args)
{
Test t1=new Test();
t1.m2();
}
}
output
m2 in Test class.
interface Student
{
void getMarks();
void getDetails();
void getAddress();
void getDept();
}
class StudentDetails implements Student
{
public void getMarks()
{
}
public void getDetails()
{
}
public void getAddress()
{
}
public void getDept()
{
}
}
class Test extends StudentDetails
{
public void getMarks()
{
System.out.println("Telugu =92");
System.out.println("Hindi =94");
System.out.println("English =92");
System.out.println("Maths =99");
System.out.println("Physics =93");
System.out.println("Chemistry =94");
}
public static void main(String[] args)
{
Test t1=new Test();
t1.getMarks();
}
output
Telugu =92
Hindi =94
English =92
Maths =99
Physics =93
Chemistry =94
enum(Enumuration)
The purpose of values() is to list out the total number of constansts in enum.
9.ordinal()
The purpose of ordinal() is to give ordinal value from 0 to length-1 to the enum constants.
10.enum is ordinal based ordinal starts from 0 and ends with length-1.
11.enum allows variables,methods,constructors.
enum Week
{
Sun,Mon,Tue,Wed,Thu,Fri,Sat
}
class Test
{
public static void main(String[] args)
{
Week w1=Week.Sun;
System.out.println(w1);
Week w2=Week.Mon;
System.out.println(w2);
Week w3=Week.Tue;
System.out.println(w3);
Week w4=Week.Wed;
System.out.println(w4);
}
}
output
Sun
Mon
Tue
Wed
class Test
{
enum Week
{
Sun,Mon,Tue,Wed,Thu,Fri,Sat;
}
public static void main(String[] args)
{
Week w1=Week.Sun;
System.out.println(w1);
Week w2=Week.Mon;
System.out.println(w2);
Week w3=Week.Tue;
System.out.println(w3);
Week w4=Week.Wed;
System.out.println(w4);
}
}
output
Sun
Mon
Tue
Wed
enum Directions
{
East,West,North,South;
public static void main(String[] args)
{
Directions d1=Directions.East;
System.out.println(d1);
Directions d2=Directions.West;
System.out.println(d2);
Directions d3=Directions.North;
System.out.println(d3);
Directions d4=Directions.South;
System.out.println(d4);
}
}
enum Directions
{
East,West,North,South;
public static void main(String[] args)
{
Directions[] d1=Directions.values();
for(Directions d2:d1)
{
System.out.println(d2+"......"+d2.ordinal());
}
}
}
output
East......0
West......1
North......2
South......3
enum Directions
{
East,West,North,South;
Directions()
{
System.out.println("constructor");
}
public static void main(String[] args)
{
Directions d1=Directions.East;
}
}
output
constructor
constructor
constructor
constructor
enum Beer
{
kf(100),Bw(70),Ko(85);
int getPrice;
Beer(int getPrice)
{
this.getPrice=getPrice;
}
int getRates()
{
return getPrice;
}
}
class Test
{
public static void main(String[] args)
{
Beer[] b1=Beer.values();
for(Beer b2:b1)
{
System.out.println(b2+"....."+b2.getRates());
}
}
}
output
kf.....100
Bw.....70
Ko.....85
enum Beer
{
kf(100),Bw(70),Ko(85),BB;
int getPrice;
Beer(int getPrice)
{
this.getPrice=getPrice;
}
Beer()
{
getPrice=200;
int getRates()
{
return getPrice;
}
}
class Test
{
public static void main(String[] args)
{
Beer[] b1=Beer.values();
for(Beer b2:b1)
{
System.out.println(b2+"....."+b2.getRates());
}
}
}
output
kf.....100
Bw.....70
Ko.....85
BB.....200
Annotations
1.predefine/standard annotations
The annotations which are already present in java software(jdk).These annotations are developed
by java developers.
predefine annotations are divided into 2 types.They are
1.General purpose annotations.
2.Meta annotations.
1.General purpose annotations.
2.Meta Annotations
@Target
@Tetention
@Inherited
@Documented
@Target
@Target annotation will give information where we applied to the corresponding annotation
(where it can be method,variable,class,Constructor)
1.ElementType.TYPE====>class
2.ElementType.METHOD====>Method
3.ElementType.FIELD====>variable
2.@Retention
RetentionPolicy.SOURCE
RetentionPolicy.CLASS
RetentionPolicy.RUNTIME
3.@Documented
4.@Inherited
@Inherited annotation is used to reuse one annotation features into another annotation.
2.UserDefine/custom annotations
The annotations which are not present in java software(jdk).These annotations are developed
by java programmers.
Marker Annotation
@interface Bank
{
}
@interface Bank
{
int bno();
}
Multivalue Annotation
@interface Bank
{
int bno();
String bname();
}
@override
If we are trying to do override sub class method with super class method unfortunately or by mistake if we does
spelling mistakes then @Override annotation will give error at compile time.
class Sbi
{
void sendMoneyToCustome()
{
System.out.println("sending money from sbi");
}
}
class Axis extends Sbi
{
void sendMoneyToCustomer()
{
System.out.println("sending money from Axis");
}
}
class Test
{
public static void main(String[] args)
{
Axis bhavadeesh=new Axis();
bhavadeesh.sendMoneyToCustome();
}
}
output
class Sbi
{
void sendMoneyToCustome()
{
System.out.println("sending money from sbi");
}
}
class Axis extends Sbi
{
@Override
void sendMoneyToCustomer()
{
System.out.println("sending money from Axis");
}
}
class Test
{
public static void main(String[] args)
{
Axis bhavadeesh=new Axis();
bhavadeesh.sendMoneyToCustome();
}
}
output
class Sbi
{
void sendMoneyToCustomer()
{
System.out.println("sending money from sbi");
}
}
class Axis extends Sbi
{
@Override
void sendMoneyToCustomer()
{
System.out.println("sending money from Axis");
}
}
class Test
{
public static void main(String[] args)
{
Axis bhavadeesh=new Axis();
bhavadeesh.sendMoneyToCustomer();
}
}
output
@Deprecated
If we are trying to access outdated methods then @Depricated annotation will give error
class Tcs
{
class Test
{
public static void main(String[] args)
{
Tcs t1=new Tcs();
t1.getSalary(2000,1200);
}
}
output
class Tcs
{
@Deprecated
void getSalary(int basic,int hra)
{
System.out.println("Before ycp govt");
}
void getSalary(int basic,int hra,int jtax)
{
System.out.println("After ycp govt");
}
}
class Test
{
public static void main(String[] args)
{
Tcs t1=new Tcs();
t1.getSalary(2000,1200);
}
}
output
@FunctionalInterface
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
@FunctionalInterface
interface A
{
void m1();
}
class B implements A
{
public void m1()
{
}
}
class Test
{
public static void main(String[] args)
{
}
@SuppressWarnings
If we perform unchecked or unsafe operations the compiler will give error (warning messages).
To overcame this problem then we are using @SuppressWarnings
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add(1);
al.add(1.2);
al.add("venky");
System.out.println(al);
}
import java.util.*;
class Test
{
@SuppressWarnings("unchecked")
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add(1);
al.add(1.2);
al.add("venky");
System.out.println(al);
}
output
[1,1.2,venky]
import java.lang.annotation.*;
@Inherited
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Bank
{
int bno();
String bname();
}
@Bank(bno=4567,bname="HDFC")
class Account
{
int acno;
String aname;
Account(int acno,String aname)
{
this.acno=acno;
this.aname=aname;
}
void display()
{
System.out.println(acno);
System.out.println(aname);
}
}
class Test
{
@SuppressWarnings("unchecked")
public static void main(String[] args)
{
Account a1=new Account(23,"parithosh");
a1.display();
Class c1=a1.getClass();
Annotation a2=c1.getAnnotation(Bank.class);
Bank b1=(Bank)a2;
System.out.println(b1.bno());
System.out.println(b1.bname());
}
}
import java.lang.annotation.*;
@Inherited
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface School
{
int slno();
String schname();
}
@School(slno=345,schname="Durga")
class Student
{
int sno;
String sname;
Student(int sno,String sname)
{
this.sno=sno;
this.sname=sname;
}
void display()
{
System.out.println(sno);
System.out.println(sname);
}
}
class Test
{
@SuppressWarnings("unchecked")
public static void main(String[] args)
{
Student s1=new Student(12,"Venky");
s1.display();
Class c1=s1.getClass();
Annotation a1=c1.getAnnotation(School.class);
School s2=(School)a1;
System.out.println(s2.slno());
System.out.println(s2.schname());
}
}
output
12
Venky
345
Durga
import java.lang.annotation.*;
@Inherited
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Bank
{
int bno();
String bname();
}
@Bank(bno=4567,bname="HDFC")
class Account
{
int acno;
String aname;
Account(int acno,String aname)
{
this.acno=acno;
this.aname=aname;
}
void display()
{
System.out.println(acno);
System.out.println(aname);
}
}
class Dept extends Account
{
}
class Test
{
@SuppressWarnings("unchecked")
public static void main(String[] args)
{
Account a1=new Account(23,"parithosh");
a1.display();
Class c1=a1.getClass();
Annotation a2=c1.getAnnotation(Bank.class);
Bank b1=(Bank)a2;
System.out.println(b1.bno());
System.out.println(b1.bname());
}
}
interface
1.interface is a collection of public static final variables and public abstract methods.
2.In interface public static final is implicitly present to the variables.
3.In interface public abstarct is implicitly present to the methods.
4.If we want to perform abstraction inheritance is required.
5. ======>1 class can extends 1 class
======>1 class implements multiple interfaces
======>1 interface extends multiple interfaces
6.interface cannot be instantiated(we cannot create object for interface because it contains
abstract methods(didnot contain body)there is no use to call abstract methods in interface.
7.abstract methods must be override with public access modifier in implementation class.
8.abstract methods cannot be static
9.abstract methods cannot be private
10.abstract methods cannot be final
11.interface cannot be final.
12.Constructors are not possible in interfaces.
13.In interfaces we can achieve multiple inheritance.
interfaces
interface Demo
{
public static final int a=12;==========>int a=12;
interface Demo
{
public static final int a=12;
public abstract void m1();
}
class B implements Demo
{
void m1()
{
System.out.println(a);
System.out.println("welcome to interfaces");
}
}
class Test
{
public static void main(String[] args)
{
Demo d1=new Demo();
}
}
output
error interface Demo cannot be instantiated(we cannot create object for interface
interface Demo
{
public static final int a=12;
public abstract void m1();
}
class B implements Demo
{
void m1()
{
System.out.println(a);
System.out.println("welcome to interfaces");
}
}
class Test
{
public static void main(String[] args)
{
Demo d1=new B();
d1.m1();
}
}
output
interface Demo
{
public static final int a=12;
public abstract void m1();
}
class B implements Demo
{
public void m1()
{
System.out.println(a);
System.out.println("welcome to interfaces");
}
}
class Test
{
public static void main(String[] args)
{
Demo d1=new B();
d1.m1();
}
}
output
12
welcome to interfaces
interface Loan
{
int itr=2;
void getLoan();
}
class HomeLoan implements Loan
{
public void getLoan()
{
System.out.println(itr+" ruppes interest for HomeLoan");
}
}
class EducationLoan implements Loan
{
public void getLoan()
{
System.out.println(itr+" ruppes interest for EducationLoan");
}
}
class GoldLoan implements Loan
{
public void getLoan()
{
System.out.println(itr+" ruppes interest for GoldLoan");
}
}
class User
{
public static void main(String[] args)
{
Loan bhavi=new HomeLoan();
bhavi.getLoan();
Loan Hemanth=new EducationLoan();
Hemanth.getLoan();
Loan venky=new GoldLoan();
venky.getLoan();
}
}
output
interface Physics
{
void getpyMarks();
}
interface Chemistry
{
void getchMarks();
}
class Student implements Physics,Chemistry
{
public void getpyMarks()
{
System.out.println("67 marks in physics");
}
public void getchMarks()
{
System.out.println("87 marks in chemistry");
}
}
class User
{
public static void main(String[] args)
{
p1.getpyMarks();
p1.getchMarks();
Physics p2=new Student();
p2.getpyMarks();
Chemistry p3=new Student();
p3.getchMarks();
}
}
67 marks in physics
87 marks in chemistry
67 marks in physics
87 marks in chemistry
interface A
{
void m1();
}
interface B
{
void m2();
}
interface C extends A,B
{
void m3();
}
class D implements C
{
public void m1()
{
System.out.println("m1 in D");
}
public void m2()
{
System.out.println("m2 in D");
}
public void m3()
{
System.out.println("m3 in D");
}
}
class Test
{
public static void main(String[] args)
{
D d1=new D();
d1.m1();
d1.m2();
d1.m3();
A a1=new D();
a1.m1();
B b1=new D();
b1.m2();
C c1=new D();
c1.m3();
}
}
m1 in D
m2 in D
m3 in D
m1 in D
m2 in D
m3 in D
Inner classes
1.Instance class.
A class which is defined outside of a method without using static keyword then that is called
a Instance class.
Instance class can access private features(variables or methods),static features(variables or
methods) from outer class.
Main method is allowed for outer class not for inner class.
class Outer
{
void m2()
{
System.out.println("m2 in outer");
}
class Inner
{
void m1()
{
System.out.println("m1 in Inner");
}
}
public static void main(String[] args)
{
Outer o1=new Outer();
o1.m2();
new Outer().m2();
}
}
output
m2 in outer
m2 in outer
class Outer
{
void m2()
{
System.out.println("m2 in outer");
}
class Inner
{
void m1()
{
System.out.println("m1 in Inner");
}
}
public static void main(String[] args)
{
Outer o1=new Outer();
o1.m2();
new Outer().m2();
Outer.Inner i1=o1.new Inner();
i1.m1();
}
}
output
m2 in outer
m2 in outer
m1 in inner
class Outer
{
void m2()
{
System.out.println("m2 in outer");
}
class Inner
{
void m1()
{
System.out.println("m1 in Inner");
}
}
public static void main(String[] args)
{
Outer o1=new Outer();
Outer.Inner i1=o1.new Inner();
i1.m1();
Outer.Inner i2=new Outer().new Inner();
i2.m1();
new Outer().new Inner().m1();
}
}
output
m1 in Inner
m1 in Inner
m1 in Inner
class Outer
{
int x=5;
void m2()
{
System.out.println("m2 in outer");
}
class Inner
{
int y=7;
void m1()
{
System.out.println(y);
System.out.println(x);
System.out.println("m1 in Inner");
m2();
}
}
public static void main(String[] args)
{
new Outer().new Inner().m1();
}
}
output
7
5
m1 in Inner
m2 in outer
class Outer
{
private int x=5;
static int z=5;
void m2()
{
System.out.println("m2 in outer");
}
class Inner
{
int y=7;
void m1()
{
System.out.println(y);
System.out.println(x);
System.out.println(z);
System.out.println("m1 in Inner");
m2();
}
}
public static void main(String[] args)
{
new Outer().new Inner().m1();
}
}
output
7
5
5
m1 in Inner
m2 in outer
class Outer
{
class Inner
{
public static void main(String[] args)
{
}
}
}
output
error
class Outer
{
class Inner
{
private int x=4;
static int y=9;
int z=18;
void m1()
{
System.out.println(x);
System.out.println(y);
System.out.println(z);
}
public static void main(String[] args)
{
new Outer().new Inner().m1();
}
}
output
4
9
18
static class
1.The class which is defined with static keyword is called static class.
2.static class can access only static features(var & meth) from outer class but inside static
class both static and non static possible.
class Outer
{
static class Inner
{
void m2()
{
System.out.println("m2 in Inner");
}
}
public static void main(String[] args)
{
Outer o1=new Outer();
Inner i1=new Outer.Inner();
i1.m2();
}
}
output
m2 in Inner
class Outer
{
static class Inner
{
int x=7;
void m2()
{
System.out.println(x);
System.out.println("m2 in Inner");
}
}
public static void main(String[] args)
{
Outer o1=new Outer();
Inner i1=new Outer.Inner();
i1.m2();
new Outer.Inner().m2();
}
}
output
7
m2 in Inner
7
m2 in Inner
class Outer
{
static int y=9;
static int z=17;
static private int u=8;
static class Inner
{
int x=7;
void m2()
{
System.out.println(y);
System.out.println(z);
System.out.println(u);
System.out.println(x);
System.out.println("m2 in Inner");
}
}
public static void main(String[] args)
{
new Outer.Inner().m2();
}
}
output
9
17
8
7
m2 in inner
class Outer
{
static int y=9;
int z=17;
private int u=8;
static class Inner
{
int x=7;
void m2()
{
System.out.println(y);
System.out.println(z);===============>error
System.out.println(u);==============>error
System.out.println(x);
System.out.println("m2 in Inner");
}
}
public static void main(String[] args)
{
new Outer.Inner().m2();
}
}
3.Local class.
A class is defined inside a method without static keyword is called a local class.
class Outer
{
public static void main(String[] args)
{
class Inner
{
void m1()
{
System.out.println("m1 in Inner");
}
}
Inner i1=new Inner();
i1.m1();
}
}
class Outer
{
void m1()
{
System.out.println("m1 in Outer");
class Inner
{
void m2()
{
System.out.println("m2 in Inner");
}
}
new Inner().m2();
}
public static void main(String[] args)
{
new Outer().m1();
}
}
4.Anonymus class
Note:
1.private,protected,static is not allowed for outer class.
2.static,public,protected,private is not allowed for local class and anonymous class.
3.All access modifiers are allowed in instance and static class.
abstract class A
{
abstract void m1();
}
class Demo
{
public static void main(String[] args)
{
A a1=new A()
{
void m1()
{
System.out.println("m1 in anon...class");
}
};
a1.m1();
}
}
interface A
{
void m1();
}
class Demo
{
public static void main(String[] args)
{
A a1=new A()
{
public void m1()
{
System.out.println("m1 in imple class");
}
};
a1.m1();
}
}
1.public
2.static
Note:jvm will call the main method by using object or object refernce if main method is not static
void
main
String[] args
Note
String[] args
String []args
String args[]
String bhavi[]
3.class Demo
{
public static void main(String venky[])
{
String s=venky[0];
System.out.println(s);
}
}
class Demo
{
public static void main(String venky[])
{
String s=venky[0];
System.out.println(s);
}
}
javac Demo.java
java Demo Dhoni
Dhoni
class Demo
{
public static void main(String[] args)
{
System.out.println("string data");
}
public static void main(int[] args)
{
System.out.println("int data");
}
output
String data
Abstraction
1.The process of hiding uncessesary details and showing necessary details is called Abstaraction.
2.The process of hiding implementation code and showing only functinality to the user.
3.Abstraction can be achieved in 2 ways.They are
1.abstract class
2.interfaces
1.abstarct class
1.A class which is defined with abstract keyword then that is called a abstract class.
2.abstract class is a collection of concrete methods and abstract methods.
abstract class A
{
}
concrete methods
1.The methods which have body then that is called a concrete method.
2.The purpose of concrete methods to give common functinality to the implementation classes.
void m1()
{
}
static void m2()
{
}
abstract methods
1.A method which is defined with abstarct keyword and without body is called abstract method.
2.The purpose of abstract method is give different funtionality to the implementation classes.
3.abstract methods can be defined in abstract classes only.
Important points on Abstarction
1.Abstarct class cannot be instantiated(we cannot create object for abstarct class) because abstract class contains
abstract methods (i.e abstract methods donot have body or implemented code
then there is no use to call abstract method.
Ex
--
abstract void m1();
abstract class A
{
void m1()
{
System.out.println("welcome to concrete");
}
abstract void m2();
}
class Test
{
public static void main(String[] args)
{
A a1=new A();
a1.m1();
}
}
output
abstract class A
{
void m1()
{
System.out.println("welcome to concrete");
}
abstract void m2();
}
class Test extends A
{
public static void main(String[] args)
{
Test t1=new Test();
t1.m1();
}
}
output
Test is not abstract and does not override abstract method m2() in A
abstract class A
{
void m1()
{
System.out.println("welcome to concrete");
}
abstract void m2();
}
class Test extends A
{
void m2()
{
System.out.println("m2 is ovverriden in implemetation Test class");
}
output
welcome to concrete
m2 is ovverriden in implemetation Test class
}
}
abstract class A
{
void m1()
{
System.out.println("m1 in A");
}
abstract private void m2();
}
class B extends A
{
void m2()
{
System.out.println("m2 in B");
}
}
class Test
{
public static void main(String[] args)
{
A a1= new B();
a1.m1();
a1.m2();
}
}
output
error
abstract class A
{
void m1()
{
System.out.println("m1 in A");
}
abstract final void m2();
}
class B extends A
{
void m2()
{
System.out.println("m2 in B");
}
}
class Test
{
public static void main(String[] args)
{
A a1= new B();
a1.m1();
a1.m2();
}
}
output
error
}
class B extends A
{
void m2()
{
System.out.println("m2 in B");
}
}
class Test
{
public static void main(String[] args)
{
A a1= new B();
a1.m1();
a1.m2();
}
}
output
error
abstract class A
{
static void m1()
{
System.out.println("m1 in A");
}
abstract void m2();
}
class B extends A
{
void m2()
{
System.out.println("m2 in B");
}
}
class Test
{
public static void main(String[] args)
{
A a1= new B();
a1.m1();
a1.m2();
A.m1();
}
}
output
m1 in A
m2 in B
m1 in A
abstract class A
{
public static void main(String[] args)
{
System.out.println("welcome to abstract class");
}
}
output
IO Streams
Stream
1.Byte Streams
1.InputStream
The purpose of InputStream is to carry the data from source file(java file) to target file(abc.txt)
Ex
---
1.FileInputStream
2.ObjectInputStream
3.DataInputStream
2.OutputStream
The purpose of OutputStream is to carry the data from target file(abc.txt) to source file(java.file)
Ex
---
1.FileOutputStream
2.ObjectOutputStream
3.DataOutputStream
2.Character Streams
1.Reader
Reader is used to carry the character data from input devices to java application
Ex
--
1.FileReader
2.BufferedReader
2.Writer
Writer is used to carry the character data from java applications to output devices.
1.FileWriter
2.BufferdWriter
3.PrintWriter
PrinWriter
Methods in PrintWriter
1.print===>print() is used to print the data from source file(Demo.java) to target file(venky.txt)in same line.
2.println===>println() is used to print the data from source file to target file in new line.
3.printf===>printf() is used to print the formatting data from source file to target file.
import java.io.*;
class FileOutput
{
public static void main(String[] args)throws Exception
{
FileOutputStream fos=new FileOutputStream("xyz.txt",);
String s1="virat";
byte[] b=s1.getBytes();
fos.write(b);
fos.close();
}
}
xyz.txt=============>String s1="virat";
virat
xyz.txt=============>String s1="kohli";
kohli
xyz.txt=============>String s1="virat";
virat
xyz.txt=============>String s1="kohli";
viratkohli
import java.io.*;
class FileOutput
{
public static void main(String[] args)throws Exception
{
FileInputStream fis=new FileInputStream("xyz.txt");
int size=fis.available();
byte[] b=new byte[size];
fis.read(b);
String s=new String(b);
System.out.println(s);
fis.close();
}
}
viratkohli
import java.io.*;
class Demo
{
public static void main(String[] args)throws Exception
{
FileWriter fw=new FileWriter("pqr.txt");
String data="Hello everyone";
char[] ch=data.toCharArray();
fw.write(data);
fw.close();
}
}
import java.io.*;
class Demo
{
public static void main(String[] args)throws Exception
{
FileReader fr=new FileReader("pqr.txt");
String data="";
int av=fr.read();
while(av!=-1)
{
data=data+(char)av;
av=fr.read();
}
System.out.println(data);
fr.close();
}
}
import java.io.*;
class Demo
{
public static void main(String[] args)throws Exception
{
FileInputStream fis=new FileInputStream("virat.jpg");
int size=fis.available();
byte[] b=new byte[size];
fis.read();
fis.close();
}
}
import java.io.*;
class Demo
{
public static void main(String[] args)throws Exception
{
PrintWriter pw=new PrintWriter("mno.txt");
pw.print("virat");
pw.print("kohli");
pw.println("is champ");
pw.println("in the world");
int a=5;
pw.printf("value of a is %d",a);
System.out.println("printing in console");
pw.close();
}
}
viratkohliis champ
in the world
value of a is 5
The process of providing input data at runtime(command prompt)is called dynamic data.
There are 3 ways to take data from command prompt.They are
1.BufferedReader
2.Scanner
3.console
1.BufferedReader methods
readLine() is used to store the complete String line data in the form of String.
read() is used to store 1st character of String in the form of ascii value.
2.Scanner methods
1.int======>nextInt()
2.byte=====>nextByte()
3.short=====>nextShort()
4.long======>nextLong()
5.float=====>nextFloat()
6.double====>nextDouble()
7.char======>next().charAt(0)
8.String====>next(),nextLine()
3.Console methods
readLine() is used to store the complete String line data in the form of String
readPassword() is used to password in the hidden form(it is not visible to users).
import java.io.*;
class Demo
{
public static void main(String[] args)throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter data 1st:");
String s1=br.readLine();
System.out.println("enter data 2nd:");
int av=br.read();
System.out.println("first data:"+s1);
System.out.println("second data:"+av+(char)av);
}
}
import java.io.*;
class Demo
{
public static void main(String[] args)throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter a value: ");
String a=br.readLine();
System.out.println("enter b value: ");
String b=br.readLine();
System.out.println(a+b);
int fn=Integer.parseInt(a);
int sn=Integer.parseInt(b);
System.out.println(fn+sn);
}
}
enter a value:
5
enter b value:
6
56
11
import java.io.*;
import java.util.*;
class Demo
{
public static void main(String[] args)throws Exception
{
Scanner sc=new Scanner(System.in);
System.out.println("enter username: ");
String uname=sc.nextLine();
System.out.println("enter password: ");
String pd=sc.next();
System.out.println(uname);
System.out.println(pd);
}
}
enter username:
Bhavadeesh
enter password:
Bhavi
Bhavadeesh
Bhavi
import java.io.*;
class Demo
{
public static void main(String[] args)throws Exception
{
Console c=System.console();
System.out.println("enter username: ");
String uname=c.readLine();
System.out.println("enter password: ");
char[] pwd=c.readPassword();
String pd=new String(pwd);
System.out.println(uname);
System.out.println(pd);
}
}
enter username:
Bhavadeesh
enter password:
Bhavadeesh
bhavi
Serialization
DeSerialization
import java.io.*;
class Emp implements Serializable
{
int eno;
String ename;
}
class SerEx
{
public static void main(String[] args)throws Exception
{
Emp e1=new Emp();
FileOutputStream fs=new FileOutputStream("pqr.txt");
ObjectOutputStream oos=new ObjectOutputStream(fs);
oos.writeObject(e1);
fs.close();
oos.close();
}
}
packages
1.predefine packages
A package which is already present in java software(jdk).These packages are developed by java
developers.
java.lang is a bydefault package in java.
2.Userdefine packages
A package which is not present in java software(jdk).These packages are developed by java
programmers.
package conventions
www.tcs.com==================>domain name
com.tcs======================>reverse domain
com.tcs.bank.withdraw
com.tcs=====>domain
bank========>project
withdraw====>module
com.tcs.bank.withdraw module1
com.tcs.bank.account module2
com.tcs.bank.transfer module3
com.tcs.bank.loans module4
syntax
------
package packagename;
class ClassName
{
}
interface InterfaceName
{
}
enum EnumName
{
}
Advantages of packages
package com.tcs.bank.account;
class Sample
{
public static void main(String[] args)
{
System.out.println("welcome to packages");
}
}
interface I1
{
}
javac Sample.java
Sample
I1
java Sample
error
compilation of packages
javac -d . Sample.java
Here
-d====================>directory
.====================>current directory
com
|---tcs
|--bank
|--account
|-I1
|-Sample
Execution of packages
java fullname
java com.tcs.bank.account.Sample
package com.tcs.bank.account;
class Sample
{
public static void main(String[] args)
{
System.out.println("welcome to packages");
}
}
interface I1
{
}
javac -d . Sample.java
java com.tcs.bank.account.Sample
welcome to packages
package com.tcs.bank.withdraw;
class Sample
{
public static void main(String[] args)
{
System.out.println("packages easy");
}
}
javac -d . Sample.java
java com.tcs.bank.withdraw.Sample
packages easy
com
|--tcs
|--bank
|--withdraw
|-Sample
import
public=======>Anywhere
protected====>package and subclass of another package
default======>package
private======>class
without import statement shall we access methods or variables from 1 package to another package.
yes,possible.
package com.state.info;
public class Info
{
public void apInfo()
{
System.out.println("jai ap");
}
public void tsInfo()
{
System.out.println("jai ts");
}
package com.state.requiredinfo;
import com.state.info.Info;
class Client
{
public static void main(String[] args)
{
Info i1=new Info();
i1.apInfo();
i1.tsInfo();
}
}
javac -d . Info.java
javac -d . Client.java
java com.state.requiredinfo.Client
jai ap
jai ts
package com.state.info;
public class Info
{
public void apInfo()
{
System.out.println("jai ap");
}
public void tsInfo()
{
System.out.println("jai ts");
}
package com.state.requiredinfo;
class Client
{
public static void main(String[] args)
{
com.state.info.Info i1=new com.state.info.Info();
i1.apInfo();
i1.tsInfo();
}
}
javac -d . Info.java
javac -d . Client.java
java com.state.requiredinfo.Client
jai ap
jai ts
1.Multitasking Introduction
2.Types of Multitasking
3.Thread class and Runnable Interface
4.Getting and setting names for Threads
5.Priorities of Thread
6.join(),yield(),sleep()
7.synchronization and Asynchronization
8.Daemon Threads
9.InterThread communication
10.Deadlock and starvation
Multitasking
The process of executing multiple tasks simultaneously.Here each task is a separate process(program)
Process based tasking is applicable for os level.
Each process(program) has separate memory address.
Processors(programs) are heavy weight.
Communication between 2 processors is exepensive
Switching from 1 processor to another processor is expensive
Thread
Thread
start()
run()
getName()
setName()
currentThread()
1.predefine Threads
The Threads which are already present java software(jdk).These Threads are developed
by java developers.
Ex
---
Main Thread
2.Userdefine Threads
The Threads which are not present java software(jdk).These Threads are developed
by java Programmers.
Ex
---
Mohan Thread
Ajay Thread
1. Thread is born
AjayThread a=new AjayThread()
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
3.Note:If we set priorities more than 10 and less than 1 then it will give
IllegalArgumentException
4.If we increase or decrease priorities for main thread it will be same for child thread.
5.If we increase or decrease priorities for child thread it will be differnt for main thread.
6.Bydefault priorities will be same for both threads main(5) and child(5) threads
So we not able to predict output.
8.If we decrease priority for child thread(3) when compared to main thread(5) child
thread will be executed last.
getPriority()
setPriority()
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
}
public static void main(String[] args)
{
AjayThread a=new AjayThread();=====>UserdefineThread is born
a.start();=======================>Userdefine Thread is ready to run
for(int i=1;i<=10;i++)
{
System.out.println("Predefine Thread");
}
}
}
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
}
public static void main(String[] args)
{
AjayThread a=new AjayThread();
a.run();
for(int i=1;i<=10;i++)
{
System.out.println("Predefine Thread");
}
}
}
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Userdefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
Predefine Thread
}
public static void main(String[] args)
{
Car c1=new Car();
c1.start();
Car c2=new Car();
c2.start();
Car c3=new Car();
c3.start();
}
}
car is going
car is going
car is going
}
}
userdefinethread
interface I1
{
}
class UserDefineThread implements Runnable,I1
{
public void run()
{
System.out.println("userdefinethread with multiple inheritance");
}
public static void main(String[] args)
{
UserDefineThread u=new UserDefineThread();
Thread t1=new Thread(u);
t1.start();
}
}
class Venky
{
}
class UserDefineThread extends Thread,Venky
{
public void run()
{
System.out.println("userdefinethread with multiple inheritance");
}
public static void main(String[] args)
{
UserDefineThread u=new UserDefineThread();
u.start();
}
}
Error
UserDefineThread extends Thread,Venky
}
}
class VenkyThread extends Thread
{
public void run()
{
}
public static void main(String[] args)
{
System.out.println(Thread.currentThread().getName());
Thread.currentThread().setName("PawanThread");
System.out.println(Thread.currentThread().getName());
System.out.println("================================");
VenkyThread v=new VenkyThread();
System.out.println(v.getName());
v.setName("MaheshThread");
System.out.println(v.getName());
}
}
main
PawanThread
Thread-0
MaheshThread
}
public static void main(String[] args)
{
System.out.println(Thread.currentThread().getName());
Thread.currentThread().setName("AjayThread");
System.out.println(Thread.currentThread().getName());
VenkyThread v=new VenkyThread();
v.start();
}
}
main
AjayThread
Thread-0
ManjuThread
}
public static void main(String[] args)
{
System.out.println(Thread.currentThread().getName());
System.out.println(Thread.currentThread().getPriority());
System.out.println("============================");
VenkyThread v=new VenkyThread();
v.start();
}
}
main
5
Thread-0
5
}
public static void main(String[] args)
{
System.out.println(Thread.currentThread().getName());
System.out.println(Thread.currentThread().getPriority());
Thread.currentThread().setPriority(7);
System.out.println(Thread.currentThread().getPriority());
System.out.println("============================");
VenkyThread v=new VenkyThread();
v.start();
}
}
main
5
7
Thread-0
7
}
public static void main(String[] args)
{
System.out.println(Thread.currentThread().getName());
System.out.println(Thread.currentThread().getPriority());
System.out.println("================================");
VenkyThread1 v=new VenkyThread1();
System.out.println(v.getName());
v.setPriority(8);
System.out.println(v.getPriority());
v.start();
for(int i=1;i<=5;i++)
{
System.out.println("main thread");
}
}
}
main
5
Thread-0
8
main thread
main thread
main thread
main thread
main thread
child thread
child thread
child thread
child thread
child thread
}
}
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()
}
catch(InterruptedException e)
{
}
}
}
public static void main(String[] args)throws InterruptedException
{
Demo d=new Demo();
d.start();
d.join();
for(int i=1;i<=10;i++)
{
System.out.println("Mohan thread");
}
}
}
d.join()
Ajay Thread
Ajay Thread
Ajay Thread
Ajay Thread
Ajay Thread
Ajay Thread
Ajay Thread
Ajay Thread
Ajay Thread
Ajay Thread
Mohan Thread
Mohan Thread
Mohan Thread
Mohan Thread
Mohan Thread
Mohan Thread
Mohan Thread
Mohan Thread
Mohan Thread
Mohan Thread
d.join(3000)
Ajay thread
Ajay thread
Mohan thread
Mohan thread
Mohan thread
Mohan thread
Mohan thread
Mohan thread
Mohan thread
Mohan thread
Mohan thread
Mohan thread
Ajay thread
Ajay thread
Ajay thread
Ajay thread
Ajay thread
Ajay thread
Ajay thread
Ajay thread
}
}
public static void main(String[] args)throws InterruptedException
{
Demo d=new Demo();
d.start();
d.yield();
for(int i=1;i<=10;i++)
{
System.out.println("Mohan thread");
}
}
}
Mohan thread
Mohan thread
Mohan thread
Mohan thread
Mohan thread
Mohan thread
Mohan thread
Mohan thread
Mohan thread
Mohan thread
Ajay thread
Ajay thread
Ajay thread
Ajay thread
Ajay thread
Ajay thread
Ajay thread
Ajay thread
Ajay thread
Ajay thread
synchronization
6.In case of synchronized block synchronization is applied to the few lines of code
and not to entire method.
class ClassRoom
{
synchronized void takeClass(String faculty)
{
for(int i=1;i<=10;i++)
{
System.out.println(i+" class is taking by : "+faculty);
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
}
}
}
}
class UserThread extends Thread
{
ClassRoom c1;
String faculty;
UserThread(ClassRoom c1,String faculty)
{
this.c1=c1;
this.faculty=faculty;
}
public void run()
{
c1.takeClass(faculty);
}
class Demo
{
public static void main(String[] args)
{
ClassRoom c1=new ClassRoom();
UserThread u1=new UserThread(c1,"Bhavadeesh");
UserThread u2=new UserThread(c1,"Durga");
u1.start();
u2.start();
}
}
class ClassRoom
{
void takeClass(String faculty)
{
System.out.println("1st 100 lines");
synchronized(this){
for(int i=1;i<=10;i++)
{
System.out.println(i+" class is taking by : "+faculty);
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
}
}
}
System.out.println("last 20 lines");
}
}
class UserThread extends Thread
{
ClassRoom c1;
String faculty;
UserThread(ClassRoom c1,String faculty)
{
this.c1=c1;
this.faculty=faculty;
}
public void run()
{
c1.takeClass(faculty);
}
class Demo
{
public static void main(String[] args)
{
ClassRoom c1=new ClassRoom();
UserThread u1=new UserThread(c1,"Bhavadeesh");
UserThread u2=new UserThread(c1,"Durga");
u1.start();
u2.start();
}
}
Asynchronization
class ClassRoom
{
void takeClass(String faculty)
{
for(int i=1;i<=10;i++)
{
System.out.println(i+" class is taking by : "+faculty);
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
}
}
}
}
class UserThread extends Thread
{
ClassRoom c1;
String faculty;
UserThread(ClassRoom c1,String faculty)
{
this.c1=c1;
this.faculty=faculty;
}
public void run()
{
c1.takeClass(faculty);
}
class Demo
{
public static void main(String[] args)
{
ClassRoom c1=new ClassRoom();
UserThread u1=new UserThread(c1,"Bhavadeesh");
UserThread u2=new UserThread(c1,"Durga");
u1.start();
u2.start();
}
}
Daemon Thread
1.A Thread which will execute in background along with another Thread.
2.The purpose of Daemon Thread is to provide support or services to non DaemonThreads.
3.We cannot create Daemon thread for main thread(predefine thread).
Examples
Methods
u1.start();
System.out.println("main thread");==============>main thread
}
}
}
public static void main(String[] args)
{
UserDefineThread u1=new UserDefineThread();
u1.start();
System.out.println("main thread");
}
}
u1.setDaemon(true)
main thread main thread
child thread child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
}
}
InterThread communication
1.wait()
when a thread is expecting updation or notification from another thread then we have
to use wait() and then thread will goes to waiting state.
2.notify()
when a thread is sending or giving updation or notification to the single waiting thread then we have to use notify().
3.notifyAll()
when a thread is sending or giving updation or notification to the multiple waiting threads then we have to use
notifyAll().
class AjayThread extends Thread
{
public void run()
{
int sum=0;
for(int i=1;i<=100;i++)
{
sum=sum+i;
}
}
}
class Demo
{
public static void main(String[] args)throws Exception
{
AjayThread a1=new AjayThread();
a1.start();
System.out.println(a1.sum);
}
}
case-3 child thread got chance and performed some logic and main got chance
0 to 5050
}
}
}
class Demo
{
public static void main(String[] args)throws Exception
{
AjayThread a1=new AjayThread();
a1.start();
synchronized(a1)
{
System.out.println("main got chance 1st and waiting");
a1.wait();
System.out.println("main got updation");
System.out.println(a1.sum);
}
}
}
output
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 Demo
{
public static void main(String[] args)throws Exception
{
AjayThread.mt =Thread.currentThread();
AjayThread a1=new AjayThread();
a1.start();
for(int i=1;i<=10;i++)
{
System.out.println("main Thread");
Thread.sleep(1000);
}
}
}
Here child thread calling join method on main thread object and child thread will stops its execution and wait for
until completion of main thread.
main Thread
main Thread
main Thread
main Thread
main Thread
main Thread
main Thread
main Thread
main Thread
main Thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
}
}
class A
{
public synchronized void d1(B b)
{
System.out.println("Thread1 starts execution of d1 method");
try
{
Thread.sleep(2000);
}
catch(Exception e)
{
}
System.out.println("Thread1 trying to call bis last method");
b.last();
}
public synchronized void last()
{
System.out.println("Inside A last method");
}
}
class B
{
public synchronized void d2(A a)
{
System.out.println("Thread2 starts execution of d2 method");
try
{
Thread.sleep(2000);
}
catch(Exception e)
{
}
System.out.println("Thread2 trying to call Ais last method");
a.last();
}
public synchronized void last()
{
System.out.println("Inside B last method");
}
}
class MyThread extends Thread
{
A a=new A();
B b=new B();
public void m1()
{
this.start();
a.d1(b);
}
public void run()
{
b.d2(a);
}
}
class Demo
{
public static void main(String[] args)
{
MyThread t=new MyThread();
t.m1();
}
}