Core Java Complete Marerial
Core Java Complete Marerial
Ratan
1|Page
Corejava Material RATANIT [email protected] Mr.Ratan
2|Page
Corejava Material RATANIT [email protected] Mr.Ratan
3|Page
Corejava Material RATANIT [email protected] Mr.Ratan
4|Page
Corejava Material RATANIT [email protected] Mr.Ratan
JAVA introduction:
Author : James Gosling
Your best Trainer : Mr. Ratan
Vendor : Sun Micro Systems (which has since merged into Oracle Corporation)
Importance of core java: According to the SUN 3 billion devices run on the java language only.
✓ Java is used to develop Desktop Applications such as MediaPlayer, Antivirus etc.
✓ Java is Used to Develop Web Applications such as durgasoft.com, irctc.co.in etc.
✓ Java is Used to Develop Enterprise Application such as Banking applications.
✓ Java is Used to Develop Mobile Applications.
✓ Java is Used to Develop Embedded System.
✓ Java is Used to Develop SmartCards.
✓ Java is Used to Develop Robotics.
✓ Java is used to Develop Games…. etc.
5|Page
Corejava Material RATANIT [email protected] Mr.Ratan
Importance of java: Most of the technologies& frame works depend on Core java.
6|Page
Corejava Material RATANIT [email protected] Mr.Ratan
Reserved words (53) : Keywords (50) + constants (3) = Reserved Words (53)
Separators in java:
Symbol name usage
() parentheses used to contains list of parameters & contains expression.
{} braces block of code for class, method, constructors & local scopes.
. period used to separate package names from sub packages. And also
used for separate a variable,method from a reference type.
7|Page
Corejava Material RATANIT [email protected] Mr.Ratan
Java Comments:
✓ Comments are used to write the detailed description about application logics to understand the
logics easily.
✓ The main objective of comments is application maintenance will become easy.
✓ Comments are non-executable code these are ignored during compilation.
Multi line Comments: To write the description in more than one line.
Starts with : /*
Ends with : */
Syntax: /* satement-1
statement-2
;;;;;;;;;;;;;;
statement-n
*/
Downloading Api document: it contains detailed description about how to use java product.
To download java api document use fallowing link : http://docs.oracle.com/javase/8/docs
8|Page
Corejava Material RATANIT [email protected] Mr.Ratan
In c-lang the predefined cpp language the predefined In java predefined support is
support is available in the is maintained in the form of available in the form of
form of header files. header files. packages.
Ex:- stdio.h , conio.h Ex:- iostream.h Ex: java.lang, java.io,java.awt
methods toUpperCase()
In above first example we are In above first example we are
using printf predefined in above exampe we are using
using cout predefined
function that is present in two classes(String,System) these
function that is present in
stdio.h header file hence stdio.h header file hence classes are present in java.lang
must include that header file must include that header file package must import it by using
by using #include statement. by using #include statement. import keyword.
Ex:#include<stdio.h> Ex:#include<stdio.h> a) Import java.lang.*; all lasses
b)Import java.lang.System; required
Import java.lang.String; classes
In C lang program execution In C lang program execution
In above two approachaes 2nd good
starts from main method starts from main method
called by Operating system. called by Operating system. In java execution starts from
main called by JVM
To print data use printf() To print data use cout To print data use System.out.println()
9|Page
Corejava Material RATANIT [email protected] Mr.Ratan
Packages contains:
Java predefined support in the form of pakcages, the package contains 6-elements
i. Classes
ii. Interfaces
iii. Enum
iv. Annotations
v. Exceptions
vi. Errors
10 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Simple
✓ Java technology has eliminated all the difficult and confusion-oriented concepts like pointers,
multiple inheritance, operator overloading... etc from the java language.
✓ Java uses c, cpp syntaxes mainly hence who knows C, CPP for that java is simple language.
Platform Independent
✓ Once we develop the application by using any one operating system(windows) that application runs
only on same operating system is called platform dependency.
ex: C, CPP
✓ Once we develop the application by using any one operating system(windows) that application runs
on all operating system is called platform independency.
ex: java, python
11 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Architectural Neutral
One we develop the applications using any one Architecture/hardware (RAM, Hard Disk),
that application will run on any architecture(hardware) is called Architectural Neutral.
Portable
In Java the applications are supports in any OS (operating system) and any
Architecture(hardware) hence we can say java is a portable language.
Object Oriented
Java is object oriented because it is representing total data of the class in the form of object.
Oops are methodologies to design the application, it’s supported all oops features like,
o Inheritance
o Polymorphism,
o Encapsulation
o Cupling ......etc
Robust
Robust simply means strong. Java is robust because:
Automatic memory management in java with the help of garbage collector.
Strong in exception handling, type checking machanisum, supports Datastructrs.
The above all the points makes java robust.
Secure
To provide security Java provides one component inside JVM called Security Manager.
To provide security to applications java.security package giving some classes & interfaces.
Dynamic
C-languae is static language so the memory allocation is done during compile time.
Java is dynamic language the memory allocation done at runtime.
Distributed
using java it is possible to develop distributed applications...RMI,Webservices…etc
Interpreted
JVM mostly uses interpreter to convert byte code to machine dependentcode.
High Performance
Java support features like Robust, Security, Platform Independent, Dynamic and so on
then that technology is high performance.
Multithreaded
Executing more than one thread simultaneously is called multithreading.
Main advantage of multithreading is used to develop multimedia, gaming, web application.
12 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
13 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
5. Mobile applications:
✓ The applications which are design for mobile platform are called mobile applications.
✓ We are developing mobile applications by sing android,IOS,j2me…etc
✓ There are three types of mobile applications
o Web-application (gmai l ,online shopping,oracle …etc)
o Native (run on device without internet or
browser)ex:phonecall,calculator,alaram,games
These are install from application store& to run these apps internet not required.
o Hybrid (required internet data to launch) ex:whats up,facebook,LinkedIn…etc
These are installed form app store but to run this application internet data required.
14 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Open the Google site type the jdk8 download as shown below.
After clicking above link we will get below window then accept license agreement by clinking
radio button then choose the software based on your operating system and processor to download.
15 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Step 3: set the path to run the application from any disk.
In C language we can run the application only form turbo-C folder.
But in java it is possible to run the java files in any local disk (D: , E: , F: …etc.) to achive this
when wehave to set the path.
After path setting open the command prompt type javac command then you will get list of
commands then decide java is working properly your system.
16 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
NOTE: The coding standards are mandatory for predefined library & optional for user defined library but
as a java developer it is recommended to fallow the coding standards for user defined library also.
Note: Initial 20-days classes use the editor to develop the application, after that use the IDE to design
to develop the application. (Remember realtime we are using only IDE but not editor).
17 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
IDE download :
https://www.eclipse.org/downloads/packages/release/2018-12/r/eclipse-ide-java-developers
import java.lang.System;
import java.lang.String;
class Test
18 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
In above example we are using two predefined classes(String , System) & these are present in
java.lang package hence must import that package by using import statement.
There are two approaches to import the classes in java,
1) Import all classes of particular package.
a. Import java.lang.*;
2) Importing application required classes.
a. Import java.lang.System;
b. Import java.lang.String;
Note: The source file is allows declaring only one public class, if we are trying to declare more than one
public class then compiler generate error message.
Application location:
D: (any disk)
|-->java5pm (any folder)
|-->Ratan.java (your file name)
19 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Compiler responsibilities:
✓ Compiler check the syntax errors, if the application contains syntax errors then compiler will
generate error message in the form of compilation error.
✓ If the application does not contain syntax errors then compiler translate .java to .class file.
Note: In java compiler generate .class files based on number of classes present in source file.
If the source file contains 100 classes after compilation compiler generates 100 .class files.
Step-4: Execution process. Run /execute the java application by using java command.
Syntax: Java class-name
Java Test
JVM responsibilities:
✓ JVM wills loads corresponding .class file byte code into memory.
✓ After loading .class file JVM calls main method to start the execution process.
D:\java5pm>java Test
Ratan world
D:\java5pm>java A
Error: Main method not found in class A, please define the main method as:
D:\java5pm>java B
Error: Main method not found in class B, please define the main method as:
D:\java5pm>java CCC
Error: Could not find or load main class CCC
20 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
21 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
22 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Conclusion 1:
Java contains 14 predefined packages but the default package in java is java.lang
Conclusion -2:
The source file is allows you to declare only one public class, if you are declaring more than one
public class compiler generating error message.
Test.java
public class Test {
}
public class A{
}
error: class A is public, should be declared in a file named A.java
Conclusion-3
✓ The coding conventions are mandatory for predefined library & optional for user defined but as a
java developer must fallow the coding conventions for use defined library also.
✓ The below example compiled & executed but it is not recommended because the class name
starting with lower case letters.
class test
{ public static void main(String[] args)
{ System.out.println("Ratan World!");
}
}
G:\>java test
Ratan World!
Conclusion-4
D:
|-->java5pm
|-->A.java
|-->B.java
|-->C.java
javac A.java One file is compiled(A.java)
javac B.java C.java Two files are compiled
javac *.java All files are compiled
javac Emp*.java files prefix with emp compiled (EmpId.java EmpName.java…)
javac *Emp.java files suffix with emp compiled (XEmp.java YEmp.java…)
Possible to compile more than one file at a time, but possible to execute only one class
file(the class which contains main method).
23 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Conclusion -5:
The class which contains main method is called Mainclass and java allows declaring multiple
main class in a single source file.(but it is recommended to declare only one main class ).
class Test
{ public static void main(String[] args)
{ System.out.println("Test World!");
}
}
class A
{ public static void main(String[] args)
{ System.out.println("A World!");
}
}
class B
{ public static void main(String[] args)
{ System.out.println("B World!");
}
}
D:\java5pm>java Test
Test World!
D:\java5pm>java A
A World!
D:\java5pm>java B
B World!
Conclusion-6:
24 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Print( ) vs Println ( ):
Print(): This method used to print the data after printing control present in same line.
Println(): This method used to print the data after printing control present in new line.
class Test
{ public static void main(String[] args)
{ System.out.print("ratan");
System.out.print("anu");
System.out.println("durga");
System.out.println("sravya");
}
}
Output :
ratananudurga
sravya
Escape Sequences:
A character preceded by a backslash (\) is an escape sequence and has special meaning to the
compiler. The following table shows the Java escape sequences.
System.out.println("hi\t\tratan\t\tsir");
System.out.println("hi\nratan\nsir");
System.out.println("hi\bratan\bsir");
}
}
25 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Java Tokens:
Smallest individual part of a java program is called Token &It is possible to provide n number of
spaces in between two tokens.
class Test
{ public
static void main(String[] args)
{ System.
out. println ("sravya");
}
}
Tokens are---------→class,test,{,”,[ …………….etc
26 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Except Boolean and char remaining all data types consider as a signed data types because we can
represent both +ve & -ve values.
Printing variables:
27 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
int eid=111;
System.out.println(eid); //valid
System.out.println("eid"); //invalid
System.out.println('eid'); //invalid
String:
✓ String is not a data type & it is a class present in java.lang package to represent group of
characters or character array enclosed with in double quotes.
✓ The default value of the String is null
String ename="ratan";
System.out.println(ename); //ratan
String str;
System.out.println(str); //null
double d=20.5;
System.out.println(d);
28 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
}
}
ex-2: A double variable can provide precision up to 15 to 16 decimal points as compared to float
precision of 6 to 7 decimal digits.
class Test
{ public static void main(String[] args)
{ float f=10.123456789f;
System.out.println(f);
double d=10.123456789123456789;
System.out.println(d);
}
}
E:\>java Test
10.123457
10.123456789123457
Therefore a number like 3.14159265359 would most likely get rounded to 3.141593.
class Test
{ public static void main(String[] args)
{ float f=3.14159265359f;
System.out.println(f);
double d=10.123456789123456789;
System.out.println(d);
}
}
E:\>java Test
3.1415927
10.123456789123457
29 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Java identifiers:
Every name in java is called identifier such as, Class-name, Method-name, Variable-name…etc
Identifier contains (a-z , A-Z , 0-9 , _ , $) but not start with number & not allowed special characters.
2. Java identifiers are case sensitive of course java is case sensitive programming language. The
below three declarations are different & valid.
class Test
{ int a=10;
Int A=20;
}
5. There is no length limit for identifiers but is never recommended to take lengthy names because
it reduces readability of the code.
6. It is possible to use predefined class names & interfaces names as a identifier but it is not
recommended.
class Test
{ public static void main(String[] args)
{ int String = 10;
30 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
System.out.println(String);
ii. It is not possible to take the underscores starting & ending of the number.
int num = _2323;
int num = 2323_;
int num = _2323_;
iii. it is not possible to take the underscores before & after the decimal point.
double d = 232_.23;
double d = 232._23;
double d = 232_._23;
iv. it is not possible to take the undersocres before & after the constant.
float f = 10.5_f;
float f = 10.5f_;
float f = 10.5_f_;
31 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
v. it is not possible to take the uderscores before & after the representation.
int a = 0B_00110
int a = _0B00110
int a = _0B_00110
1 = enable 0 = desable
64 32 16 8 4 2 1
1 0 1 0 = 10
1 0 1 1 = 11
1 1 1 1 = 15
1 0 1 0 1 = 21
1 0 1 0 1 0 = 42
1 0 0 1 1 1 0 = 78
ex-1: Binary data.
class Test
{ public static void main(String[] args)
{ int x1 = 0b1100;
System.out.println(x1);
int x2 = 0B11111;
System.out.println(x2);
}
}
ex-2: octal data
class Test
{ public static void main(String[] args)
{ int a = 0123;
System.out.println(a);
int b = 0222;
System.out.println(b);
}
}
ex-3: decimal data : by default our data is decimal data.
class Test
{ public static void main(String[] args)
32 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
{ int a = 123;
System.out.println(a);
int b = 222;
System.out.println(b);
}
}
ex-4: Hexa decimal number.
class Test
{ public static void main(String[] args)
{ int a = 0x123;
System.out.println(a);
int b = 0X222;
System.out.println(b);
int c = 0x1af;
System.out.println(c);
}
}
class Test
{
public static void main(String[] args)
{
int i = 15, j = 39;
System.out.println(Integer.toBinaryString(i));
System.out.println(Integer.toBinaryString(j));
33 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
34 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
37) For the class types what are the default values?
38) Define the camel case?
39) How to calculate the ranges of the data types?
40) What is the difference between float & double?
*****Thank you********
35 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
3. Transfer statements
goto
break
continue
try
return
case 1:
if (20 > 10) {
System.out.println("20 is greater than 10");
}
case 2:
int x = 20, y = 10;
if (x > y) {
System.out.println("x is greater than y");
}
36 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
If syntax:
if (condition)
{ true body;
}
else
{ false body;
}
Case-1:
class Test
{ public static void main(String[] args)
{ int age = 20;
if (age>22)
{ System.out.println("Eligible for marriage");
}
else
{ System.out.println("not Eligible for marriage ");
}
}
}
Case -2: To the if statement it is possible to provide Boolean constants directly.
if (true)
{ System.out.println("true body");
}
else
{ System.out.println("false body");
}
Case -3: in c-language 0-false & 1-true but these conventions are not allowed in java.
if (0)
{ System.out.println("true body");
}
error: incompatible types: int cannot be converted to boolean
37 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
case 5: The curly brasses are optional but without curly braces it is possible to take only one statement
that should not be a initialization.
if (true)
System.out.println("true body");
else
System.out.println("false body");
Observation: without braces it is possible to take only one statement that should not be a initialization.
if (true)
int a=10;
error: variable declaration not allowed here
Assignment 1: Take the number from end user check it is even or odd?
Assignment 2: Take the two numbers from end user print the bigger number?
Assignment 3: Take the year from end user check it is leap year or not?
Assignment 4: Take the user name & password from end user.
Check the condition print the the message login Success or fail.
Assignment-5: what is the difference between next() & nextLine() write one example.
scanner.next() : to read the String data
scanner.nextLine() : to read the String data.
38 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
case 6: To take the input from end user use Scanner object.
Scanner class present in java.util package so import the class using import statement.
Scanner class introduced in java-5.
To read the String data: next() "adi ratan" : next() method will take the data upto space(one word)
To read the complete line : nextLine() "Addanki ratan" : it will read the complete line with spaces.
import java.util.Scanner;
class Test
{ public static void main(String[] args)
{ Scanner s = new Scanner(System.in);
if (esal>10000)
{ System.out.println("Very Good employeee...");
System.out.println(eid+" "+ename+" "+esal);
}
else
{ System.out.println("Good employeee...");
System.out.println(eid+" "+ename+" "+esal);
}
s.close();
}
}
E:\>java Test
Enter emp id
anu
Exception in thread "main" java.util.InputMismatchException
39 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Case 2: in else-if statement taking else block is optional but recommanded to take the else block.
class Test
{ public static void main(String[] args)
{ int a = 10;
if (a==10)
{ System.out.println("Tharun don't sleep");
}
else if (a==10)
{ System.out.println("venkat don't sleep");
}
}
}
40 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Case-3: in else-if multiple conditions are matched it will execute first match.
class Test
{ public static void main(String[] args)
{ int a = 10;
if (a==10)
{ System.out.println("Tharun don't sleep");
}
else if (a==10)
{ System.out.println("venkat don't sleep");
}
else
{ System.out.println("ramu don't sleep");
}
}
}
Case-4: Taking input from end user checking it is positive or negative or zero.
import java.util.Scanner;
class Test
{ public static void main(String[] args)
{ Scanner s = new Scanner(System.in);
System.out.println("Enter a num:");
int num = s.nextInt();
if (num<0) { System.out.println("Number is Negative...."); }
else if (num>0) { System.out.println("Number is positive....."); }
else { System.out.println("Zerooooo.........."); }
s.close();
}
}
Case 5:
class Test
{ public static void main(String[] args)
{ int examscore=77;
char grade;
if (examscore>90) { grade='A'; }
else if (examscore>80) { grade='B'; }
else if (examscore>70) { grade='C'; }
else if (examscore>60) { grade='D'; }
else { grade='E'; }
System.out.println("The Grade is :"+grade);
}
}
41 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Switch statement:
✓ Inside the switch possible to declare more than one case but it is possible to declare only one default.
✓ Based on the provided argument the matched case will be executed if the cases are not matched
default will be executed.
✓ Float,double,long is not allowed as a switch argument because these are having too large values.
✓ Boolean not allowed as switch argument because it contains only two values(true,false).
Syntax:
switch(argument)
{
case label-1 : statements;
break;
case label-2 : statements;
break;
| |
| |
case label-n : statements;
break;
default : statements;
break;
}
Case 1:
class Test
{ public static void main(String[] args)
{ int a=10;
switch (a)
{ case 10:System.out.println("ratan");
break;
case 20:System.out.println("anu");
break;
default:System.out.println("durga");
break;
}
}
}
42 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Case 2 :
✓ Inside the switch statement beak is optional.
✓ If we are not declaring break statement then from the matched case onwards up to the next
break statement will be executed, if there is no break statement then end of the switch will be
executed.
✓ The above situation is called as fall though inside the switch.
class Test
{ public static void main(String[] args)
{ int a=10;
switch (a)
{ case 10:System.out.println("10");
case 20:System.out.println("40");
break;
default: System.out.println("default");
break;
}
}
}
Case 6: Invalid : Inside the switch independent statements are not allowed. If we are declaring
the statements that statement must be inside the case or default.
int x=10;
switch(x)
{ System.out.println("Hello World");
}
43 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Case 7 : In switch it is possible to declare the default at starting or middle or end of the switch.
int a=100;
switch (a)
{ default: System.out.println("default");
case 10:System.out.println("10");
}
Case 8: Inside the switch the case labels must be unique; if we are declaring duplicate case labels
the compiler will raise compilation error “duplicate case label”.
int a=10;
switch (a)
{ case 10:System.out.println("ratan");
case 10:System.out.println("anushka");
}
Case 9 : Inside the switch for the case labels & switch argument it is possible to provide expressions
int a=100;
switch (a+10)
{ case 110 :System.out.println("ratan");
case 10*5 :System.out.println("durga");
}
Case 10: Invalid
✓ Inside the switch the case label must be constant values.
✓ If we are declaring variables as a case labels the compiler will generate error.
int a=10;
switch (a)
{ case a:System.out.println("anushka");
}
Valid
o possible to declare final variables as a case label. Because the final variables are constants.
o The final variables are replaced with constants during compilation.
final int a=10;
switch (a)
{ case a:System.out.println("anushka");
}
Case 11:
✓ Inside the switch the case label must match with provided argument data type otherwise
compiler will raise compilation error “incompatible types”.
✓ In below example we are passing String is a switch argument hence the case labels must be
Strings constants.
String str=”aaa”;
Switch (str)
{ case "aaa" :System.out.println("ratan");
case 'a' :System.out.println("durga");
}
44 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Case 12 :
✓ Inside switch the case labels must be within the range of provided argument data type otherwise
compiler will raise compilation error “possible loss of precision”.
✓ In below example we are passing byte as a switch argument hence the case labels must be
within the range of byte.
byte b=127;
switch (b)
{ case 127:System.out.println("ratan");
case 128:System.out.println("anu");
}
case 13 : Unicode values : a=97 A=65
int a=97; char ch='d';
switch (a) switch (ch)
{ case 99:System.out.println("ratan"); { case 100:System.out.println("ratan");
case 'a':System.out.println("anu"); case 'a':System.out.println("anu");
} }
45 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Iteration Statements:
By using iteration statements, it is possible to execute group of statements repeatedly or more
number of times.
There are 4-iteration statements.
1) For
2) For-each
3) while
4) do-while
1 2 5 4 7
f
for (initialization f
;condition 5 ;increment/decrement
f f )
{ o o f o o
r Body; r3 o
6 r r
} ( (i
o r
6 (i (i
i n
r (i
f n n
n i(i n
o i i
Case 1: i tn ri t t
t
With out for loop ii t(i i i By using for loop
class Test i a
t i
n a a class Test
{ a
public static lii
void main(String[] ia args) li li { public static void main(String[] args)
{ liSystem.out.println("ratan");
za lit z z { for (int i=0;i<5;i++)
z System.out.println("ratan");
lia iz a a { System.out.println("Ratan");
aSystem.out.println("ratan");
tz aa t t }
t System.out.println("ratan");
ia tli i i }
} i o
t i
z o o }
} o n
i o
a n n
n ;o n
t ; ;
cn i; c c
; o
; c
o o o
c n
c o
n n n
o d
o ;n d d
46 | P a g e n in d
c i i
d td io t t
i ii t
n i i
t o
t i
d o o
Corejava Material RATANIT [email protected] Mr.Ratan
Case 2: Inside the for loop initialization part is optional but semicolon is mandatory.
int i=0;
for (;i<10;i++)
{ System.out.println("durga");
}
47 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
✓ Initialization part it is not possible to declare the data type two times whether it is same
type or different types.
✓ But it is possible to declare the single data type with more than one variable.
Invalid
for (int i=0,int j=0 ;i<10;i++)
{ System.out.println("ratan");
}
Valid
for (int i=0,j=0;i<10;i++)
{ System.out.println("ratan");
}
Conditional part :
Inside for loop conditional part is optional, if we are not providing condition at the time of
compilation compiler will generate true constant.
for (int i=0;;i++)
{ System.out.println("ratan");
}
increment/decrement :
case 1 : Inside the for loop increment/decrement part is optional.
for (int i=0;i<10;)
{ System.out.println("durga");
I++;
}
Case 2 : In the increment/decrement it is possible to take the n number of SOP() statements and
each and every statement is separated by comma(,).
for (int i=0;i<10;System.out.println("aruna"),System.out.println("sravya"))
{ System.out.println("sravya");
i++;
}
Case 1: error: Unreachable statement
✓ If the control unable to enter in particular area is called unreachable statement.
✓ We will get the unreachable code when we declare only Boolean constants(true,false).
✓ When we will give true condition the remaining code is unreachable
✓ when we will give false condition the body is unreachable.
Rest of the code unreachable
for (int i=1;true;i++)
{ System.out.println("ratan");
}
System.out.println("rest of the code");
Loop body is unreachable
for (int i=1;false;i++)
{ System.out.println("ratan");
}
48 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Case 2: Valid
✓ When you provide the condition even though that condition is represent infinite loop compiler is
unable to find unreachable statements,because there may be chance of condition fail.
✓ When you provide Boolean constants as a condition then compiler is identifying unreachable
statement because compiler knows that condition never change.
for (int i=1;i>0;i++ )
{ System.out.println("durga");
}
System.out.println("rest of the app");
Case 4 : Inside the for loop each and every part is optional but semicolon is mandatory.
for(;; ) represent infinite loop because the condition is always true.
Case 5: error : unreachable statement
for ( ; ; )
{ System.out.println("ratan");
}
System.out.println("anu"); //error: unreachable statement
For-each loop: (introduced in 1.5 version)
class Test
{ public static void main(String[] args)
{ int[] a={10,20,30};
System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);
49 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
while (Boolean-expression)
{ body;
}
Case 1:
class Test
{ public static void main(String[] args)
{ int i=0;
while (i<10)
{ System.out.println("ratan");
i++;
}
}
50 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Case 5 : Just to check the data & print the data use while loop.
while (itr.hasNext())
{ System.out.println(itr.next());
}
Do-While:
✓ If we want to execute the loop body at least one time them we should go for do-while statement.
✓ In do-while first body will be executed then only condition will be checked.
Syntax: do
{ //body of loop
} while(Boolean-condition);
Case 1:
class Test
public static void main(String[] args)
{ int i=0;
do
51 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
{ System.out.println("ratan");
i++;
}while (i<10);
}
}
break: Break is used to stop the execution & it is possible to use the break statement only two areas.
✓ Inside the switch statement.
✓ Inside the loops.
52 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
class Test
{ public static void main(String[] args)
{ for (int i=0;i<10;i++)
{ if (i==5)
break;
System.out.println(i);
}
}
}
Case 2: if we are using break outside switch or loops the compiler will raise compilation error
“break outside switch or loop”
if (true)
{ System.out.println("ratan");
break;
System.out.println("nandu");
}
Continue: it is used skip the current iteration and it is continuing the rest of the iterations normally.
class Test
{ public static void main(String[] args)
{ for (int i=0;i<10;i++)
{ if (i==5)
continue;
System.out.println(i);
}
}
}
Assignments : if-else
Assignment 1: take the number from end user check it is even or odd?
Assignment 2: take the two numbers from end use print the bigger number?
Assignemnt 3: Take the number from end user check it is positive or Negative, and print it is even or odd.
(use nested if-else condition).
ouptut :
enter a num : 2
Number is positive & even
ouptut :
enter a num : 3
Number is positive & odd
ouptut :
enter a num : -6
53 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Ans 1:
import java.util.Scanner;
class Test
{ public static void main(String[] args)
{ Scanner s = new Scanner(System.in);
System.out.println("Enter a number:");
int num = s.nextInt();
if (num%2==0)
{ System.out.println("Even Number");
}
else
{ System.out.println("Odd number");
}
s.close();
}
}
Ans2:
import java.util.Scanner;
class Test
{ public static void main(String[] args)
{ Scanner s = new Scanner(System.in);
System.out.println("Enter first number:");
int n1 = s.nextInt();
System.out.println("Enter second number:");
int n2 = s.nextInt();
if (n1>n2)
{ System.out.println("First number is Bigger.....");
}
else
{ System.out.println("Second number is Bigger.....");
}
s.close();
}
}
54 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Ans-3:
import java.util.Scanner;
class Test
{ public static void main(String[] args)
{ Scanner s = new Scanner(System.in);
System.out.println("Enter number:");
int num= s.nextInt();
if (num>0)
{ if (num%2==0)
{ System.out.println("Number is positive & even");
}
else
{ System.out.println("Number is positive & odd");
}
}
else
{ if (num%2==0)
{ System.out.println("Number is Negative & even");
}
else
{ System.out.println("Number is Negative & odd");
}
}
s.close();
}
}
55 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
56 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Java Variables:
✓ Variables are used to store the constant values by using these values we are achieving project
requirements.
o class type
Test t; o Variable argument type.
Employee emp; Int… a;
57 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
o Annotation type
Override e;
✓ Variable declaration is composed of four components in order,
o Zero or more modifiers. public int a=10;
o The variable type. public -->modifier (specify permission)
o The variable name. int -->data type (type of the variable)
o Constant value/ literal a -->variable name
public final int x=100; 10 -->constant value or literal;
; -->statement terminator
Local variables:
❖ The variables which are declare inside a method or constructor or blocks those variables are called
local variables.
class Test
{ public static void main(String[] args)
{ //local variables
int a=10;
int b=20;
System.out.println(a+b);
}
58 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
❖ It is possible to access local variables only inside the method or constructor or blocks only, it is not
possible to access outside of method or constructor or blocks.
void add()
{ int a=10;
System.out.println(a); //possible
}
void mul()
{ System.out.println(a); //not-possible
}
❖ Local variables memory allocated when method starts & memory released when method completed.
Instance Area:
void m1() //instance method
{ Logics here //instance area
}
Static Area:
Static void m1() //static method
{ Logics here //static area
}
✓ The variables which are declare inside a class but outside of methods are called instance variables.
✓ The scope (permission) of instance variable is inside the class having global visibility.
✓ Instance variables memory allocated during object creation& memory released when object is
destroyed.
✓ Instance variables are stored in heap memory.
59 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
✓ In java program execution always starts from main method called by JVM.
✓ The JVM is responsible to execute only main method so must call the user defined method (m1)
inside the main method then only user method will be executed.
ex: Observation
class A
{ int num=10; //instance variable
}
class Test
{ void m1() //instance method of different class
{ A a = new A();
System.out.println(a.num);
}
}
60 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Note: Always access the instance members (variables & method) by using object.
Operator overloading:
✓ One operator with more than one behavior is called operator over loading.
✓ Java is not supporting operator overloading concept, but only one implicit overloaded operator
in java is + operator.
o If two operands are integers then plus (+) perform addition.
o If at least one operand is String then plus (+) perform concatenation.
class Test
{ public static void main(String[] args)
{ System.out.println(10+20); //addition
System.out.println(“ratan”+”anu”); //concatenation
int a=10;
int b=20;
int c=30;
System.out.println(a);
System.out.println(a+"---");
System.out.println(a+"---"+b);
System.out.println(a+"---"+b+"----");
System.out.println(a+"---"+b+"----"+c);
}
}
❖ The variables which are declared inside the class but outside of the methods with static modifier are
called static variables.
❖ Scope of the static variables with in the class global visibility.
❖ Static variables memory allocated during .class file loading & memory released at .class file
unloading.
❖ Static variables are stored in method area.
61 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
class Test
{ //static variables
static int a=100;
static int b=200;
//static method
public static void main(String[] args)
{ System.out.println(Test.a);
System.out.println(Test.b);
Static variables calling: There are three ways to access the static members
class Test
{ static int x=100; //static variable
public static void main(String[] args)
{
62 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Example:
✓ It is possible to create the objects inside the main method & inside the user defined methods also.
✓ When we crate the object inside the method, the scope of the object is only within the method.
✓ When we create object inside method that object is destroyed when method completed, if any other
method required object then create the object inside that method.
class Test
{ int a=10;
int b=20;
static void m1()
{ Test t = new Test();
System.out.println(t.a);
System.out.println(t.b);
}
static void m2()
{ Test t = new Test();
System.out.println(t.a);
System.out.println(t.b);
}
public static void main(String[] args)
{ Test.m1(); //static method calling
Test.m2(); //static method calling
}
}
ex 1: JVM will assign default values only for the instance & static variables but not for local variable .
class Test
{ int a;
Static boolean b;
public static void main(String[] args)
{ Test t=new Test();
System.out.println(t.a);
System.out.println(Test.b);
63 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
}
}
ex 2:
✓ JVM does not assign default values for local variables.
✓ In java before using local variables must initialize some values to the variables otherwise compiler
generates compilationerror “variable a might not have been initialized”.
Case 1: Invalid : Local variable not initialized so JVM will generate error message.
class Test
{ public static void main(String[] args)
{ int a;
System.out.println(a);
}
}
error: variable a might not have been initialized
case 2: Valid : Before using local variable must initialize the values.
class Test
{ public static void main(String[] args)
{ double d;
;;;;;
d=10.5;
System.out.println(d);
}
}
✓ Class is a logical entity it contains logics whereas object is physical entity it is representing memory.
✓ Class is blue print it decides object creation without class we are unable to create object.
✓ Based on single class it is possible to create multiple objects but every object occupies memory.
✓ We are declaring the class by using class keyword but we are creating object by using new keyword.
64 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Dog is a single class but here we created three objects means three different memories are created.
class Test
{ int a=10;
static int b=20;
public static void main(String[] args)
{ Test t = new Test();
System.out.println(t.a);
System.out.println(Test.b);
t.a=111;
Test.b=222;
System.out.println(t.a);
System.out.println(Test.b);
65 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
}
}
✓ In case of instance variables the JVM will ✓ In case of static variables irrespective of
create separate copy of memory for each object creation per class single memory is
and every object. allocated.
✓ Always access the instance by using object. ✓ Always access the static by using clas-name.
66 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
✓ Inside the classes it is not possible to write the business logics directly, so inside the class declares the
method to write the logics of the application.
✓ Methods are used to write the business logics of the application.
Coding convention:
Method name starts with lower case letter and every inner word starts with uppercase letter
ex: post() , charAt() , toUpperCase() , compareToIgnoreCase()……etc
Note: Whether it is an instance method or static method the methods are used to provide business
logics of the application.
Instance method:
Void add()
{ body : logics here : instance area
}
67 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Instance member’s memory is allocated during object creation hence accesses the instance
members by using object-name (reference-variable).
Objectname.instancemethod( );
Test testobj = new Test();
testobj.add( );
Static method:
static void mul()
{ Body: logics here: static area
}
Static member’s memory allocated during .class file loading hence access the static members
by using class-name.
Classname.staticmethod( );
Test.mul( );
Note: Always access the instance methods using object-name & static methods using class-name.
Example -1 :
68 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
class Test
{ void sayHello()
{ System.out.println("Good Morning");
}
static void add(int num1,int num2) //local variables
{ System.out.println(num1+num2);
}
void mul(int val1,int val2)
{ System.out.println(val1*val2);
}
void login(String username,String password)
{ if (username.equals("ratan"))
{ System.out.println("Login Success");
}
else
{ System.out.println("Login Fail");
}
}
static void display(int a,boolean b,char ch)
{ System.out.println(a+" "+b+" "+ch);
}
public static void main(String[] args)
{ Test t = new Test();
t.sayHello();
Test.add(4,5);
int x=10,y=20;
t.mul(x,y);
t.login("ratan","durga");
Test.display(10,false,'a');
}
}
✓ If the method is taking parameters (inputs to functionality), while calling that method must pass
the values to parameters.
✓ If the method expecting three arguments must pass three arguments, not less than three not
more than three.
✓ Method arguments are always local variables.
✓ While calling the method we can pass constants as a argument values Test.add(10,20)
Or we can pass variables as a argument values Test.add(x,y)
Example -2:
69 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Case 1: java methods return type is mandatory, otherwise the compilation will generate error.
class Test
{ add()
{
}
}
error: invalid method declaration; return type required
Case 2:
Method Signature: Method-name & parameters list is called method signature.
Syntax: Method-name(parameter-list)
m1(int a)
m2(int a,int b)
Inside the class it is not possible to declare more than one method with same signature(duplicate
methods) , if we are trying to declare with same signature compiler generates error.
class Test
{ void m1()
{ System.out.println("m1 method");
}
void m1()
{ System.out.println("m1 method");
}
}
error: m1() is already defined in Test
Case 3:
✓ Declaring the class inside another class is called nested classes, java supports nested classes.
✓ Declaring the methods inside other methods is called inner methods but java not supporting
inner methods concept.
class Test
{ void m1()
{ void m2() //inner method : error: illegal start of expression
{
}
}
}
ex -4 :
70 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
If the application continas both instnace & local variables with same name, in this case to
represent instance variables we have two approaches.
1. Access by using object.
2. Access by uisng this keyword
System.out.println(this.a+this.b); //approach-2
}
public static void main(String[] args)
{ Test t = new Test();
t.add(10,20);
}
}
Case 2: Invalid : inside the static area this keyword not allowed
Int a=100,b=200;
static void add(int a,int b)
{ System.out.println(this.a+this.b);
}
error:non-static variable this cannot be referenced from a static context.
Case 3: In almost all cases to represent instance variables we are using this keyword but inside the
static area this keyword is not allowed hence use object creation approach.
int a=100,b=200;
static void add(int a,int b)
{ Test t = new Test();
System.out.println(t.a+t.b);
}
71 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
class Test
{ void m1(byte a) { System.out.println("Byte value-->"+a); }
void m2(short b ) { System.out.println("short value-->"+b); }
void m3(int c) { System.out.println("int value-->"+c); }
void m4(long d) { System.out.println("long value is-->"+d); }
void m5(float e) { System.out.println("float value is-->"+e); }
void m6(double f) { System.out.println("double value is-->"+f); }
void m7(char g) { System.out.println("character value is-->"+g); }
void m8(boolean h) { System.out.println("Boolean value is-->"+h); }
public static void main(String[] args)
{ Test t=new Test();
t.m1((byte)10);
t.m2((short)20);
t.m3(30);
t.m4(40);
t.m5(10.6f);
t.m6(20.5);
t.m7('a');
t.m8(true);
}
}
ex-6 : java method calling: one method is able to call more than one method
class Test
{ void m1()
{ m2(100);
System.out.println("m1....");
m2(20);
}
void m2(int a)
{ System.out.println("m2...."+a);
}
public static void main(String[] args)
{ Test t=new Test();
t.m1();
}
}
ex- 7 : methods vs. return type.
72 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
✓ Java methods return type is mandatory & void represents no return value. And methods can
have any return type like primitive type such as byte,short,int,long,float &Arrays type , Class type
, Interface type ,Enum type….etc
✓ If the method is having return type other than void then must return the value by using return
keyword otherwise compiler will generate error message “missing return statement”.
✓ Inside the method it is possible to declare only one return statement, that statement must be last
statement of the method otherwise compiler will generate error message.
✓ Method is able to returns the value, it is recommended to hold the return value check the status
of the method but it is optional.
class Test
{ int add(int a,int b)
{ int c;
c = a+b;
return c;
}
static String login(String uname,String upwd)
{ if (uname.equals("ratan"))
{ return "success";
}
else
{ return "fail";
}
}
boolean print(int num)
{ if (num==10)
return true;
else
return false;
}
public static void main(String[] args)
{ Test t = new Test();
int addition = t.add(10,20);
System.out.println("Return value="+addition);
boolean b = t.print(10);
System.out.println("Return value="+b);
}
}
Ex-8 : method vs. return variables
73 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Case 1: if the application contains both instance & local variables the return value will be local.
class Test
{ int a=10;
int m1(int a)
{ return a;
}
public static void main(String[] args)
{ Test t = new Test();
int x = t.m1(100);
System.out.println("return value="+x);
}
}
D:\>java Test
100
Case 2: No local variables in application the return value will be instance value.
class Test
{ int a=10;
int m1()
{ return a;
}
public static void main(String[] args)
{ Test t = new Test();
int x = t.m1();
System.out.println("return value="+x);
}
}
Case 3: If the application contains both local & instance variables with same name then first
priority goes to local variables but to return instance value use this keyword.
class Test
{ int a=10;
int m1(int a)
{ return this.a;
}
public static void main(String[] args)
{ Test t = new Test();
int x = t.m1(100);
System.out.println("return value="+x);
}
}
ex 9: Observations
Case 1: It is possible to print return value of the method in two ways,
1. Hold the return value & print that value.
2. Directly print the value by calling method using System.out.println()
74 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
class Test
{ int m1()
{ System.out.println("m1 method");
return 10;
}
public static void main(String[] args)
{ Test t =new Test();
int x = t.m1();
System.out.println("return value="+x); //Approach-1
Case 2: If the method is having return type is void but if we are trying to call method by using
System.out.println() then compiler will generate error message.
Static void m2()
{ System.out.println("m2 method");
}
System.out.println(Test.m2());
error:'void' type not allowed here
ex-10:
✓ To take the input from end user use scanner class.
✓ Scanner class present in java.util package and it is introduced in 1.5 versions.
✓ To create an object of Scanner class, we usually pass the predefined object System.in, which
represents the standard input stream.
75 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
import java.util.Scanner;
class Test
{ public static void main(String[] args)
{ Scanner s=new Scanner(System.in);
System.out.println("*****emp details*****");
System.out.println("emp no----->"+eno);
System.out.println("emp name---->"+ename);
System.out.println("emp sal------>"+esal);
System.out.println("emp hobbies------>"+ehobbies);
System.out.println("emp Gender------>"+gender);
s.close();
}
}
ex-11:
import java.util.Scanner;
class Test
{ public static void main(String[] args)
{ int count=0,sum=0;
Scanner s = new Scanner(System.in);
76 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
ex-12:
import java.util.Scanner;
class Test
{ public static void main(String[] args)
{ String s = "hi, This is Ratanit.";
ex 13:
import java.util.*;
public class Test
{ public static void main(String args[])
{ String input = "7 tea 12 coffee";
Scanner s = new Scanner(input).useDelimiter("\\s");
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.nextInt());
System.out.println(s.next());
s.close();
}
}
ex-14 : Conversion of local variables to instace variables to improve the scope of the variable.
class Test
{ //instance variables
int val1;
int val2;
void values(int val1,int val2) //local variables
{ System.out.println(val1);
77 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
System.out.println(val2);
//conversion of local to instance (passing local values to instance)
this.val1=val1;
this.val2=val2;
}
void add()
{ System.out.println(val1+val2);
}
void mul()
{ System.out.println(val1*val2);
}
public static void main(String[] args)
{ Test t = new Test();
t.values(10,20);
t.add();
t.mul();
}
}
if the instance variable names and local variable names are different we can assign directly
without using this keyword.
//instance variables
int a;
int b;
void values(int val1,int val2)//local variables
{ System.out.println(val1);
System.out.println(val2);
//conversion of local to instance (passing local values to instance)
a=val1;
b=val2;
}
Case 1: Inside the method taking local value then converting local to instance
import java.util.*;
class Test
{ int sid;
void details()
{ Scanner s = new Scanner(System.in);
78 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
79 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
RecursiveMethod.withrecursive(1);
}
}
class RecursiveMethod
{ static void recursive(int a)
{System.out.println("number is :- "+a);
if (a==0)
return;
recursive(++a);
}
public static void main(String[] args)
80 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
{ RecursiveMethod.recursive(10);
}
}
ex 17 : Stack Memory
✓ The JVM will create empty stack memory just before calling main method &
JVM will destroyed empty stack memory after completion of main method.
✓ When JVM calls particular method that method entry and local variables stored in stack memory
When the method completed, that particular method, local variables destroyed from stack memory
That released memory used by some other methods.
class Test
{ void add(int a,int b)
{ System.out.println(a+b);
}
void mul(int a,int b)
{ System.out.println(a*b);
}
public static void main(String[] args)
{ Test t = new Test();
t.add(5,8);
t.mul(10,20);
}
}
81 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
ex 18: when we call methods recursively then JVM will generate StackOverFlowError.
class Test
{ void m1()
{ m2();
}
void m2()
{ m1();
}
public static void main(String[] args)
{ Test t=new Test();
t.m1();
}
}
**************Methods Completed***************
CONSTRUCTORS
82 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
new keyword:
✓ New keyword is used to create object in java.
✓ When we create object by using new operator after new keyword that part is constructor then
constructor execution will be done.
83 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Default Constructor:
✓ Inside the class if we are not declaring any constructor then compiler generates zero argument
constructors with empty implementation at the time of compilation is called default constructor.
✓ The compiler generated constructor is called default constructor.
✓ Inside the class default constructor is invisible mode.
✓ To check the default constructor provided by compiler open the .class file code by using java de-
compiler software.
84 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
class Test
{ void m1()
{ System.out.println("m1 method");
}
/* default constructor generated by compiler
Test()
{ empty implementation
}
*/
public static void main(String[] args)
{ Test t = new Test();
t.m1();
}
}
User defined constructor:
class Test
{ void m1()
{ System.out.println(“m1 method”);
}
Test()
{ System.out.println("0-arg constructor");
}
Test(int i)
{ System.out.println("1-arg constructor");
}
public static void main(String[] args)
{ Test t1=new Test();
Test t2=new Test(10);
t1.m1();
t2.m1();
}
}
Note 1:
Methods are used to write logics of the application these are executed when we call methods.
Constructor is a special method to write the logics, these logics are automatically
executed during object creation process.
Note 2:
Only the compiler generated 0-argument is called default constructor.
The user defined 0-argument constructor is not a default constructor.
Note 3:
Inside the class if we are not declaring any constructor (either 0-arg or parameterized) then only
compiler generate 0-arg constructor with empty implementation is called default constructor.
85 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Inside the class if we are declaring at least one constructor (either 0-arg or parameterized) then
compiler not generating default constructor.
case-1 : Call the methods by using method name but call the contructor using this keyword.
class Test
{ Test()
{ this(100);
System.out.println("0-arg constructor logics");
}
Test(int a)
{ this('g',10);
System.out.println("1-arg constructor logics");
}
Test(char ch,int a)
{ System.out.println("2-arg constructor logics");
}
public static void main(String[] args)
{ Test t = new Test();
}
}
Case -2 : Inside the constructor this keyword must be first statement.
Test()
{ System.out.println("0 arg");
this(10);
}
error : call to this must be first statement in constructor.
86 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Case 3: One method is able to call more than one method at a time but
One constructor is able to call only one construtor at time.
Test()
{ this(10);
this(10,20);
System.out.println("0-arg cons");
}
error: call to this must be first statement in constructor
class Test
{ void m1()
{ System.out.println("m1 method");
}
public static void main(String[] args)
{ //Named object
Test t = new Test();
t.m1();
//Nameless object
new Test().m1();
}
}
87 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Assignment: Check this Assignment after compilation of 3-cases. (This assignment present in next page)
Write the application with named & nameless object Approaches.
class Test
{ Take 1-ins method (Dog d, Puppy p, Animal a) ---> void return type
Take 1-static method () ---> Student object return type
public static void main(String[] args)
{ Call 2-methods by passing arguments & hold the return value & print it
}
}
Case 2: Method arguments: name less object Approach is recommended.
class Emp{
}
class Student{
}
class Test
{ void m1(Emp e,Student s,int a)
{ System.out.println("m1 method");
System.out.println(e+" "+s+" "+a);
}
public static void main(String[] args)
{ //Named object: passing argumetns
Test t1 = new Test();
Emp e = new Emp();
Student s = new Student();
t1.m1(e,s,10);
88 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
}
public static void main(String[] args)
{ Emp e1 = Test.m1();
System.out.println("m1 method return value="+e1);
Emp e2 = Test.m2();
System.out.println("m2 method return value="+e2);
}
}
Student s = Test.m2();
System.out.println("Return value="+s);
}
}
89 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Student s = Test.m2();
System.out.println("Return value="+s);
}
}
90 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Solution: only one time we are creating object at instance level using multiple times.
91 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Advantages of constructors
✓ Constructors are used to write the logics these logics are executed during object creation.
✓ Constructors are used to initialize the values to instance variables during object creation
(Constructor is a special method used to initialize the object).
Case 1: Problem: in below example we are passing duplicate parameter. It is not recommended.
class RectangleEx
{ void area(int l,int b)
{ System.out.println(l*b);
}
void volume(int l,int b,int h)
{ System.out.println(l*b*h);
}
void perimeter(int l,int b)
{ System.out.println(2*(l+b));
}
public static void main(String[] args)
{ RectangleEx r = new RectangleEx();
r.area(3,4);
r.volume(3,4,5);
r.perimeter(3,4);
}
}
Case 2: To overcome above limitation to initialize the values during object creation use constructor.
class RectangleEx
{ int l,b,h;
RectangleEx() //cons executed during object creation to initialize the data
{ l=2;
h=3;
b=4;
}
void area()
{ System.out.println(l*b);
}
void volume() { System.out.println(l*b*h); }
void perimeter() { System.out.println(2*(l+b)); }
public static void main(String[] args)
{ RectangleEx r = new RectangleEx();
r.area();
r.volume();
r.perimeter();
}
}
When we create only one object the above example is good…
92 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Case 3: when we create multiple objects for every object same constructor(0-argument
constructor) executed initialize the same values.
public static void main(String[] args)
{ RectangleEx r1 = new RectangleEx();
r1.area();
r1.volume();
r1.perimeter();
93 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Case 5: Assignment
class Student
{ during object creation initialize the student values : id name marks
void printGrade()
{ marks>70 : A grade
marks<70 : B grade
}
void printDetails()
{ print all student details : id name marks
}
public static void main(String[] args)
{ create the two students object by passing parameters.
call printGradce() method
call print Details() method
}
}
94 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
ex-1: Assigning values of one object to another object without using constructor.
class Emp
{ int eid;
String ename;
Emp(int eid,String ename)
{ this.eid=eid;
this.ename=ename;
}
Emp(){ }
void disp()
{ System.out.println("Emp id="+eid);
System.out.println("Emp name="+ename);
}
public static void main(String[] args)
{ Emp e1 = new Emp(111,"ratan");
Emp e2 = new Emp();
e2.eid=e1.eid;
e2.ename=e1.ename;
e1.disp();
e2.disp();
}
}
Example 2: Assigning values of one object to another object by using constructor.
class Emp
{ int eid;
String ename;
Emp(int eid,String ename)
{ this.eid=eid;
this.ename=ename;
}
Emp(Emp e)
{ eid=e.eid;
ename=e.ename;
}
void disp()
{ System.out.println("Emp id="+eid);
System.out.println("Emp name="+ename);
}
public static void main(String[] args)
{ Emp e1 = new Emp(111,"ratan");
Emp e2 = new Emp(e1);
e1.disp();
e2.disp();
}
}
95 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
3)Return type Return type not allowed It allows all valid return
Even void. Types(void,int,Boolean…etc)
4)Name Method name starts with lower Class name and constructor
Case & every inner word starts name must be matched.
With upper case.
Ex: charAt(),toUpperCase()….
7)how to call To call the methods use method to call the constructor use
Name. this keyword.
8)Able to call how many one method is able to call one constructors able to
Methods or constructors multiple methods at a time. Call only one constructor
at a time.
9)this to call instance method use this To call constructor use this
Keyword but It is not possible to keyword but inside constructor
call static method. use only one this statement.
10)Super used to call super class methods. Used to call super class constructor
96 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Instance Blocks:-
➢ Instance blocks are used to write the logics of projects & these logics are executed during object
creation just before constructor execution.
Syntax:
{ //logics here
}
➢ Instance blocks execution depends on object creation it means if we are creating 10 objects 10 times
instance blocks are executed.
➢ Inside the class it is possible to declare the more than one instance block the execution order is top to
bottom.
Example:
✓ During compilation the compiler will copy instance blocks code in every constructor.
✓ The constructor logics are specific to object but instance block logics are common for all objects.
//Application before compilation (.java)
class Test
{ { System.out.println("instance block:logics-1"); }
{ System.out.println("instance block:logics-2"); }
Test()
{ System.out.println("0-arg cons");
}
Test(int a)
{ System.out.println("1-arg cons ");
}
public static void main(String[] args)
{ new Test();
new Test(10);
}
}
//Application after compilation (.class)
class Test
{ Test()
{ System.out.println("instance block:logics-1");
System.out.println("instance block:logics-2");
System.out.println("0-arg cons ");
}
Test(int a)
{ System.out.println("instance block:logics-1");
System.out.println("instance block:logics-2");
System.out.println("1-arg cons ");
}
public static void main(String[] args)
{ new Test();
new Test(10);
}
}
97 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Example:
✓ Instance block execution depends on object creation but not constructor exaction.
✓ In below example two constructors are executing but only one object is crating hence only one
time instance block is executed.
✓ Inside the constructor when we declare this or super keyword in this instance block is not copied
in constructor.
class Test
{ { System.out.println("instance block logics");
}
Test()
{ this(10);
System.out.println("0-arg constructor ");
}
Test(int a)
{ System.out.println("1-arg constructor ");
}
public static void main(String[] args)
{ new Test();
}
}
Example:-
✓ Instance blocks are used to initialize instance variables during object creation.
✓ In java it is possible to initialize the values in different ways
o By using constructors
o By using instance blocks
o By setter methods
class Emp
{ int eid;
{ eid=111;} //instance block
void disp()
{ System.out.println("emp id="+eid);
}
public static void main(String[] args)
{ new Emp().disp();
}
};
98 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Case 1:- When we declare instance block & instance variable the execution order is top to bottom.
In below example instance block is declared first so instance block is executed first.
class Test
{ { System.out.println("instance block"); } //instance block
int m1()
{ System.out.println("m1() method called by variable");
return 100;
}
public static void main(String[] args)
{ new Test();
}
}
D:\morn11>java Test
instance block
m1() method called by variable
case 2:-When we declare instance block & instance variable the execution order is top to bottom.
In below example instance variable is declared first so instance block is executed first.
class Test
{ int a=m1(); //instance variables
int m1()
{ System.out.println("m1() method called by variable");
return 100;
}
{ System.out.println("instance block"); } //instance block
public static void main(String[] args)
{ new Test();
}
}
D:\morn11>java Test
m1() method called by variable
instance block
99 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Static block:
✓ Static blocks are used to write the logics theselogics are executed during .class file loading time.
✓ In java .class file is loaded only one time hence static blocks are executed only once per class.
static
{ //logics here
}
✓ In class it is possible to write more than one static blocks but the execution order is top to bottom.
Note : Instance blocks execution depends on object creation but static blocks execution depends on
.class file loading.
Ex :
class Test
{ static { System.out.println("static block-1"); }
static { System.out.println("static block-2"); }
public static void main(String[] args)
{
}
}
Example :-
class Test
{ static { System.out.println("static block-1"); }
static { System.out.println("static block-2"); }
{ System.out.println("instance block"); }
Test() { System.out.println("0-arg cons"); }
Test(int a) { System.out.println("1-arg cons"); }
public static void main(String[] args)
{ new Test();
new Test(10);
}
}
Example :-
up to 1.6 versionValid : it is possible to execute static blocks without using main method.
class Test
{ static
{ System.out.println("static block");
}
}
From 1.7 version Invalid : it is not possible to execute static blocks without using main method.
class Test
{ static
{ System.out.println("static block");
}
}
100 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
101 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
102 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Operators in java
Operator is a symbol used to perform the operation; there is different type of operators in java ,
✓ Unary Operator
✓ Arithmetic Operator
✓ Relational Operator
✓ Bitwise Operator
✓ Logical Operator // conditional operator
✓ Ternary Operator // conditional operator
✓ Assignment Operator.
103 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Unary operator:
104 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Arithmetic Operators:
105 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Relational operator:
106 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Bitwise operators:
107 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
System.out.println(31>>1);
System.out.println(31>>2);
}
}
108 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Logical operators:
The bitwise & always checking both conditions then only decide the result.
In logical operator second condition checking completely depends on first condition result.
The logical && operator does not check second condition if the first condition is false. It checks
the second condition if the first condition is true.
The logical || operator does not check the second condition if the first condition true. It will
check the second condition if the first condition false.
Note : The && and || operators perform Conditional-AND and Conditional-OR operations on two
Boolean expressions. These operators exhibit "short-circuiting" behavior, which means that the
second operand is evaluated only if needed.
ex: int a=10,b=20,c=30;
System.out.println(a>b && a<c); //false
System.out.println(a>b & a<c); //false
109 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
ex-1 :
class Test{
public static void main(String args[])
{
int a=16;
int b=5;
int min=(a < b) ? a : b;
System.out.println(min);
}
}
ex 4: class Test
{ public static void main(String[] args)
{ String str = "Australia";
String data = str.contains("A") ? "Str contains 'A'" : "Str doesn't contains 'A'";
System.out.println(data);
}
}
110 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Assignment operator :
111 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Dog is a single class but here we created three objects means three different memories are created.
112 | P a g e
Corejava Material RATANIT [email protected] Mr.Ratan
Inheritance:
1. The process of creating new class by using the properties of existing class is called inheritance.
2. The process of acquiring properties (variables) &methods (behaviors) from one class to another
class is called inheritance.
3. We are achieving inheritance concept by using extends keyword. Also known as is-a relationship.
4. Extends keyword is providing relationship between two classes..
5. The main objective of inheritance is code extensibility whenever we are extending the class
automatically code is reused.
Note: Child support all features of parent class & support extra features.
113 | P a g e
Corejava Material RATANIT Mr. Ratan
E:\>javap java.lang.Object
public class java.lang.Object
{ public final native java/lang/Class<?> getClass();
public native int hashCode();
public boolean equals(java.lang.Object);
protected native java.lang.Object clone() throws ava.lang.CloneNotSupportedException;
public java.lang.String toString();
public final native void notify();
public final native void notifyAll();
public final native void wait(long) throws java.lang.InterruptedException;
public final void wait(long, int) throws java.lang.InterruptedException;
public final void wait() throws java.lang.InterruptedException;
protected void finalize() throws java.lang.Throwable;
}
114 | P a g e
Corejava Material RATANIT Mr. Ratan
Types of inheritance:
115 | P a g e
Corejava Material RATANIT Mr. Ratan
class Animal
{ void eat()
{ System.out.println("eating...");
}
}
class Dog extends Animal
{ void bark()
{ System.out.println("barking...");
}
}
class TestInheritance
{ public static void main(String args[])
{ Dog d=new Dog();
d.bark();
d.eat();
}
}
116 | P a g e
Corejava Material RATANIT Mr. Ratan
ex : Hierarchical inheritance.
class Animal {
void eat() {
System.out.println("eating...");
}
}
class Dog extends Animal {
void bark() {
System.out.println("barking...");
}
}
class Cat extends Animal {
void sleep() {
System.out.println("Sleeping...");
}
}
class TestInheritance {
public static void main(String args[]) {
Cat c = new Cat();
c.eat();
c.sleep();
117 | P a g e
Corejava Material RATANIT Mr. Ratan
Instanceof operator:
✓ It is used check the type of the object at runtime & it returns Boolean value as a return value.
Syntax: reference-variable instanceof class-name
✓ To use the instanceof operator the class name & reference variable must have some relationship
either parent to child or child to parent otherwise compiler will generate error message.
✓ If the relationship is,
o child to parent it returns true
o Parent to child it return false.
o No relation compiler generates error message incompatible types.
ex 1:
class Animal { }
class Dog extends Animal{ }
class Test
{ public static void main(String[] args)
{ Animal a = new Animal();
Dog d = new Dog();
Object o = new Object();
p = c1;
System.out.println(p instanceof Child1); //true
System.out.println(p instanceof Child2); //false
p = c2;
System.out.println(p instanceof Child1); //false
System.out.println(p instanceof Child2); //true
}
}
118 | P a g e
Corejava Material RATANIT Mr. Ratan
Association:
The name of an association specifies the nature of the relationship between objects.
Association can be one-to-one, one-to-many, many-to-one, many-to-many.
Aggregation:
➢ Class A has instance of class B is called aggregation.
➢ Aggregation is an association that represents part of a whole relationship where a part can exist
without a whole. It has a weaker relationship.
➢ Take the relationship between teacher and department. A teacher may belong to multiple
departments hence teacher is a part of multiple departments but if we delete department object
teacher object will not destroy.
Example-1:
File-1 : Address.java
class Address
{ int dno; //instance variables
String state;
String country;
Address(int dno,String state,String country) //local variables
{ //conversion process
this.dno=dno;
this.state= state;
this.country = country;
}
}
119 | P a g e
Corejava Material RATANIT Mr. Ratan
File-2 : Heroin.java
class Heroin
{ String hname;
int hage;
Address addr; //reference of address class [dno,state,country]
Heroin(String hname,int hage,Address addr)
{ //conversion process
this.hname = hname;
this.hage = hage;
this.addr = addr;
}
void display()
{ System.out.println("Heroin name-->"+hname);
System.out.println("Heroin age-->"+hage);
System.out.println("Heroin address-->"+addr.country+" "+addr.state+" "+addr.hno);
}
public static void main(String[] args)
{ Address a1 = new Address("india","banglore",111);
Heroin h1 = new Heroin("anushka",30,a1);
h1.display();
120 | P a g e
Corejava Material RATANIT Mr. Ratan
Example-2:
File -4 : MainTest.java
class MainTest
{ //instance variables
Test1 t1;
Test2 t2;
Test3 t3;
MainTest(Test1 t1 ,Test2 t2,Test3 t3) //local variables
{ //conversion of local-instance
this.t1 = t1;
this.t2 = t2;
this.t3 = t3;
}
void display()
{ System.out.println(“Test1 object values:-”+t1.a+"----- "+t1.b);
System.out.println(“Test2 object values:-”+t2.b1+"----- "+t2.b2);
System.out.println(“Test3 object values:-”+t3.ch1+"----- "+t3.ch2);
}
public static void main(String[] args)
{
Test1 t = new Test1(10,20);
Test2 tt = new Test2(true,true);
Test3 ttt = new Test3('a','b');
MainTest main = new MainTest(t,tt,ttt);
main.display();
121 | P a g e
Corejava Material RATANIT Mr. Ratan
Composition:
➢ Strong aggregation is called composition.
➢ Composition is an association represents a part of a whole relationship where a part cannot exist
without a whole. If a whole is deleted then all parts are deleted. It has a stronger relationship.
➢ For example, if order HAS-A line-items, then an order is a whole and line items are parts. If an
order is deleted then all corresponding line items for that order should be deleted..
➢ Let’s take Example house contains multiple rooms, if we delete house object no meaning of room
object hence the room object cannot exists without house object.
ex:
Marks.java
class Marks
{ int m1,m2,m3;
Marks(int m1,int m2,int m3) //local variables
{ this.m1=m1;
this.m2=m2;
this.m3=m3;
}
}
student.java
class Student
{ Marks mk; //without student class no meaning of marks is called "composition"
String sname;
int sid;
Student(Marks mk,String sname,int sid) //local variables
{ this.mk = mk;
this.sname = sname;
this.sid = sid;
}
void display()
{ System.out.println("student name:-->"+sname);
System.out.println("student id:-->"+sid);
System.out.println("student marks:-->"+mk.m1+"---"+mk.m2+"--"+mk.m3);
}
public static void main(String[] args)
{ Marks m1 = new Marks(10,20,30);
Student s1 = new Student(m1,"ratan",111);
s1.display();
new Student(new Marks(10,20,30),"ratan",111).display();
122 | P a g e
Corejava Material RATANIT Mr. Ratan
Example-2 :
File 1: Parents.java
class Parents
{ Declare fname, mname
Declare the constructor to initialize the values during object creation.
}
File 2: Marks.java
class Marks
{ Decalre m1 m2 m3 of int type
Declare the constructor to initialize the values during object creation.
}
File 3 : Address.java
class Address
{ Declare dno street
Declare the constructor to initialize the values during object creation.
}
File 4 : Student.java
class Student
{ int sid;
String sname;
Parents p;
Marks m;
Address addr;
Declare the main method to create the object of Student class & Access the display() method
}
123 | P a g e
Corejava Material RATANIT Mr. Ratan
Super keyword:
✓ “this” keyword is used to represent current class object, “super” represent super class object.
✓ Inside the static area both this,super keywords are not allowed.
1. Super class variables.
2. Super class methods.
3. Super class constructors.
4. Super class instance blocks.
5. Super class static blocks.
124 | P a g e
Corejava Material RATANIT Mr. Ratan
class Parent
{ Parent()
{ System.out.println("parent 0-arg constructor");
}
}
class Child extends Parent
{ Child()
{ this(10);
System.out.println("Child 0-arg constructor");
}
Child(int a)
{ super();
System.out.println("child 1-arg constructor--->"+a);
}
public static void main(String[] args)
{ new Child();
}
}
125 | P a g e
Corejava Material RATANIT Mr. Ratan
Case 2: Inside the constructor super keyword must be first statement otherwise compiler
generates error message “call to super must be first line in constructor”.
Child(int a)
{ System.out.println("child 1-arg constructor--->"+a);
super();
}
Case 3: Inside the constructor it is possible to use either this keyword or super keyword but,
✓ Two super keywords are not allowed.
✓ Two this keywords are not allowed.
✓ Both super & this keyword also not allowed.
Invalid Invalid Invalid
Child() Child() Child()
{ super(10); { this(10); { this(10);
super(); this(); super();
} } }
Case 4: In below example parent class default constructor is executed that is provided by compiler.
class Parent
{ // default constructor
}
class Child extends Parent
{ Child()
{ super()
System.out.println("Child 0-arg constructor");
}
public static void main(String[] args)
{ new Child();
}
}
Case 5: compiler generate default constructor with super keyword.
class Parent
{ Parent()
{ System.out.println("parent 0-arg cons");
}
}
class Child extends Parent
{ /* below code is generated by compiler : default constructor with super keyword
Child()
{ super();
} */
public static void main(String[] args)
{ new Child();
}
}
126 | P a g e
Corejava Material RATANIT Mr. Ratan
Case 6:
✓ Inside the constructor if we are not declaring this or super keyword then compiler generate super
keyword at first line of the constructor.
✓ The compiler generated super keyword is always 0-arg constructor calling.
class Parent
{ Parent()
{ System.out.println("parent 0-arg cons");
}
}
class Child extends Parent
{ Child()
{ //super(); generated by compiler
System.out.println("Child 0-arg constructor");
}
Child(int a)
{ //super(); generated by compiler
System.out.println("child 1-arg cons");
}
public static void main(String[] args)
{ new Child();
new Child(10);
}
}
Observation -1: what is the output? If you say correct : you are perfect in java
class Parent
{ Parent(int a){ System.out.println("parent 1-arg cons"); }
}
class Child extends Parent
{ Child()
{ System.out.println("Child 0-arg constructor");
}
Child(int a)
{ super(10);
System.out.println("child 1-arg cons");
}
public static void main(String[] args)
{ new Child();
new Child(10);
}
}
127 | P a g e
Corejava Material RATANIT Mr. Ratan
Static blocks are executed only once during class loading: In parent and child relationship first
parent class static blocks are executed then child class static blocks are executed.
class Parent
{ static
{ System.out.println("parent static block");
}
{ System.out.println("parent instance block");
}
}
class Child extends Parent
{ static
{ System.out.println("child static block");
}
{ System.out.println("child instance block");
}
public static void main(String[] args)
{ new Child();
new Child();
}
}
E:\>java Child
parent static block
child static block
parent instance block
child instance block
parent instance block
child instance block
128 | P a g e
Corejava Material RATANIT Mr. Ratan
Polymorphism
Inroduction:
✓ One functionality with different behaviors is called polymorphism.
✓ The ability to appear in more forms is called polymorphism.
✓ Polymorphism is the ability of an object to take on many forms
✓ Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many and
"morphs" means forms. So polymorphism means many forms.
129 | P a g e
Corejava Material RATANIT Mr. Ratan
Note: In above example When we call t.sum(10); In above example during compilation compiler is
checking the method with 1-argument is available or not ,this mapping is done during
compilation is called static binding.
Without overloading must define multiple method names: add2 add3 add4
With method overloading same name we can use with different behaviors.
130 | P a g e
Corejava Material RATANIT Mr. Ratan
Observations:
case 1: valid
void m1(int a){}
void m1(int a,int b){}
case 2: valid
void m1(int a)
void m1(char ch)
case 3: invalid
void m1(int a)
void m1(int b)
case 4: valid
void m1(int a,char ch)
void m1(char ch,int a)
Note :
It is possible to overload any type of methods(static,final,public,private,abstract...).
131 | P a g e
Corejava Material RATANIT Mr. Ratan
c.m1(10);
c.m1(10,20);
c.m1('a');
}
}
ex: Method overloading with type promotion:
byte short
Int long float double
char
Type promotion means implicit type casting it perform from left to right
class Test
{ void m1(int a,long b)
{ System.out.println("int,long arguments method");
}
void m1(float f)
{ System.out.println("float argument");
}
public static void main(String[] args)
{ Test t=new Test();
t.m1(10,20l);
t.m1(10,20);
t.m1((byte)10,(short)20);
t.m1('a','b'); // here the Unicode values are assigned
t.m1(10.5f);
t.m1(10);
t.m1('a');
t.m1((byte)10);
}
}
✓ In java the numeric values are by default int values,
o To represent byte, short perform type casting
o to represent long value use L constant (small or capital L )
✓ In java the decimal values are by default double values but to represent float value use f constant.
Ex: class Test
{ void m1(int a) { System.out.println("int arguments method"); }
void m1(float f) { System.out.println("float argument"); }
public static void main(String[] args)
{ Test t = new Test();
t.m1(10);
t.m1(10.5f);
t.m1('a');
}
}
In above example t.m1('a'); this matches both int & float arguments but the type promotion
done to immediate level.
132 | P a g e
Corejava Material RATANIT Mr. Ratan
b. Constructor overloading
c. Operator overloading implicitly by the JVM(‘+’ addition& concatenation)
Constructor Overloading:
If the class contains more than one constructor with same name but different arguments or
same number of arguments with different data types those constructors are called overloaded
constructors.
class Test
{ //overloaded constructors
Test(int i)
{ System.out.println("int argument constructor");
}
Test(char ch,int i)
{ System.out.println("char,int argument constructor");
}
Test(char ch)
{ System.out.println("char argument constructor");
}
public static void main(String[] args)
{ new Test(10);
new Test('a',100);
new Test('r');
}
}
Operator overloading: One operator with different behaviors is called Operator overloading .
Java is not supporting operator overloading but only one overloaded in java language is ‘+’.
• If both operands are integer then “+” performs addition.
• If at least one operand is String then “+” perform concatenation.
class Test
{ public static void main(String[] args)
{ System.out.println(10+20); //30 [addition]
System.out.println(“ratan”+"anu"); //ratananu [concatenation]
}
}
Type-conversion in java :
The process of converting data one type to another type is called type casting.
133 | P a g e
Corejava Material RATANIT Mr. Ratan
ex:
class Test
{ public static void main(String[] args)
{ //implicit typecasting (up casting)
byte b=120;
int i=b;
System.out.println(b);
char ch='a';
float a=ch; //[automatic conversion of char to float]
System.out.println(a);
//explicit-typecasting (down-casting)
int a1=130;
134 | P a g e
Corejava Material RATANIT Mr. Ratan
byte b1 =(byte)a1;
System.out.println(b1);
}
}
✓ Rewriting the parent method implementation in child according to child specific implementation.
✓ To achieve method overloading one java class sufficient but to achieve method overriding we
required two java classes with parent and child relationship.
✓ In overriding parent class method is called ===> overridden method
Child class method is called ===> overriding method
ex:
class Parent
{ void property()
{ System.out.println("money+land+house+gold.......");
}
void marry() //overridden method
{ System.out.println("black girl");
}
}
class Child extends Parent
{ void marry() //overridden method
{ System.out.println("Red girl");
}
public static void main(String[] args)
{ Child c=new Child();
c.property();
c.marry();
}
}
If we are not overriding marry method then parent class marry executed the output is :
E:\>java Child
money+land+house+gold.......
135 | P a g e
Corejava Material RATANIT Mr. Ratan
black girl
If we are overriding marry method then our class marry method executed output is :
E:\>java Child
money+land+hhouse
white girl/red girl
class Test{
public static void main(String args[]){
SBI s = new SBI();
ICICI I = new ICICI();
AXIS a = new AXIS();
136 | P a g e
Corejava Material RATANIT Mr. Ratan
class Parent
{ void mrg(){System.out.println("very balck girl");} // overridden method
}
class Child extends Parent
{ int mrg(){System.out.println("red girl");} //overriding method
}
error: mrg() in Child cannot override mrg() in Parent
return type int is not compatible with void
137 | P a g e
Corejava Material RATANIT Mr. Ratan
Case 2: valid
class Parent
{ Object mrg(){ return new Animal(); }
}
class Child extends Parent
{ Dog mrg() { return new Dog(); }
}
138 | P a g e
Corejava Material RATANIT Mr. Ratan
Case 3: Valid
class Parent
{ Object mrg(){ return new Animal(); }
}
class Child extends Parent
{ Animal mrg() { return new Dog(); }
}
Case 4 : invalid
class Parent
{ Dog mrg(){ return new Animal(); }
}
class Child extends Parent
{ Animal mrg() { return new Dog(); }
}
Case 1 : Both methods are instance : method Overriding : execution decided by object creation
class Parent
{ void m1(){ System.out.println("parent m1()"); }
}
class Child extends Parent
{ void m1(){ System.out.println("child m1()"); }
}
Case 2: Both methods are static : method hiding : execution decided by class-name
class Parent
139 | P a g e
Corejava Material RATANIT Mr. Ratan
140 | P a g e
Corejava Material RATANIT Mr. Ratan
}
Case3 : decreasing permission Invalid [public-protected]
class Parent
{ public void m1(){System.out.println("m1 method");}
}
class Child extends Parent
{ protected void m1(){System.out.println("m1 method");}
}
Method overriding -9
If the super class method declares an exception, subclass overridden method can declare same
exception, subclass exception or no exception but cannot declare parent exception.
141 | P a g e
Corejava Material RATANIT Mr. Ratan
142 | P a g e
Corejava Material RATANIT Mr. Ratan
143 | P a g e
Corejava Material RATANIT Mr. Ratan
r.disp();
}
}
Note : in "Parent p = new Child()" using parent reference varaible we can access only overriding
methods, But it is not possible to access the direct method of child class. To access the direct methods of
child classe perform type conversion process.
Ex: In java it is possible to override methods in child classes but it is not possible to override
variables in child classes.
class Parent
{ int a=100;
}
class Child extends Parent
{ int a=1000;
public static void main(String[] args)
{ Parent p = new Child();
System.out.println("a vlues is :--->"+p.a);
}
}
Ex:
class Test
{ void m1(Object o)
{ System.out.println("Object method");
}
void m1(Number b)
{ System.out.println("Number method");
}
public static void main(String[] args)
{ Test t = new Test();
t.m1(new Integer(10));
t.m1(new String("ratan"));
t.m1(new Character('a'));
t.m1(null);
}
}
144 | P a g e
Corejava Material RATANIT Mr. Ratan
Modifications on main():
✓ Modifiers order is not important it means it is possible to declare public static or static public .
public static void main(String[] args)
static public void main(String[] args)
✓ from1.5 version onwards instead of String[] args it is possible to take String… args (var-arg)
static public void main(String... ratan)
Strictfp modifier:
a. It is applicable for classes, methods.
b. In java the floating point calculations are varied from operating system to operating system &
processor to processor hence it will generate platform dependent output.
c. To overcome above problem to get platform independent results use strictfp modifier.
d. If a method is declared as strictfp all floating point calculations in that method will follow
IEEE754 standard. So that we will get platform independent results.
e. If a class is declared as stictfp all methods inside the class will follow IEEE754 standard so we will
get platform independent results.
145 | P a g e
Corejava Material RATANIT Mr. Ratan
Native modifier:
a. Native is the modifier applicable only for methods.
b. Native method is used to represent particular method implementations there in non-java code
(other languages like C,CPP) .
c. Native methods are also known as “foreign methods”.
public final int getPriority(); normal method
public static native java.lang.Thread currentThread(); native method
Synchronized modifier:
It is applicable for only methods.
There are two types of methods in java
a. Synchronized methods
b. Non-synchronized methods.
Synchronized methods:
Only one thread is able to access the synchronized methods and these methods are
thread-safe methods but the performance of the application will be reduced.
If the application requirement is thread-safe then use synchronized methods.
Non-Synchronized methods:
More than onethreadis able to access non-synchronized methods but these methods are
not a thread-safe methods but the performance of the application will be increased.
If the application requirement is performance use non synchronized method.
ex-1:
class Test
{ final strictfp synchronized static public void main(String...ratan)
{ System.out.println("hello ratan sir this is main method");
}
}
146 | P a g e
Corejava Material RATANIT Mr. Ratan
}
}
class Child extends Parent
{
}
D:\>java Child
Parent class main
D:\>java Parent
Parent class main
ex-4: It is not possible to override main method because main is a static method.
In java it is not possible to override static methods.
class Test
{ public static void main(String[] ratan)
{ System.out.println(ratan.length);
System.out.println(ratan[0]);
147 | P a g e
Corejava Material RATANIT Mr. Ratan
System.out.println(ratan[1]);
System.out.println(ratan[0]+ratan[1]);
ex-2: To provide the command line arguments with spaces then take that command line
argument with in double quotes.
class Test
{ public static void main(String[] args)
{ System.out.println(args[0]);
System.out.println(args[1]);
}
}
148 | P a g e
Corejava Material RATANIT Mr. Ratan
ex-2: java methods it is possible to declare normal arguments along with variable arguments.
class Test
{ void m1(char ch,int... a)
{ System.out.println(ch);
for (int a1:a)
{ System.out.println(a1);
}
}
public static void main(String[] args)
{ Test t=new Test();
t.m1('a');
t.m1('b',10);
t.m1('c',10,20);
t.m1('d',10,20,30,40);
}
}
ex-3 : Inside the method it is possible to declare only one variable-argument and that must be last
argument otherwise the compiler will generate compilation error.
149 | P a g e
Corejava Material RATANIT Mr. Ratan
}
public static void main(String[] args)
{ Test t=new Test();
t.m1(10);
}
}
E:\>java Test
normal argument=10
ex-5 : variable-argument method vs. overloading
class Test
{ void m1(int... a)
{ for (int a1 : a)
{ System.out.println(a1);
}
}
void m1(String... str)
{ for (String str1 : str)
{ System.out.println(str1);
}
}
public static void main(String[] args)
{ Test t=new Test();
t.m1(10,20,30);
t.m1("ratan","Sravya");
}
}
ex 6 : variable -argument method vs. ambiguity
class Test
{ void m1(int... a) { ------ }
void m1(String... str) {------ }
public static void main(String[] args)
{ Test t=new Test();
t.m1(10,20,30);
t.m1("ratan","Sravya");
t.m1(); // [compilation error ambiguous]
}
}
error: reference to m1 is ambiguous,
both method m1(int...) in Test and method m1(String...) in Test match
Arrays : Here must create the String[] object then pass the data.
150 | P a g e
Corejava Material RATANIT Mr. Ratan
ex:
class Test
{ public static void main(String[] args) {
Test.callMe1(new String[] {"a", "b", "c"});
Test.callMe2("a", "b", "c");
Test.callMe2(new String[] {"a", "b", "c"}); // You can also do this
}
public static void callMe1(String[] args) {
System.out.println(args.getClass() == String[].class);
for (String s : args) {
System.out.println(s);
}
}
public static void callMe2(String... args) {
System.out.println(args.getClass() == String[].class);
for (String s : args) {
System.out.println(s);
}
}
}
Abstract methods:
✓ The abstract method contains only method declaration but not implementation.
✓ Every abstract method must ends with semicolon.
✓ To represent method is abstract use abstract modifier.
abstract void m1 (); ---->method declaration
Based on above representation of methods the classes are divided into two types
1) Normal classes.
2) Abstract classes.
Normal classes: The class which contains only normal methods that class is said to be normal class.
class Test
{ void m1() { body ; }
void m2() { body ;
void m3() { body ; }
};
Abstract class:-
✓ The abstract class may contains abstract methods or may not contains abstract methods but
for the abstract classes object creation not allowed.
✓ To represent particular class is abstract class use abstract modifier.
Case 1: the class contains at least one abstract method is called abstract class.
abstract class Test
{ void m1(){body}
void m2(){body}
abstract void m3();
}
ex-1:-
✓ If the abstract class contains abstract methods write the implementations in child classes.
✓ For the abstract classes object creation not possible :
✓ The abstract is able to hold Child class object.
Abstract-class reference-variable = new child-class();
Test t1 = new Test1(); //abstract class reference variable Child class object
t1.m1();
t1.m2();
t1.m3() ;
t1.m4() ;
}
}
ex-3:
✓ If the abstract class contains abstract methods write the implementation in child classes.
✓ If the child class is unable to provide implementation of all abstract class methods then declare
the child class with abstract modifier, and complete the remaining method implementations in
next created child classes.
✓ It is possible to declare multiple child classes but at final complete the implementation of all
abstract methods.
✓ If we are completing implementations of all methods then only it is possible to create the object
of normal class and possible to access the methods.
Emp e = t.m3();
System.out.println("m3() return value is:-"+e);
}
};
Example-6 :-
abstract class Test
{ abstract void m1(int a);
abstract void m1(char ch);
abstract void m1(int a,int b);
}
class Test1 extends Test
{ //overloaded methods
void m1(int a) {System.out.println("m1 method int arg method");}
void m1(char ch){System.out.println("m1 method char arg method");}
void m1(int a,int b){System.out.println("m1 method int,int arg method");}
public static void main(String[] args)
{ Test1 t = new Test1();
t.m1(10);
t.m1('a');
t.m1(10,20);
}
}
Example-7 : In child classes it is possible to override abstract methods & possible to declare user
defined normal methods also.
abstract class Test
{ abstract void m1();
abstract void m2();
}
abstract class Test1 extends Test
{ void m1(){System.out.println("m1 method");} //overriding abstract method
Example-8: In child class it is possible to override abstract method & possible to declare our own
abstract methods.
abstract class Test
{ abstract void m1();
}
abstract class Test1 extends Test
{ void m1(){System.out.println("m1 method");}// overriding abstract method
abstract void xxx(); // user specific abstract method
}
class Test2 extends Test1
{ void xxx(){System.out.println("xxx method");}
}
Example-9:-
case 1:- [it is possible to override abstract method to normal method]
abstract class Test
{ abstract void m1();
};
class Test1 extends Test
{ void m1(){System.out.println("m1 method");}
};
Example 10:-
abstract class Bank
{ abstract int rateOfInterest();
}
class Sbi extends Bank
{ int rateOfInterest()
{ return 8;
}
}
class Axis extends Bank
{ int rateOfInterest()
{ return 9;
}
}
class Test
{ public static void main(String[] args)
{ Sbi s1 = new Sbi();
Axis s2 = new Axis();
System.out.println(s1.rateOfInterest());
System.out.println(s2.rateOfInterest());
Bank b1,b2;
b1 = new Sbi();
b2 = new Axis();
System.out.println(b1.rateOfInterest());
System.out.println(b2.rateOfInterest());
Bank b;
b = new Sbi();
System.out.println(b.rateOfInterest());
b = new Axis();
System.out.println(b.rateOfInterest());
}
}
Example 12 :-Inside the abstract class it is possible to declare instance blocks & static blocks.
abstract class Test
{ { System.out.println("abstract class instance block"); }
Static {System.out.println("abstract class static block");}
}
class Test1 extends Test
{ {System.out.println("normal class instance block");}
static {System.out.println("normal class static block");}
public static void main(String[] args)
{ new Test1();
}
}
Abstraction definition :-
✓ The process highlighting the set of services and hiding the internal implementation is called
abstraction.
✓ We are achieving abstraction concept by using Abstract classes & Interfaces.
✓ Bank ATM Screens Hiding the internal implementation and highlighting set of services like ,
money transfer, mobile registration,…etc).
✓ Syllabus copy of institute just highlighting the contents of java but implementation there in
classrooms.
Encapsulation:-
✓ The process of binding the data(variables) and code(methods) as a single unit is called
encapsulation.
✓ Group machanisum is called encapsulation.
✓ The process of hiding the implementation details to user is called encapsulation. And we are
achieving this concept by declaring variables as a private modifier because it is possible to access
private members with in the class only.
Data hiding :
✓ The main objective is data hiding is security and it is possible to hide the data by using private
modifier.
✓ If a variable declared as a private it is possible to access those variables only inside the class is called
data hiding.
Example:- java bean class or VO(value object) class or BO(business object) class
If the variables are declared as a private it is possible to access those variables only with in the
class but it possible to set(update) the data by using setter methods and it is possible to get(read) the
data by using getter methods.
The data of the private field can be accessed only by using public setter & getter method
In this way we are hiding implementation to other classes. The setter and getter methods are
userdefined methods.
The setter method return type is always void & getter method return type is always property return type.
File-1 EmpBean.java
Public class EmpBean
{ private int sid;
private int sname;
public void setSid(int sid)
{ this.sid=sid;
}
System.out.println(e.getSid());
System.out.println(e.getSname());
}
}
Oops
➢ java is open-source technology and it is possible to check source code of the java.
➢ The source code location C:\Program Files\Java\jdk1.7.0_75\src (zip file) extract the zip file.
➢ Java contains 14 predefined packages but the default package in java if java.lang. package.
Predefined packages:
Java contains 14 predefined packages but the default package in java if java.lang. package.
The predefined packages contain predefined classes & interface.
ex: java.lang, java.io ,java.util…...etc
package ratan.anu;
class A{
}
class B{
}
Folder structure:
ratan
|--> anu
| --> A.class
| --> B.class
Note: Inside the source file it is possible to declare only one package statement and that statement
must be first statement of the source file, otherwise compiler generate error message.
1) The package name must reflect with organization domain name (reverse of domain name).
Domain name: www.tcs.com
Package name: package com.tcs;
2) Package name must reflect with project name.
Project name : bank
package : package com.tcs.bank;
3) The project name must reflect with project module name.
Domain name: www.tcs.com
Project name: bank
Module name: deposit
package name: package com.tcs.bank.deposit;
m1 package com.tcs.bank.deposit;
m2 package com.tcs.bank.withdraw;
m3 package com.tcs.bank.loans;
m4 package com.tcs.bank.account;
m5 package com.tcs.bank.chat;
Note: In real time the project is divided into number of modules that each and every module is nothing
but a package statement.
Advantages of packages:
1. It improves parallel development of the project.
2. Project maintenance will become easy.
3. It improves readability.
4. It improves reuseing of properties.
Example-1:
{
}
enum Week
{
}
Javac -d . Test.java
javac ---> java compiler
-d ---> creates folder structure
. ---> Current working directory
Test.java ---> source file name
package com.dss;
public class Test
{ public void m1()
{ System.out.println("Test class m1()");
}
}
G:\>javac -d F:\ratan Test.java
The folder structure is stored in local disk F in ratan folder.
ex-3:
error-1 :
Whenever we are using other packages classes then import that package by using import statement.
There are two ways to import the classes,
o Importing all classes.
Import java.lang.*;
o Importing application required classes [it is recommended approach]
Import java.lang.System;
Import java.lang.String;
error-2: Whenever we are using other package classes, that classes must be public classes otherwise
compiler generate error message.
Default modifier:
➢ It is applicable for variables, methods, classes, constructors.
➢ The default modifier in java is default.
➢ It is possible to access default members only within the package but not outside package.
➢ Default access is also known as package level access.
Public modifier:
✓ Public modifier is applicable for variables, methods, classes,constructors.
✓ All packages are able to access public members.
error-3: Whenever we are using other package class member that members also must be public.
Note: if a class declare class as public the corresponding members are not public, if we want
access public class members that members also must be public.
//StatesInfo.java
package com.tcs.states.info;
public class StatesInfo
{ public void ap() { System.out.println("jai andhra"); }
public void ts() { System.out.println("jai telangana"); }
public void others(){ System.out.println("jai others"); }
}
//ReuiredInfo.java
package com.tcs.states.requiredinfo;
import com.tcs.states.info.StatesInfo;
class RequiredInfo
{ public static void main(String[] args)
{ StatesInfo si = new StatesInfo();
si.ap();
si.ts();
si.others();
}
}
E:\pkgsexamples>javac -d . StatesInfo.java
E:\pkgsexamples>javac -d . RequiredInfo.java
E:\pkgsexamples>java com.tcs.states.requiredinfo.RequiredInfo
jai andhra
jai telangana
jai others
ex-4: It is possible to access other package classes in two ways.
1) Application with import statement. (Access the class directly without full-name)
2) Application without import statement. (Access the class by using full-name)
Test.java
package com.dss;
public class Test
{ public void m1()
MainTest.java : Appllication with import statement : (Access the class directly without full-name)
package com.dss.client;
import com.dss.Test;
class MainTest
{ public static void main(String[] args)
{ Test t = new Test();
t.m1();
}
}
MainTest.java : Application without import statement. (Access the class by using full-name)
package com.dss.client;
class MainTest
{ public static void main(String[] args)
{ com.dss.Test t = new com.dss.Test();
t.m1();
}
}
Ex-5 :
A.java :
package app1;
public class A
{ public void m1()
{ System.out.println("app1 m1() method");
}
}
MainTest.java:
package com.dss.client;
class MainTest
{ public static void main(String[] args)
{ app1.A a = new app1.A();
a.m1();
com module-3
|-->dss
|-->client
|-->MainTest.class
Note : If two different modules contains same class name(A) if third module required those two classes
then use the fully qualified name to access those classes . It is not required to import.
ex-6: working with the sub packages.
Test.java:
package com.dss;
public class Test
{ public void m1()
{ System.out.println("Test class m1()");
}
}
A.java:
package com.dss.corejava;
public class A
{ public void m1()
{ System.out.println("A class m1()");
}
}
B.java:
package com.dss.advjava;
public class B
{ public void m1()
{ System.out.println("B class m1");
}
}
MainTest.java:
package com.dss.client;
import com.dss.Test;
import com.dss.corejava.A;
import com.dss.advjava.B;
class MainTest
{ public static void main(String[] args)
{ new A().m1();
new B().m1();
new Test().m1();
}
}
Compilation & execution: Folder Structure:
G:\>javac -d . Test.java com
G:\>javac -d . A.java |-->dss
G:\>javac -d . B.java |-->Test.class
G:\>javac -d . MainTest.java |-->corejava
G:\>java com.dss.client.MainTest | |-->A.class
A class m1() |-->advjava
B class m1 | |-->B.class
Test class m1() |-->client
|-->MainTest.class
Note : when we import the main package with * then it is possible to access only main package
classes but not sub package classes, if we want to access the sub package classes must
import sub packages also.
class Parent
{ private int a=10;
}
pkg-1
class A
{ protected int a=10;
}
class B
{ System.out.println(a); //possible
}
class C extends A
{ System.out.println(a); //possible
}
pkg-2
class D extends A //Direct sub class
{ System.out.println(a); //possible
}
class E
{ System.out.println(a); //not possible
}
class F extends D //indirect sub cals
{ System.out.println(a); //not possible
}
Modifiers Summary-1:
Private default protected public
Same class yes yes yes yes
Same package sub class no yes yes yes
Same package non sub class no yes yes yes
Different package sub class no no yes yes
Different package non sub class no no no yes
Modifiers Summary-2:
classes methods variables constructors
Public yes yes yes yes
Private no yes yes yes
Protected no yes yes yes
Default yes yes yes yes
Info.java
package com.dss;
public class Info
{ public static int a=100;
public static void m1(){System.out.println("m1 method");}
}
Tcs.java : Application with normal import : access the static members by using class-name
package com.tcs;
import com.dss.Info;
class Tcs
{ public static void main(String[] args)
{ System.out.println(Info.a);
Info.m1();
}
}
Tcs.java : Application with static import : Access the static members directly without class-name
package com.tcs;
import static com.dss.Durga.*;
class Tcs
{ public static void main(String[] args)
{ System.out.println(a);
m1();
}
}
ex-10 : There are two types of imports in java
1. normal import
2. static import
Normal Import : By using normal import it is possible to access both instance & static members
but access the static members by using class-name.
Import java.lang.System;
Static import :- By using static import It is possible to access only static members of particular class
directly into application without using class-name.
Import static java.lang.System.*;
Durga.java:
package com.dss;
public class Durga
{ public static int fee=1000;
public void course()
{ System.out.println("core java");
}
}
Tcs.java:
package com.tcs;
import static com.dss.Test.*; // static import
import com.dss.Test; //normal import
class Tcs
{ public static void main(String[] args)
{ System.out.println(fee);
Question : Already normal import is available to access both static and non-static members of a
class then what is the use of the static import.
Answer :
By using normal import we can access both static & instance members but access the static
members by using class-name.
But by using static import we can access the only static members directly into application
without using class-name.
}
}
Application With static import
import static java.lang.System.*;
class Test
{ public static void main(String[] args)
{ out.println("ratan world");
out.println("ratan world");
out.println("ratan world");
}
}
ex-12 : System.out.println
System: System is a class present in java.lang package.
ex-13: In java it is not possible to use predefined package names as a user defined packages. If we are
trying to use predefined package names as a user defined packages at runtime JVM will generate
securityException.
package java.lang;
class Test
{ public static void main(String[] args)
{ System.out.println("Ratan World!");
}
}
D:\DP>javac -d . Test.java
D:\DP>java java.lang.Test
Exception in thread "main" java.lang.SecurityException: Prohibited package name: java.lang
ex-14 :
✓ The source file is allows to declare only one public class but if you want more public classes in
single module use fallowing structure.
✓ In below four files save separately when we compiled all the file single folder structure is
generated in that folder all the four classes are stored.
} public class C
{
B.java: }
package com.dss;
public class B D.java:
{ package com.dss;
} public class D
C.java: {
package com.dss; }
com [in single module all public classes are stored]
|-->dss
|-->A.class
|-->B.class
|-->C.class
|-->D.class
Applicable modifiers on constructors:
1) Public
2) Private
3) Protected
4) Default
Case -1 : Default constructors : we can access only within the package but in below example A is having
default constructor but if we are trying to access in different package whoch is not possible.
A.java:
package com.dss;
public class A
{ A()
{ System.out.println("A class cons");
}
}
B.java:
package com.tcs;
import com.dss.A;
public class B
{ public static void main(String[] args)
{ new A();
}
}
G:\>javac -d . A.java
G:\>javac -d . B.javaB.java:5: error: A() is not public in A; cannot be accessed from outside packag
Case 2 : Public constructor: all packages are able to access the public constructors.
Test.java:
public class A
{ private A()
{ System.out.println("A class cons");
}
}
class B
{ public static void main(String[] args)
{ A a = new A();
}
}
G:\>javac Test.java
A.java:9: error: A() has private access in A
Case 4: the below example generates error message what is the reason?
Test.java
class Parent
{ private Parent() { }
}
class Child extends Parent
{
}
G:\>javac Test.java
Durga.java:6: error: Parent() has private access in Parent
In above example in child class default constructor is generated in that default constructor super()
keyword is generated but Parent class constructor is private hence it will generate compilation error.
Packages
1. What do you mean by package and what it contains?
2. How many pre-defined packages in java?
3. What is the default package in java?
6. What are coding conventions must fallow while declaring user defined
package names?
7. Is it possible to declare multiple package statements in single source file?
8. What is the purpose of import?
9. What is the location of predefined packages in our system?
10. How many types of imports present in java explain it?
Java Interfaces
************
Introduction:
✓ Interfaces are used to declare the functionalities of the project. Interface provides
service details but not its implementation details.
✓ Interfaces also compiler will generate .class files.
✓ Interfaces are by default abstract so object creation is not possible.
✓ The interfaces are extension of abstract classes but not replacement of abstract classes.
✓ Declare the interface by using interface keyword.
// The Client code: The interface is holding the implementation class objects.
class TestClient
{ void info(Bank b)
{ b.roi();
}
public static void main(String[] args)
{ TestClient t = new TestClient();
t.info(new SbiBank());
t.info(new AxisBank());
}
}
Note:
a. One interface contains multiple implementation classes.
So, class to class they can change the implmentation.
b. Interface implementation classes methods must be public, because interface mehods are
by default public. (Overriding rule: Permission level)
c. inside the interface not possible to declare instance variables. Because by default
interface variables are constants (public static final).
d. inside the interfaces constructors not allowed.
e. inside the interface instance, static blocks are not possible.
f. Inside the interface main method is not allowed.
class Test
{ public static void main(String[] args)
{ Operations op = new Dev2();
op.add(10,20);
op.mul(4,5);
}
}
Observation-1: interface methods it is possible to any return type & any number of arguments.
interface Operations
{ String m1(int a,int b);
int m2(char ch,String str)
void m3(int a);
}
Observation-2: possible to overload the abstract methods of interface.
interface it1
{ void add(int a,int b);
void add(int a,int b,int c)
void add(double d1,double d2)
}
ex-3: Realtime Development process.
level 1 - interfaces : contains the declarations
level 2 - abstract classes : contians partial implementations
level 3 - implementation class : contians all implementations
level 4 - client code : Access the data.
interface Bank
{ void deposit();
void withdraw();
void loan();
void account();
}
class TestClient
{ public static void main(String[] rgs)
{ Dev3 d = new Dev3();
d.account();
d.loan();
d.deposit();
d.withdraw();
}
}
{ void m1();
void m2();
}
interface It2
{ void m2();
void m3();
}
interface It3 extends It1,It2
{ void m4();
}
class Test implements It3
{ Must override 4 methods.
}
Case-4 : one class is able to implements more than one interface.
interface It1
{ void m1();
}
interface It2
{ void m2();
}
interface It3
{ void m3();
}
class Test implements It1
{ Must override 1 methods
}
class Test1 implements It1,It2
{ Must override 2 methods
}
class Test2 extends It1,It2,It3
{ Must override 3 methods
}
Case 2: If more than one interface is having same method then just provide the implementation only
once in implementation class.
interface It1
{ void m1();
void m2();
}
interface It2
{ void m2();
void m3();
}
class Test implements It1,It2
{ override 3-methods.
}
possibilities: extends vs. implements
class A extends B ----> valid
class A extends B,C ----> invalid
Case 3: Declaring interface inside the normal class is called nested interface.
class A
{ interface it1
{ void add(int a,int b);
}
}
class Test implements A.it1
{ public void add(int a,int b)
{ System.out.println("Addition...."+(a+b));
}
public static void main(String[] args)
{ new Test().add(10,20);
}
}
Adaptor class: This class contains empty implementations of interface methods
interface It1
{ void m1();
void m2();
;;;;;
void m6();
}
class X implements It1
{ void m1(){}
void m2(){}
;;;;;
void m6(){}
}
Limitation of interface:
✓ If the interface contains 6-methods in implementation class must override 6 methods if you
required or not.
✓ To overcome above problem to override required methods use adaptor class concept.
✓ Adaptor class is a normal java class contains empty implementation of interface methods.
Note: If our class implementing interface must override all methods but whenever our class
extending adaptor class it is possible to override required methods.
ex: Development process: when we write the code remember below points in realtime.
class MyClass implements myinterface
Cloneing process:
✓ The process of creating exactly duplicate object is called cloneing process.
✓ To make the cloning process the class must implements Cloneable interface.
✓ To create the cloning use clone() method & this method present in Object class.
protected native java.lang.Object clone() throws java.lang.CloneNotSupportedException
The clone() method throws CloneNotSupportedException, it is a checked exception so
handle the exception using try-catch or throws keyword.
initially your class does not support cloneing process. So, your class must implement Cloneable.
java.lang.Cloneable ----> provides cloning capabilities
java.io.Serializable ----> provides Serialization capabilities
java.util.RandomAccess ----> data accessing capabilities
Marker interface:
✓ The marker interface does not contain any methods but whenever our class implements
that interface our class acquire some capabilities to perform some operations, such type
of interfaces are called markerinterfaces.
✓ Marker interface is empty interface but class is acquiring capabilities these capabilities
are provided by JVM.
Shallow cloneing:
Test t1 = new Test();
Test t2 = t1;
Note: In shallow cloneing t1,t2 references are pointing to same memory.
interface new version features.
In Java SE 7 or earlier versions, an interface can have only two things i.e.
Constant variables
Abstract methods.
Note: inside the interface once we declare default & static methods with implementation so
that, all implementation classes can use that implemention.
Note:
Inside the interface once we declare the private methods these implemention can not be
accessed by outside of the interface.
inside the interface once we declare default & static methods. Inside those methods we call the
interface private methods.
These private methods will improve code re-usability inside interfaces and will provide choice to
expose only our intended methods implementations to users.
Ex-1:
interface Temp {
void mul(int a, int b); // abstract method
ex-2:
interface Party
{ void eat();
default void comman_eat()
{ System.out.println("Ice creams, fruit salads.....");
}
}
class TestClient
{ public static void main(String[] args)
{ Veg v = new Veg();
v.eat();
v.comman_eat();
ex-3: Inside the interface possible to declare the main method from java8
interface It1
{ public static void main(String[] args)
{ System.out.println("interface main method");
}
}
E:\>java It1
ex-4:
interface It1
{ default void m1()
{ System.out.println("It1 m1() method");
}
}
interface It2
{ default void m1()
{ System.out.println("It2 m1() method");
}
}
class Test implements It1,It2
{ public void m1()
{ System.out.println("comman method impl....");
}
public static void main(String[] args)
{ Test t = new Test();
t.m1();
}
}
✓ When the class implements multiple interfaces, If the multiple iterfaces contains same
default methods then we will get incompatible error.
✓ To overcome above problem, override the default in the implementation class, then at
runtime override method will be executed.
case 1: valid
interface It1
{ void m1();
}
case 2: Invalid
interface It1
{ void m1();
void m2();
}
case 3: valid
interface It1
{ void m1();
static void m2(){}
}
case 4: valid
interface It1
{ void m1();
static void m2(){}
default void m3(){}
}
case 5: valid
interface It1
{ void m1();
✓ In C language we are allocating memory by using malloc() function and we are destroying
memory by using free() , here the developer is responsible for both operations .
✓ In CPP language we are allocating memory by using constructors and we are destroying memory
by using destructors, here the developer is responsible for both operations.
✓ In java programmer is responsible to allocate the memory by creating of object and memory will
be destroyed by Garbage collector it is a part of the JVM.
❖ As long as an object is being referenced, the JVM considers the object alive.
❖ UN-referenced (Object without reference) is called garbage.
❖ To destroy the objects the garbage collector will fallow mark-and-sweep algorithm.
In project level after using object make eligible that object to garbage collector then garbage
collector will destroy the objects.
Object creation is faster because global synchronization with the operating system is not needed
for every single object. An allocation simply claims some portion of a memory array and moves the offset
pointer forward. The next allocation starts at this offset and claims the next portion of the array.
When an object is no longer used, the garbage collector reclaims the underlying memory and
reuses it for future object allocation. This means there is no explicit deletion and no memory is given back
to the operating system.
Advantages:
1. It makes the java memory efficient because garbage collector removes useless objects.
2. It is automatically called by JVM no need to write extra code.
3. Garbage collector eliminating memory leaks and other memory-related problems
There are four ways to make eligible your objects to garbage collector:
Approach 1 Whenever we are creating objects inside the methods one method is completed the
objects are eligible for garbage collector.
class Test
{ void m1()
{ Test t = new Test();
}
}
In above case once the method is completed reference will destroy. Then object is no
reference is called garbage.
Approach-2 Assigning null constants to our objects then objects are eligible for GC.
class Test
{ public static void main(String[] args)
{ Test t1=new Test();
System.out.println(t1);
t1=null;
System.out.println(t1);
}
}
Approach-3 : Whenever we reassign the reference variable the objects are automatically eligible to GC.
class Test
{ public static void main(String[] args)
{ StringBuffer s1 = new StringBuffer("hello");
StringBuffer s2 = new StringBuffer("ratan");
s1 = s2;
System.out.println(s1);
System.out.println(s2);
}
}
In above case s1 object is pointing to s2
So the “hello” object is eligible for garbage collector.
G:\>java Test
ratan
ratan
Approach-4 : Nameless object once the line is completed that object is eligible to gc() .
class Test
{ public void finalize()
{ System.out.println("object destroyed....");
}
public static void main(String[] args)
{ new Test();
System.gc();
}
}
Example :-
➢ To call the garbage collector explicitly use gc() method it is a static method system class.
➢ Just before destroying object garbage collector will call finalize() method.
➢ Finalize() method present in object class & it is called by garbage collector just before destroying
object.
➢ If we are overriding finalize() then our class finalize() executed , if we are not overriding finalize()
method then object class finalize() method executed having empty implementation.
class Test
{ public void finalize()
{System.out.println("object destroyed");
}
public static void main(String[] args)
{ Test t1 = new Test();
Test t2 = new Test();
System.out.println(t1.toString());
System.out.println(t2.toString());
;;;;;;;;//using object
t1=null;
t2=null;
System.gc();
}
};
Observation :
✓ When JVM calls finalize method ,if any exceptions raised in finalize() method those exceptions are
ignored & objects will be destroyed.
✓ When programmer calls finalize method , if any exception raised in finalize() method that exception
raised program terminated abnormally.
public void finalize()
{System.out.println("object destroyed");
System.out.println(10/0);
}
Example :
✓ Just before destroying object that class fi1nalize method will be executed.
o Emp obj destroyed ---- Emp class finalize method executed
o Student obj destroyed ---- Student class finalize method executed
o String obj destroyed ----String finalize method executed (having empty implementation)
class Emp
{ public void finalize()
{ System.out.println("Emp obj destroyed");
}
}
class Test
{ public void finalize()
{ System.out.println("Test obj destoryed");
}
public static void main(String[] args)
{ Test t = new Test();
t=null;
java.lang.Runtime :-
✓ This class is used to interact with java runtime environment.
✓ The java Runtime class is provide the facility,to execute a process,to call GC,to check free
memory & total memory……etc
r.gc();
}
};
Example :-
class Test
{ public static void main(String[] args) throws Exception
{ Runtime r = Runtime.getRuntime();
System.out.println("Total memory....."+r.totalMemory());
System.out.println("Free memory....."+r.freeMemory());
for(int i=0;i<100000;i++)
{ new Test();
}
System.out.println("Free memory after 10000 objects....."+r.freeMemory());
r.gc();
System.out.println("Free memory after GC called....."+r.freeMemory());
}
}
Example :-opening notepad& shutdown the system & restart the system by using Runtime class.
class Test
{ public static void main(String[] args) throws Exception
{ Runtime.getRuntime().exec("notepad");
Runtime.getRuntime().exec("shutdown -s -t 0");
Runtime.getRuntime().exec("shutdown -r -t 0");
}
}
Example : in below example one object(e2) is eligible to GC.
class Emp{ }
class Test
{ public void finalize()
{ System.out.println("object destroyed");
}
Emp m1()
{ Emp e1 = new Emp();
Emp e2 = new Emp();
System.out.println(e1);
return e1;
}
public static void main(String[] args)
{ Emp e = new Test().m1();
System.out.println(e);
Runtime.getRuntime().gc();
}
}
class Test
{ static Emp m1()
{ Emp e1 = new Emp();
Emp e2 = new Emp();
return e1;
}
public static void main(String[] args)
{ Test.m1();
}
}
Garbage Collector
20. When we destroy the Student class object which class finalize method executed.
String manipulations
Java.lang.String
Java.lang.StringBuffer
Java.lang.StringBuilder
Java.util.StringTokenizer
Java.lang.String:
String is used to represent group of characters or character array enclosed within the double quotes.
class Test
{ public static void main(String[] args)
{ String str="ratan";
System.out.println(str);
char[] ch={'r','a','t','a','n'};
String str3=new String(ch);
System.out.println(str3);
char[] ch1={'a','r','a','t','a','n','a'};
byte[] b={65,66,67,68,69,70};
String str5=new String(b);
System.out.println(str5);
byte[] b1={65,66,67,68,69,70};
String str6=new String(b1,3,3);
System.out.println(str6);
}
}
E:\>java Test
ratan
ratan
ratan
at
ABCDEF
DEF
class Test
{ public static void main(String[] args)
{ //Two approaches to create a String object
String str1 = "ratan";
String str2 = new String("anu");
System.out.println(str1+str2);
== Operator:
By using == operator we can compare primitive data & reference data returns Boolean value.
✓ If the primitive data is same returns true otherwise false.
int a=10,b=10;
System.out.println(a==b);
✓ If two reference variables are pointing to same object then it returns true otherwise false.
class Test{
public static void main(String[] args){
Object obj1 = new Object();
Object obj2 = new Object();
System.out.println(obj1==obj2); //false
obj1=obj2;
System.out.println(obj1==obj2); //true
}
}
ex:
class Test
{ public static void main(String[] args)
{ Test t1 = new Test();
Test t2 = new Test();
System.out.println(t1==t2);
String str1="ratan";
String str2="ratan";
System.out.println(str1==str2);
✓ String is child class of object and it is overriding equals( ) methods used for content comparison.
o If two objects content is same then returns true otherwise false.
✓ StringBuffer class is child class of object and it is not overriding equals() method hence it is using
parent class(Object) equals() method used for reference comparison.
o If two reference variables are pointing to same object returns true otherwise false.
class Object
{ public boolean equals(java.lang.Object) { // reference comparison; }
}
class String extends Object
{ //String class is overriding equals() method
public boolean equals(java.lang.Object); { //content comparison; }
}
class StringBuffer extends Object
{ //not overriding equals() hence it uses object class equals() perform reference comparison
}
ex : class Test
{ Test(String str)
{
}
public static void main(String[] args)
{ //Object class equals() method executed (reference comparison)
Test t1 = new Test("ratan");
Test t2 = new Test("ratan");
System.out.println(t1.equals(t2));
//StringBuffer class not overriding equals() method so object class equals executed
StringBuffer sb1 = new StringBuffer("anu");
StringBuffer sb2 = new StringBuffer("anu");
System.out.println(sb1.equals(sb2));
}
}
✓ == Operator :
Used to check reference comparison & primitive data comparison, returns Boolean value.
• If the primitive data same returns true otherwise false.
• If two reference variables are pointing to same object returns true otherwise false.
✓ equals() method :
Used to compare only object data but not primitive data, returns Boolean value.
• Result of equals() method depends on overridden implementation.
• equals() method present in object class it perform reference comparison.
• String class overriding equals() method perform content comparison.
• StringBuffer class not overriding equals() method it uses parent class(Object) equals
method perform reference comparison.
class Test
{ public static void main(String[] args)
{ String str1 = "hello";
String str2 = "hello";
String str3= new String("hello");
//identity checking
System.out.println(str1==str2);
System.out.println(str1==str3);
System.out.println(str2==str3);
//equality checking
System.out.println(str1.equals(str2));
System.out.println(str1.equals(str3));
System.out.println(str2.equals(str3));
}
}
✓ String is immutable class it means once we are creating String objects it is not possible to perform
modifications on existing object. (String object is fixed object)
✓ StringBuffer is a mutability class it means once we are creating StringBuffer objects on that existing
object it is possible to perform modification.
class Test
{ public static void main(String[] args)
{ String str="ratan";
str.concat("soft");
System.out.println(str); //ratan
concat ( ) : This method is used combining two String objects and it is returning new String object.
public java.lang.String concat(java.lang.String);
class Test
{ public static void main(String[] args)
{ String str="ratan";
String str1 = str.concat("soft");
System.out.println(str1);
}
}
Observation:
class Test
{ public static void main(String[] args)
{ String str="ratan";
str = str.concat("soft");
System.out.println(str); // ratansoft
}
}
✓ In above example after concatenation we are assigning the data to same existing reference variable.
✓ In above example we are not performing modifications on existing objects, here the modification on
performed in newly created object.
Note: possible to call the toString () method only on Object type but not primitive type.
class Object
{ public java.lang.String toString()
{ return getClass().getName() + '@' + Integer.toHexString(hashCode());
}
}
class String extends Object
{ //overriding toString() method
public java.lang.String toString()
{ return "content of String";
}
}
class StringBuffer extends Object
{ //overriding toString() method
public java.lang.String toString()
{ return "content of StringBuffer object";
}
}
class Test
{ public static void main(String[] args)
{ Test t = new Test();
System.out.println(t);
System.out.println(t.toString());
String str="ratan";
System.out.println(str);
System.out.println(str.toString());
class Test
{ public static void main(String... ratan)
{ //conversion of String to StringBuffer
String str1="ratan";
StringBuffer sb = new StringBuffer(str1);
System.out.println(sb);
System.out.println(sb.reverse());
}
}
Observation 2 :
class Test
{ public static void main(String... ratan)
{
String[] str={"119d","madhapur","hyderabad"};
StringBuffer sb = new StringBuffer();
for (String s:str)
{ sb.append(s+",");
}
String s = sb.toString();
System.out.println(s);
}
}
CompareTo ( ) vs equals ( ):
✓ equals() method is used to compare two String object it returns Boolean value as a return value.
✓ If two Strings are equals it return true otherwise false.
public boolean equals(java.lang.Object);
✓ compareTo() method used to compare two String objects return int value as a return value.
✓ compareTo() we are comparing two strings character by character, such type of checking is
called lexicographically checking or dictionary checking. It returns integer value.
o if the two strings are equal then it return zero.
o If the first string first character Unicode value is bigger than second string first character
Unicode value then it return +ve value.
o If the first string first character Unicode value is smaller than second string first
character Unicode value then it return -ve value.
class Test
{ public static void main(String... ratan)
{ String str1="ratan";
String str2="anu";
String str3="ratan";
System.out.println(str1.equals(str2));
System.out.println(str1.equals(str3));
System.out.println(str2.equals(str3));
System.out.println("ratan".equals("RATAN"));
System.out.println("ratan".equalsIgnoreCase("RATAN"));
System.out.println(str1.compareTo(str2));
System.out.println(str1.compareTo(str3));
System.out.println(str2.compareTo(str1));
System.out.println("ratan".compareTo("RATAN"));
System.out.println("ratan".compareToIgnoreCase("RATAN"));
}
}
Split(String): By using split() method we are dividing string into number of tokens.
public java.lang.String[] split(java.lang.String);
trim(): trim() is used to remove the trail and leading spacesthis method always used for memory saver.
public java.lang.String trim();
endsWith() is used to find out if the string is ending with particular character/string or not.
startsWith() used to find out the particular String starting with particular character/string or not.
public boolean startsWith(java.lang.String);
class Test
{ public static void main(String[] args)
{ //length var & length() metod
int [] a={10,20,30};
System.out.println(a.length);
String sc="ratan";
System.out.println(sc.length());
//cahrAt() method
String ss="ratan";
System.out.println(ss.charAt(1));
//System.out.println(ss.charAt(10));StringIndexOutOfBoundsException
char ch=ss.charAt(2);
System.out.println(ch);
//method chaning
String s1 = " ratan ";
System.out.println(s1.length());
System.out.println(s1.trim().length());
System.out.println(s1.trim().substring(2).length());
System.out.println(s1.trim().substring(2,4).length());
//spliting data
String s2 = "hi sir how are you";
String[] s = s2.split(" ");
for (String ss : s)
{ System.out.println(ss);
}
//chekcing the data & Upper case & lower case data
String str1 = "hi sir how r u";
System.out.println(str1.contains("how"));
System.out.println(str1.contains("ratan"));
System.out.println(“ratan”.toUpperCase());
System.out.println(“RATAN”.toLowerCase());
//replace the data
String str="ratan how r u";
System.out.println(str.replace('a','A'));
System.out.println(str.replace("how","who"));
}
}
sb5.replace(3, 9, "ratan");
System.out.println(sb5);
}
}
StringTokenizer:
✓ StringTokenizer present in java.util package & it is a legacy class.
✓ It used to split the string into number of tokens. The default splitting character is space.
✓ To check tokens are available or not use hasMoreElements() method &to print the token use
nextElement() method.
import java.util.StringTokenizer;
public class Test8{
public static void main(String[] args) {
StringTokenizer st = new StringTokenizer("hi sir class completed");
while(st.hasMoreElements())
****Thank you*****
Wrapper classes
✓ Wrapper classes wrap the primitive data type into object of the class.
✓ Java is an Object oriented programming language so represent everything in the form of the
object, but java supports 8 -primitive data types these all are not part of the object.
✓ To represent 8-primitive data types in the form of object form we required 8 java classes these
classes are called wrapper classes.
✓ All wrapper classes present in the java.lang package and these all classes are immutable classes.
2. To provide the type safety to the collection we are using generics but generics support only
object data but not primitive data.
ArrayList<int> ---- invalid
ArrayList<Integer> ---- Valid
3. Wrapper class objects allow null values while primitive data type doesn’t allow it.
Wrapper object creation by using constructor: Wrapper object creation by using valueOf():
Integer i = new Integer(10); Integer x1 = Integer.valueOf(10);
Integer i1 = new Integer("100"); Integer x2 = Integer.valueOf("10");
Observation-1:
Integer i1 = new Integer("10"); valid : string format “10” converted into integer object format.
Integer i2 = new Integer("ten"); Invalid : String format “ten” is unable to converted into Integer.
✓ In above line, to the integer constructor we are passing “10” value in the form of String it is
automatically converted into Integer format.
✓ In above line, to the integer constructor we are passing “ten” in the form of String but this String is
unable to convert into integer format JVM generate java.lang.NumberFormatException.
Integer a = new Integer("ten"); java.lang.NumberFormatException
Observation-2:
Integer i = new Integer("ten"); java.lang.NumberFormatException
Integer x = Integer.valueOf("one"); java.lang.NumberFormatException
In both object creations we will get same error
int x = Integer.parseInt(str1);
float f = Float.parseFloat(str2);
System.out.println(x+f);
}
}
System.out.println(args[0]);
System.out.println(args[1]);
System.out.println(args[0]+args[1]);
int a = Integer.parseInt(args[0]);
float f = Float.parseFloat(args[1]);
System.out.println(a+f);
}
}
E:\>java Test 2 8 7 4 1
5
2
8
28
10.0
✓ The arguments which are passé from command at runtime are called command line arguments.
The command line argument separator is space.
✓ All the command line arguments are stored in String[ ] in the form of string. Then to convert
String to primitive format use parseXXX() method.
✓ toString() method will be automatically called when we print reference variable in java.
✓ toString() present in Object class it returns String representation of object (class-name@hashcode).
✓ String,StringBuffer,all wrapper classes are overriding toString() it returns content of the objects.
String s="ratan";
System.out.println(s);
System.out.println(s.toString());
Observation 1:
In java it is possible to call toString() method only on reference type but not primitive type.
Integer i1 = Integer.valueOf(100);
System.out.println(i1.toString()); Valid
int a=100;
System.out.println(a.toString()); Invalid : error: int cannot be dereferenced
Observation 2:
When you want to convert String format data use toStirng() method because this method return
type is String data.
Conversion of Integer to String:
Integer i = new Integer(100);
String s = i.toString();
== vs. equals() :
== operator always check the references (objects) return Boolean value
✓ equals() method present in object class perform : reference comparison
✓ String class overriding equals() : content comparison
✓ StringBuffer class no equals() uses object class equals : reference comparison
✓ All wrapper classes overriding equals() method : content comparison
Creation of wrapper object by using constructor approach
class Test
{ public static void main(String[] args)
{ Integer i1 = new Integer(10);
Integer i2 = new Integer(10);
if (i1==i2) System.out.println("same");
else System.out.println("not same");
if (i1.equals(i2)) System.out.println("same");
else System.out.println("not same");
if (x1.equals(x2)) System.out.println("same");
else System.out.println("not same");
}
} Output : not same same not same same
if (i1.equals(i2)) System.out.println("same");
else System.out.println("not same");
Integer x1 = Integer.valueOf(200);
Integer x2 = Integer.valueOf(200);
if (x1==x2) System.out.println("same");
else System.out.println("not same");
if (x1.equals(x2)) System.out.println("same");
else System.out.println("not same");
}
} Output : same same not same same
✓ One java class method returns same class object or different class object is called factory method.
✓ There are three types of factory methods in java.
o Instance factory method. (method is called by using reference variable)
o Static factory method. (Method is called by using class name)
o Pattern factory method. (method is returning different class object).
class Test
{ public static void main(String[] args)
{ //static factory method
Integer i = Integer.valueOf(100);
System.out.println(i);
Runtime r = Runtime.getRuntime();
System.out.println(r);
ex : compareTo() method
public class Test {
public static void main(String[] args) {
Integer intObj1 = new Integer (25);
Integer intObj2 = new Integer ("25");
Integer intObj3= new Integer (35);
//compareTo demo
System.out.println("Comparing using compareTo Obj1 and Obj2: " + intObj1.compareTo(intObj2));
System.out.println("Comparing using compareTo Obj1 and Obj3: " + intObj1.compareTo(intObj3));
System.out.println("Comparing using compareTo Obj1 and Obj3: " + intObj3.compareTo(intObj1));
}
}
E:\>java Test
Comparing using compareTo Obj1 and Obj2: 0
Comparing using compareTo Obj1 and Obj3: -1
Comparing using compareTo Obj1 and Obj3: 1
Exception Handling
Introduction:
✓ Dictionary meaning of the exception is abnormal termination.
✓ Exception is a object occurred at runtime to disturb the normal flow of the execution.
✓ An exception is an event that occurs during execution of the program that disturbs normal flow of
the program instructions.
✓ An unexpected even that disturbs the normal termination of the application is called exception.
To overcome above limitation in order to execute the rest of the application & to get normal
termination of the application must handle the exception.
Exception Handling:
✓ The main objective of exception handling is,
a. To get normal termination of the application
b. To execute the rest of the application code.
✓ Exception handling means just we are providing alternate code to continue the execution of
remaining code &to get normal termination of the application.
Types of Exceptions:
As per the sun micro systems standards The Exceptions are divided into three types
1) Checked Exception
2) Unchecked Exception
3) Error
Unchecked Exception:
✓ The exceptions which are not checked by the compiler are called unchecked Exception.
ArithmeticException,ArrayIndexOutOfBoundsException,NumberFormatException….etc
✓ The classes that extend RuntimeException class are called unchecked exceptions.
class Test
{ public static void main(String[] args)
{ System.out.println(10/0); java.lang.ArithmeticException: / by zero
int[] a={10,20,30};
System.out.println(a[5]); java.lang.ArrayIndexOutOfBoundsException: 5
System.out.println("ratan".charAt(12)); java.lang.StringIndexOutOfBoundsException
}
}
✓ If the application contains un-checked Exception code is compiled but at runtime JVM display
exception message & program terminated abnormally.
✓ To overcome runtime problem must handle the exception either using try-catch blocks or by using
throws keyword.
Checked Exception:
✓ The Exceptions which are checked by the compiler are called Checked Exceptions.
IOException,SQLException,InterruptedException……..etc
✓ The classes that extends Exception class are called checked exceptions.
import java.io.*;
class Test
{ public static void main(String[] args)
{ FileInputStream fis = new FileInputStream("abc.txt"); FileNotFoundException
}
}
✓ If you are trying to compile the above compilation the compiler will show the compilation error.
error: unreported exception FileNotFoundException; must be caught or declared to be thrown
✓ If the application contains checked Exception code is not compiled, the compiler will give the
exception information in the form of compilation error but exception occurred at runtime.
✓ To overcome above problem to compile the application must declare the try-catch blocks or throws
keyword then only code is compiled.
Note: Whether it is a checked Exception or unchecked exception exceptions are raised at runtime but
not compile time.
Note: whether it is a checked Exception or unchecked Exception must handle the Exception by using
try-catch blocks or throws keyword to get normal termination of application & to execute rest
of the application.
1) java.lang.InterruptedException
When we used Thread.sleep(2000);your thread is entered into sleeping mode, then
other threads are able to interrupt, in this case program is terminated abnormally & rest of the
application is not executed.
To overcome above problem compile time compiler is checking that exception &
displaying exception information in the form of compilation error.
Based on compiler generated error message write the try-catch blocks or throws , if
runtime any exception raised the try-catch or throws keyword executed program is terminated
normally.
2) Java.io.FileNotFoundException
If we are trying to read the file from local disk but at runtime if the file is not available
program is terminated abnormally rest of the application is not executed.
To overcome above problem compile time compiler is checking that exception &
displaying exception information in the form of compilation error.
Based on compiler generated error message write the try-catch blocks or throws , if
runtime any exception raised the try-catch or throws keyword executed program is terminated
normally.
3) Java.sql.SQLException
If we are trying to connect to data base but at runtime data base is not available
program is terminated abnormally rest of the application is not executed.
To overcome above problem compile time compiler is checking that exception &
displaying exception information in the form of compilation error.
Based on compiler generated error message write the try-catch blocks or throws , if
runtime any exception raised the try-catch or throws keyword executed program is terminated
normally.
class Test
{ public static void main(String[] args)
{ Test[] t = new Test[100000000]; " java.lang.OutOfMemoryError”
}
}
ex-1 : Whenever exception raised in the try block, the corresponding catch block executed.
try
{ System.out.println("sravya");
System.out.println(10/0);
}
catch(NullPointerException e)
{ System.out.println(10/2);
}
ex 3: If there is no exception in try block the corresponding catch blocks are not checked.
class Test
{ public static void main(String[] args)
{ try
{ System.out.println("sravya");
}
catch(NullPointerException e)
{ System.out.println(10/2);
}
System.out.println("rest of the app");
}
}
E:\sravya>java Test
sravya
rest of the app
class Test
{ public static void main(String[] args)
{ try
{ System.out.println("sravya");
}
System.out.println("rest of the app");
}
}
E:\sravya>javac Test.java
Test.java:4: 'try' without 'catch' or 'finally' or resources
try
{ System.out.println(10/0);
}
System.out.println("anu");
catch(ArithmeticException e)
{ System.out.println(10/2);
}
ex 6:
✓ If the exception raised in other than try block it is always abnormal termination.
✓ In below example exception raised in catch block hence program is terminated abnormally.
try
{ System.out.println(10/0);
}
catch(ArithmeticException e)
{ System.out.println(10/0);
}
ex- 7:
✓ If the exception raised in try block the remaining code of try block is not executed.
✓ Once the control is out of the try block the control never entered into try block once again.
✓ Don’t take normal code inside try block because no guarantee all statements in try-block will be
executed or not.
Category-1
Case 1 : The way of handling the exceptions is varied from exception to the exception hence it is
recommended to write try with multiple catch blocks.
import java.util.*;
class Test
{ public static void main(String[] args)
{ Scanner s=new Scanner(System.in);
System.out.println("enter the division value");
int n=s.nextInt();
try
{ System.out.println(10/n);
System.out.println("ratan".charAt(10));
}
catch (ArithmeticException ae)
{ System.out.println("Ratanit");
}
catch (StringIndexOutOfBoundsException se)
{ System.out.println("durgasoft");
}
System.out.println("rest of the code");
}
}
Output: enter the division value: 5 Output: enter the division value: 0
Write the output Write the output
Case 2 : By using Exception(root class) class catch block it is possible to hold any type of exceptions.
import java.util.*;
class Test
{ public static void main(String[] args)
{ Scanner s=new Scanner(System.in);
System.out.println("enter division value");
int n=s.nextInt();
try{ System.out.println(10/n);
System.out.println("ratan".charAt(10));
}
catch (Exception e)
{ System.out.println("Ratanit="+e);
}
System.out.println("rest of the code");
}
}
232 | P a g e
Corejava material RATANIT Mr. Ratan
import java.util.*;
class Test
{ public static void main(String[] args)
{ Scanner s=new Scanner(System.in);
System.out.println("provide the division val");
int n=s.nextInt();
try
{ System.out.println(10/n);
System.out.println(“ratan”.charAt(20));
}
//catch block order is child to parent
catch (ArithmeticException ae)
{ System.out.println("Exception"+ae);
}
catch (Exception ne)
{ System.out.println("Exception"+ne);
}
System.out.println("rest of the code");
}
}
Output: provide the division value: 5 Output: provide the division value: 0
Write the output Write the output
Case 4 : Invalid : catch block order is parent to child compiler generate error message.
try
{ System.out.println(10/n);
System.out.println(“ratan”.charAt(20));
}
catch (Exception ne)
{ System.out.println("Exception"+ne);
}
catch (ArithmeticException ae)
{ System.out.println("Exception"+ae);
}
G:\>javac Test.java
error: exception ArithmeticException has already been caught
233 | P a g e
Corejava material RATANIT Mr. Ratan
Case 1:-
It is possible to handle more than one exception in single catch by using pipe(|) symbol.(java 7 version)
catch(ArithmeticException | StringIndexOutOfBoundsException a) .
catch(NumberFormatException | NullPointerException | StringIndexOutOfBoundsException a)
import java.util.Scanner;
import java.io.*;
public class Test
{ public static void main(String[] args)
{ Scanner s = new Scanner(System.in);
System.out.println("enter a number");
int n = s.nextInt();
try { System.out.println(10/n);
System.out.println("ratan".charAt(13));
}
catch(ArithmeticException | ClassCastException a)
{ System.out.println("exception info="+a);
}
catch(NumberFormatException|NullPointerException|StringIndexOutOfBoundsException a)
{ System.out.println("exception info="+a);
}
System.out.println("Rest of the application");
}
}
✓ When we declared unchecked exception in catch block by using pipe symbol, those exceptions are
not mandatory to present in try block.
✓ In above example,
o In catch we declared ArithmeticException : this exception raised in try block.(chance)
o In catch we declared ClassCastException : this exception not raised in try block.(no chance)
Case 2 :
import java.io.*;
class Test
{ public static void main(String[] args)
{ try
{ FileInputStream f = new FileInputStream("abc.txt");
}
catch(FileNotFoundException|InterruptedException a)
{ System.out.println("exception info="+a);
}
}
}
error: exception InterruptedException is never thrown in body of corresponding try statement
✓ When we declared checked exception in catch block by using pipe symbol, those exceptions must
present in try block otherwise compiler generates error message.
✓ In catch block two exceptions are declared but try block contains one exception hence compiler
generates error message.
Case 3: valid
234 | P a g e
Corejava material RATANIT Mr. Ratan
import java.io.*;
class Test
{ public static void main(String[] args)
{ try
{ FileInputStream f = new FileInputStream("abc.txt");
Thread.sleep(1000);
}
catch(FileNotFoundException|InterruptedException a)
{ System.out.println("exception info="+a);
}
}
}
✓ When we declared checked exception in catch block by using pipe symbol, those exceptions must
present in try block.
✓ In catch block two exceptions are declared & try block contains those two exceptions it is valid.
Case-4: By using pipe symbol possible it is possible to declare the both checked exceptions & un-checked
exception but checked exceptions must be present in try block.
Case-5:
✓ It is not possible to declare the both parent & child classes by using pipe symbol.
✓ Here the FileNotFoundException is the child class of IOException
Invalid: Valid :
catch(FileNotFoundException | IOException a) catch( IOException a)
{ System.out.println("exception info="+a); { System.out.println("exception info="+a);
} }
235 | P a g e
Corejava material RATANIT Mr. Ratan
When we declare the resource by using try block once the try block is completed resource is released.
Case 1:
✓ When we declare the try with resource, if the resource is throws unchecked exception in this case
catch block is optional.
✓ In below example we declared scanner class as a resource it may raise InputMissmatchException & it
is unchecked exception hence catch block is optional.
import java.util.*;
class Test
{ public static void main(String[] args)
{ try(Scanner s = new Scanner(System.in))
{ System.out.println("enter id");
int a = s.nextInt();
System.out.println("input value="+a);
}
}
}
Case 2:
✓ When we declare the try with resource, if the resource is throws checked exception in this case catch
block is mandatory.
✓ In above example we declared File resource, it throws FileNotFoundException it is a checked
exception hence catch block is mandatory.
import java.io.*;
class Test
{ public static void main(String[] args)
{ try(FileInputStream fis = new FileInputStream("abc.txt"))
{ System.out.println("reading data from text file");
}
catch (FileNotFoundException e)
{ System.out.println("file in not available");
}
}
}
Case 3:
✓ By using try block it is possible to declare more than one resource but every resource is separated
with semicolon.
✓ If the try block contains more than one resource in those resources at least one resource throws
checked exception in such case catch block is mandatory.
try(Scanner s = new Scanner(System.in);FileInputStream fis = new FileInputStream("abc.txt"))
{ //some code here
}
catch (FileNotFoundException e) { //some code here }
Note: the resources are internally calling close() method to close the resources.
public interface java.io.Closeable extends java.lang.AutoCloseable {
public abstract void close() throws java.io.IOException; }
ex 1 : There are three methods to print Exception information
236 | P a g e
Corejava material RATANIT Mr. Ratan
1) toString()
2) getMessage()
3) printStackTrace()
class Test
{ void m3()
{ try{ System.out.println(10/0); }
catch(ArithmeticException ae)
{ System.out.println(ae.toString());
System.out.println(ae.getMessage());
ae.printStackTrace();
}
}
void m2()
{ m3();
}
void m1()
{ m2();
}
public static void main(String[] args)
{ new Test().m1();
}
}
D:\DP>java Test
java.lang.ArithmeticException: / by zero //toString() method output
/ by zero //getMessage() method output
java.lang.ArithmeticException: / by zero //printStackTrace() method
at Test1.m3(Test1.java:8)
at Test1.m2(Test1.java:5)
at Test1.m1(Test1.java:3)
at Test1.main(Test1.java:17)
Note: Internally JVM uses printStackTrace() method to print exception information.
237 | P a g e
Corejava material RATANIT Mr. Ratan
If the exception raised in top of the stack method but if you are not handled it drops down to the
stack previous method, if you are not catch it drop down until end of the stack(up to main method) this
is called exception propagation.
Note: only the unchecked Exceptions are propagated automatically but not checked.
class Test
{ void m3()
{ System.out.println(10/0);
}
void m2()
{ m3();
}
void m1()
{ try{ m2(); }
catch(ArithmeticException ae)
{ System.out.println("Arithmetic Exception propagation.....");
}
}
public static void main(String[] args)
{ new Test().m1();
}
}
✓ In above example the exception raised in m3() method but it is not handled so it is propagated
to m2() method.
✓ Here the m2() method is not handled exception so it is propagated to m1().
✓ In above example m1() is handled exception.
238 | P a g e
Corejava material RATANIT Mr. Ratan
catch () }
{ catch ()
} { try
catch () {
Case-2 { }
try } catch ()
{ {
} }
catch () }
{
} Case-6
try Case-4 try
{ try { try
} { try {
catch () { }
{ } catch ()
} catch () {
{ }
} }
} catch ()
catch () { try
{ {
} }
Case-3 catch ()
try Case-5 {
{ try }
} { }
239 | P a g e
Corejava material RATANIT Mr. Ratan
Finally block:
Finally block code is always executed irrespective of try and catch block code. It is used to write
the resource releasing code like,
240 | P a g e
Corejava material RATANIT Mr. Ratan
case 3: case 4:
try try
{ System.out.println(10/0); { System.out.println(10/0);
} }
catch (NullPointerException ae) catch (ArithmeticException ae)
{ System.out.println("catch"); { System.out.println(10/0);
} }
finally finally
{ System.out.println("finally"); { System.out.println("finally");
} }
Output: Output:
finally finally
Exception in thread "main" Exception in thread "main"
java.lang.ArithmeticException: / by zero java.lang.ArithmeticException: / by zero
at Test.main(Test.java:4) at Test.main(Test.java:7)
Exception in thread "main"
case 5: java.lang.ArithmeticException: / by zero
try
{ System.out.println("try");
} case 6:-it is possible to provide try-finally.
catch(ArithmeticException ae) try
{ System.out.println("catch"); { System.out.println("try");
} }
finally finally
{ System.out.println(10/0); { System.out.println("finally");
} }
System.out.println("rest of the code"); System.out.println("rest of the code");
Output:- Output:-
try try
241 | P a g e
Corejava material RATANIT Mr. Ratan
finally
rest of the code
Case 2: In your program when we used System. Exit (0) the JVM will be shutdown hence the rest
of the code won’t be executed .
class Test
{ public static void main(String[] args)
{ try{ System.out.println("ratan");
System.exit(0);
}
finally
{ System.out.println("finally block");
}
System.out.println("rest of the code");
}
}
D:\>java Test
Ratan
Example :-if the try,catch finally blocks contains exception the default exception handler is able to
display only one exception at a time that most recently raised.
try
{ System.out.println(10/0);
}
catch(Exception e)
{ System.out.println("ratan".charAt(20));
}
finally
{ int[] a={10,20,30};
System.out.println(a[9]);
}
G:\>java Test
242 | P a g e
Corejava material RATANIT Mr. Ratan
Example :
statement 1
statement 2
try Case1: No Exception in the above example.
{ statement 3 1, 2, 3, 4, 5,6,15,16,17,18 Normal Termination
statement 4
try Case 2:- if the exception is raised in statement 2.
{ statement 5 1 , Abnormal Termination
statement 6
} Case 3:-Exception is raised in the statement 3
catch () the corresponding catch block Is
{ statement 7 not matched.
statement 8 1,2,15,16Abnormal termination
}
} Case 4:- Exception is raise in the statement-4
catch () corresponding catch block is
{ statement 9 matched.
statement 10 1,2,3,9,10,11,12,15,16,17,18NT
try
{ statement 11 Case 5:-Exception is raised in the statement 5
statement 12 and corresponding catch block
} is matched.
catch () 1,2,3,4,7,8,15,16,17,18 NT
{ statement 13
statement 14 Case 6:-If the exception is raised in the
} statement 6 and corresponding
} catch block is notmatched but
Finally{ outer catch block is matched.
statement 15 1,2,3,4,5,9,10,11,12,15,16,17,18 NT
statement 16
}
Case 7:- If the exception is raised in the statement 5 and the corresponding catch block is
matched but while executing catch block exception raised in statement-7, the outer
catch block is matched while executing outer catch exception raised in st-11, the inner
catch block is matched but while executing inner catch the exception raised in st-13.
1,2,3,4,9,10,15,16Abnormal termination.
Case 8:- If the exception is raised in the statement 6 and the corresponding catch block is
matched but while executing catch block exception raised in statement-8, the outer
catch block is matched while executing outer catch exception raised in st-12, the inner
catch block is matched but while executing inner catch the exception raised in st-14.
1,2,3,4,5,7,9,10,11,13,15,16Abnormal termination.
243 | P a g e
Corejava material RATANIT Mr. Ratan
Case 9:- If the exception raised in statement 15. 1,2,3,4,5 Abnormal termination.
Case 10:- if the Exception raised in statement 18. 1,2,3,4,5,6,15,16,17 Abnormal termination.
Throws keyword:
There are two approaches two handle the exceptions in java
a. By using try-catch blocks.
b. By using throws keyword.
Example 1:
class Test
{ void studentDetails() throws InterruptedException
{ System.out.println("suneel babu is sleeping");
Thread.sleep(3000);
System.out.println("do not disturb sir......");
}
void hod()throws InterruptedException
{ studentDetails();
}
void principal()
{ try{hod();}
catch(InterruptedException ie)
{ ie.printStackTrace(); }
}
void officeBoy()
{ principal();
}
public static void main(String[] args)
{ Test t = new Test();
t.officeBoy();
}
}
244 | P a g e
Corejava material RATANIT Mr. Ratan
Example 2:-
class Test
{ void studentDetails() throws InterruptedException
{ System.out.println("suneel babu is sleeping");
Thread.sleep(3000);
System.out.println("do not disturb sir......");
}
void hod()throws InterruptedException
{ studentDetails();
}
void principal()throws InterruptedException
{ hod();
}
void officeBoy()throws InterruptedException
{ principal();
}
public static void main(String[] args) throws InterruptedException
{ Test t = new Test();
t.officeBoy();
}
}
✓ In above example method-by-method using throws keyword to delegate responsibilities of
exception handling to caller method.
✓ At final main() method uses throws keyword to delegate the responsibilities of exception
handling to JVM.
Example 3:- One method is able to throws more than one exception.
import java.io.*;
class Test
{ void m2()throws FileNotFoundException,InterruptedException
{ FileInputStream fis = new FileInputStream("abc.txt");
Thread.sleep(2000);
System.out.println("Exceptions are handled");
}
void m1()
{ try{m2();}
catch(FileNotFoundException | InterruptedException f){f.printStackTrace();}
}
public static void main(String[] args)
{ Test t = new Test();
t.m1();
}
}
245 | P a g e
Corejava material RATANIT Mr. Ratan
Example 4:- The root class is able to throws all exceptions (Exception root class)
import java.io.*;
class Test
{ void m2()throws Exception
{ FileInputStream fis = new FileInputStream("abc.txt");
Thread.sleep(2000);
System.out.println("Exceptions are handled");
}
void m1()
{ try{m2(); }
catch(Exception e){ e.printStackTrace(); }
}
public static void main(String[] args)
{ Test t = new Test();
t.m1();
}
}
Example 5:-
import java.io.*;
class Test
{ void m2()throws FileNotFoundException,InterruptedException
{ FileInputStream fis = new FileInputStream("abc.txt");
Thread.sleep(2000);
System.out.println("Exceptions are handled");
}
void m1()throws InterruptedException
{ try{m2();}
catch(FileNotFoundException fn){fn.printStackTrace();}
}
public static void main(String[] args)
{ Test t = new Test();
try{ m1();}
catch(InterruptedException ie){ie.printStackTrace();}
}
}
246 | P a g e
Corejava material RATANIT Mr. Ratan
Throw keyword:-
In the application whenever the exception raised the JVM will create the exception object
& JVM will print predefined exception message.
The above approach is not recommended because ArithmeticException is predefined exception & it
contains some fixed meaning(/ by zero)
Note: - throw keyword is used to handover user created exception object to JVM whether it is predefined
exception class or user defined exception class but it is always recommended throw custom exception.
Example:-
import java.util.*;
class Test
{ static void validate(int age)
{ if (age>18)
{ System.out.println("eligible for mrg");
}
else
{ throw new ArithmeticException("not eligible for marriage");
}
}
public static void main(String[] args)
{ Scanner s=new Scanner(System.in);
System.out.println("please enter your age ");
Int age = s.nextInt();
Test.validate(age);
System.out.println("rest of the code");
}
}
E:\>java Test E:\>java Test
please enter your age please enter your age
45 10
Check the output Check the output
247 | P a g e
Corejava material RATANIT Mr. Ratan
The above example is not recommended because we are creating object of ArithmeticException
but is contains some fixed meaning(/ by zero).
Customization of exception handling : user defined exception:-
There are two types of user defined exceptions
1. User defined checked exception.
a. Default constructor approach.
b. Parameterized constructor approach.
Note: - while declaring user defined exceptions: the naming conventions are every exception suffix must
be the word Exception.
248 | P a g e
Corejava material RATANIT Mr. Ratan
D:\morn11>java com.tcs.project.Test
enter u r age
20
Exception in thread "main" com.tcs.userexceptions.InvalidAgeExcepiton: not eligible try after some time
249 | P a g e
Corejava Material RATANIT Mr. Ratan
ArrayIndexOutOfBoundsException:-
int[] a={10,20,30};
System.out.println(a[4]);//ArrayIndexOutOfBoundsException
NumberFormatException:-
String str1="abc";
int b=Integer.parseInt(str1);
System.out.println(b);//NumberFormatException
NullPointerException:-
String str1=null;
System.out.println(str1.length());//NullPointerException
ArithmeticException:-
int b=10/0;
System.out.println(b);//ArithmeticExceptiom
IllegalArgumentException:-
Thread priority range is 1-10
1--->low priority 10--->high priority
Thread t=new Thread();
t.setPriority(11);//IllegalArgumentException
IllegalThreadStateException:-
Thread t=new Thread();
t.start();
t.start();//IllegalThreadStateException
StringIndexOutOfBoundsException:-
String str="rattaiah";
System.out.println(str.charAt(13));//StringIndexOutOfBoundsException
250 | P a g e
Corejava Material RATANIT Mr. Ratan
NegativeArraySizeException:-
int[] a=new int[-9];
System.out.println(a.length);//NegativeArraySizeException
InputMismatchException:-
Scanner s=new Scanner(System.in);
System.out.println("enter first number");
int a=s.nextInt();
D:\>java Test
enter first number
ratan
Exception in thread "main" java.util.InputMismatchException
ClassCastException:-
String s = new String("ratan");
Object o = (Object)s;
Object oo = new Object();
String str = (String)oo; // java.lang.ClassCastException
java.lang.NoClassDefFoundError vs java.lang.ClassNotFoundException:-
class Test1
{ void m1(){ System.out.println("Test1 class m1()"); }
}
class Test
{ public static void main(String[] args) throws ClassNotFoundException
{ Test1 t = new Test1();
t.m1();
Class.forName("Emp");
}
}
Observation-1:- In Test class we are hard coding Test1 object but in target location Test1.class file is not
available it will generate java.lang.NoClassDefFoundError.
Observation-2:- In java to load .class file dynamically at runtime we are using forName() method but if
runtime the class is not available it generate java.lang.ClassNotFoundException.
OutOfMemoryError:-
class Test
{ public static void main(String[] args)
{ int[] a=new int[100000000]; //OutOfMemoryError
}
}
ExceptionInInitializerError:-
251 | P a g e
Corejava Material RATANIT Mr. Ratan
// NoClassDefFoundError vs ClassNotFoundException :
public class NoClassDefFoundError extends LinkageError
Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as
part of a normal method call or as part of creating a new instance using the new expression) and no
definition of the class could be found.
class Test
{ public static void main(String[] args)
{ new Demo().m1();
}
}
E:\>java Test
Exception in thread "main" java.lang.NoClassDefFoundError: Demo
class Test
{ public static void main(String[] args) throws ClassNotFoundException
{ Class.forName("Ratan");
}
}
253 | P a g e
Corejava Material RATANIT Mr. Ratan
40. What do you mean by default exception handler and what is the
purpose of default exception handler?
41. What is the purpose of throw keyword?
42. If we are writing the code after throw keyword usage then what
happened?
43. What is the difference between throw and throws keyword?
44. How to create user defined checked exceptions?
45. How to create user defined un-checked exceptions?
46. Where we placed clean-up code like resource release, database
closeting inside the try or catch or finally and why ?
47. Write the code of ArithmeticException?
48. Write the code of NullPointerException?
49. Write the code of ArrayIndexOutOfBoundsException &
StringIndexOutOfBoundsException?
50. Write the code of IllegalThreadStateException?
51. When we will get InputMisMatchException?
52. When we will get IllegalArgumantException?
53. When we will get ClassCastException?
54. When we will get OutOfMemoryError?
55. What is the difference between ClassNotFoundException &
NoClassDefFoundError?
56. When we will get compilation error like “unreportedException must be
catch”?
57. When we will get compilation error like “Exception XXXException has
already been caught”?
58. When we will get compilation error like “try without catch or finally”?
59. How many approaches are there to create user defined unchecked
exceptions and un-checked exceptions?
60. How to create object of user defined exceptions?
61. How to handover user created exception objects to JVM?
62. Is it possible to handle different exceptions by using single catch block
yes-->how no→why?
63. What is the purpose of try with resources?
64. Relation with Exception handling & overriding?
65. How to propagated checked & unchecked Exceptions?
254 | P a g e
Corejava Material RATANIT Mr. Ratan
I/O Streams:-
➢ Byte Streams handle I/O of raw binary data.
➢ Character Streams handle I/O of character data, automatically handling translation to and from
the local character set.
➢ Buffered Streams optimize input and output by reducing the number of calls to the native API.
Input stream:- Program uses Input stream to read the data from a source one item at a time.
255 | P a g e
Corejava Material RATANIT Mr. Ratan
Output stream:-Program uses output stream to write the data to a destination one item at a time.
256 | P a g e
Corejava Material RATANIT Mr. Ratan
class Test
{ public static void main(String[] args) throws IOException
{ //creation of File
File f = new File("anu.txt");
System.out.println(f.exists());
f.createNewFile();
System.out.println(f.exists());
//creation of directory
File f1 = new File("durga");
System.out.println(f1.exists());
f1.mkdir();
System.out.println(f1.exists());
Byte streams:-
✓ Program uses byte stream to perform input & output of byte data. All byte stream classes developed
based on InputStream & OutputStream.
✓ In byte channel the data is transferred in the from of bytes.
✓ Generally to transfer the images use byte streams.
✓ Program uses byte stream to perform input and output of 8-bit format.
To demonstrate how the byte stream works file I/O provided two main classes
✓ FileInputStream
o It is used to read the data from source one item at a time.
o To read the data from source use read() method of FileInputStream class.
public int read() throws java.io.IOException;
257 | P a g e
Corejava Material RATANIT Mr. Ratan
read() method returns first character Unicode value in the form of integer value.
✓ FileOutputStream
o It is used to write the data to destination one item at a time.
o To write the data to destination use write() method of FileOutputStream class.
public void write(int unicode) throws java.io.IOException;
write() method is taking Unicode value of the character as a parameter.
Character streams:-
✓ Program uses character stream to perform input & output of character data. All character
stream classes developed based on Reader & Writer classes.
✓ In character channel the data is transferred in the form of characters.
✓ Generally to transfer text file data use character channel.
✓ Here the data is transferred in 16 bit format.
Example :-
import java.io.*;
class Test
{ public static void main(String[] args)throws IOException
{ //Byte channel creation
FileInputStream fis = new FileInputStream("abc.txt");
FileOutputStream fos = new FileOutputStream("xyz.txt");
int c;
258 | P a g e
Corejava Material RATANIT Mr. Ratan
while((c=fis.read())!=-1)
{ System.out.print((char)c);
fos.write(c);
}
System.out.println("read() & write operatoins are completed");
//stream closing operations
fis.close();
fos.close();
}
}
✓ While working with streams we will get two exceptions mainly FileNotFoundException , IOException
& these two exceptions are checked exceptions so must handle these exception by using try-catch
blocks or throws keyword.
✓ The above example is not recommended because when the exception raised in the middle there may
be chance of resources are not released.
✓ To overcome above problem use try-catch-finally blocks to release the resources.
259 | P a g e
Corejava Material RATANIT Mr. Ratan
int c;
while((c=fis.read())!=-1)
{ System.out.println((char)c);
fos.write(c);
}
}
catch(IOException e){ e.printStackTrace(); }
finally{
try{ if(fis!=null)fis.close();
if(fos!=null)fos.close();
}
catch(IOException io){io.printStackTrace();}
}
}
}
Note : In CopyCharacters, the int variable holds a character value in its last 16 bits; in CopyBytes, the int
variable holds a byte value in its last 8 bits.
260 | P a g e
Corejava Material RATANIT Mr. Ratan
Example :
import java.io.*;
class Test
{ public static void main(String[] args)
{ FileReader fr=null;
FileWriter fw=null;
try
{ fr=new FileReader("abc.txt");
fw=new FileWriter("ratan.txt");
int c;
while ((c=fr.read())!=-1)
{ fw.write(c);
}
}
catch (IOException ie){ ie.printStackTrace(); }
finally
{ try{ if(fr!=null) fr.close(); if(fw!=null) fw.close(); }
catch(IOException e) { e.printStackTrace(); }
}
}
}
CharArrayWriter:-It is used to write the data to multiple files & this implements Appendable interface.
import java.io.*;
class Test
{ public static void main(String[] args) throws IOException
{ CharArrayWriter ch = new CharArrayWriter();
FileReader fr = new FileReader("abc.txt");
int a;
while((a=fr.read())!=-1)
{ ch.write(a);
}
FileWriter fw1 = new FileWriter("a.txt");
FileWriter fw2 = new FileWriter("b.txt");
ch.writeTo(fw1);
ch.writeTo(fw2);
261 | P a g e
Corejava Material RATANIT Mr. Ratan
fw1.close();
fw2.close();
fr.close();
System.out.println("operations are completed");
}
}
✓ In previous examples we are using un-buffered I/O (normal stream) .This means each read and
write request is handled directly by the underlying OS.
262 | P a g e
Corejava Material RATANIT Mr. Ratan
✓ By using normal streams it is possible to read the data character by character ,In normal streams
each request directly triggers disk access it is relatively expensive & performance is degraded.
✓ Buffered Streams
BufferedInputStream
BufferedOutputStream
BufferedReader
BufferedWriter
✓ Buffered input stream read the data from buffered memory and it interacting with hard disk only
when buffered memory is empty.
✓ By using buffered streams it is possible to read the data line by line format.
263 | P a g e
Corejava Material RATANIT Mr. Ratan
{ System.out.println(e);
System.out.println("getting Exception");
}
finally
{ try{ if (bis != null) bis.close();
if (bos != null) bos.close();
}
catch(IOException e) {e.printStackTrace();}
}
}
}
Serialization:-The process of converting java object to network supported form or file supported form is
called serialization. or
The process of saving an object to a file is called serialization. (or)
To do the serialization we required fallowing classes
1. FileOutputStream
2. ObjectOutputStream
Deserialization:-
The process of reading the object from file supported form or network supported form to the
java supported form is called deserialization.
We can achieve the deserialization by using fallowing classes.
1. FileInputStream
2. ObjectInputStream
The perform serialization our class must implements Serializable interfaces.
264 | P a g e
Corejava Material RATANIT Mr. Ratan
Serializable is a marker interface it does not contains any methods but whenever our class is
implementing Serializable interface our class is acquiring some capabilities to perform some operations
those capabilities are provided by JVM.
Example :- Emp.java
import java.io.*;
class Emp implements Serializable
{ int eid;
String ename;
Emp(int eid,String ename)
{ this.eid=eid;
this.ename=ename;
}
}
SerializationTest.java:-
Class SerializationTest
{ public static void main(String[] args)throws Exception
{ Emp e = new Emp(111,"ratan");
//serialization [write the object to file]
FileOutputStream fos = new FileOutputStream("xxxx.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(e);
System.out.println("serialization completed");
}
}
DeserializationTest.java:-
Class SerializationTest
{ public static void main(String[] args)throws Exception
{ FileInputStream fis = new FileInputStream("xxxx.txt");//deserialization reading obj
ObjectInputStream ois = new ObjectInputStream(fis);
Emp e1 = (Emp)ois.readObject();//returns Object
System.out.println(e1.eid+"----"+e1.ename);
System.out.println("de serialization completed");
}
}
Example :- It is possible to serialize the multiple objects but in which order we serialize same order
we have to desrialize otherwise JVM will generate ClassCastException.
import java.io.*;
class Employee implements Serializable
{ int eid;
String ename;
Employee(int eid,String ename)
{ this.eid=eid;
this.ename=ename;
}
}
class Dog implements Serializable
{ }
class Cat implements Serializable
265 | P a g e
Corejava Material RATANIT Mr. Ratan
{ }
class Test
{ void serialization() throws Exception
{ Employee e = new Employee(111,"ratan");
Dog d = new Dog();
Cat c = new Cat();
//serialization [write the object to file]
FileOutputStream fos = new FileOutputStream("xxxx.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(e); oos.writeObject(d); oos.writeObject(c);
System.out.println("serialization of multiple objetcs completed");
}
void deserialization() throws Exception
{ //deserialization [read object form text file]
FileInputStream fis = new FileInputStream("xxxx.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Employee e1 = (Employee)ois.readObject();//returns Object
Dog d = (Dog)ois.readObject();
Cat c = (Cat)ois.readObject();
System.out.println(e1.eid+"----"+e1.ename);
System.out.println(d);
System.out.println(c);
System.out.println("deserialization completed");
}
public static void main(String[] args) throws Exception
{ Test t = new Test();
t.serialization();
t.deserialization();
}
}
Case 1: it is not possible to serialize static data members in java.
Class Test implements Serializable
{ static int eid=111;
}
Case 2:
Class Address
{ int dno;
}
Class Emp implements Serializable
{ int eno;
String ename;
Address addr;
}
✓ It is not possible to serializale Emp class because the address class is not serializable.
✓ To perform emp class serialization the corresponding all members are must be serializable.
case 3:
266 | P a g e
Corejava Material RATANIT Mr. Ratan
Rule: In case of array or collection, all the objects of array or collection must be serializable. If any object
is not serialiizable, serialization will be failed.
Transient Modifiers :-
✓ it is the modifier applicable for only variables.
✓ If a variable declared as a transient those variables are not participated in serialization instead of
original values default values will be printed.
✓ To prevent the serialization use transient modifier.
Emp.java
import java.io.*;
class Emp implements Serializable
{ transient int eid;
transient String ename;
Emp(int eid,String ename)
{ this.eid=eid;
this.ename=ename;
}
}
Output : 0----null
File IO
267 | P a g e
Corejava Material RATANIT Mr. Ratan
25. When we will get IOException how many ways are there to handle the exceptions?
26. IOException is checked Exception or unchecked Exception?
Multi Threading
Uni Programming:
✓ The earlier days the computer’s memory is occupied only one program after completion of one
program it is possible to execute another program is called uni programming.
✓ Whenever one program execution is completed then only second program execution will be
started such type of execution is called co operative execution, this execution we are having lot
of disadvantages.
a. Most of the times memory will be wasted.
b. CPU utilization will be reduced because only program allow executing at a time.
c. The program queue is developed on the basis co operative execution
Multiprogramming:
✓ Multiprogramming means executing the more than one program at a time.
✓ All these programs are controlled by the CPU scheduler.
✓ CPU scheduler will allocate a particular time period for each and every program.
✓ The main advantage of multithreading is to provide simultaneous execution of two or more parts
of a application to improve the CPU utilization.
Thread:
✓ Thread is a light weight task or small task of the application.
✓ Threads exist inside a process. Multiple threads can exist in a single process.
✓ Executing more than one thread simultaneously is called multithreading.
268 | P a g e
Corejava Material RATANIT Mr. Ratan
✓ The independent execution technical name is called thread. Thread is nothing but separate path
of sequential execution.
✓ The thread is light weight process because whenever we are creating thread it is not occupying
the separate memory it uses the same memory. Whenever the memory is shared means it is not
consuming more memory.
“Multithreading is a Java feature that allows concurrent execution of two or more parts of a
program for maximum utilization of CPU. Each part of such program is called a thread.”
Multitasking:
269 | P a g e
Corejava Material RATANIT Mr. Ratan
class Test
{ public static void main(String[] args) //main thread starts
{ System.out.println("Hello World!"); //main thread executing
} //main thread ended
}
270 | P a g e
Corejava Material RATANIT Mr. Ratan
Step 2: Override the run() method to write the business logic of the Thread. The run method
present in Thread class with empty implementation.
class MyThread extends Thread
{ public void run()
{ //logics here
}
}
ex-1:
class MyThread extends Thread
{ //logics of user thread
public void run()
{ for (int i=0;i<10;i++)
{ System.out.println("userdefined Thread");
}
}
}
class ThreadDemo
{ public static void main(String[] args)
{ MyThread t=new MyThread();
t.start();
271 | P a g e
Corejava Material RATANIT Mr. Ratan
Thread Scheduler:
✓ If the application contains more than one thread then thread execution decided by thread scheduler.
✓ Thread scheduler is a part of the JVM. It decides thread execution.
✓ Thread scheduler is a mental patient we are unable to predict exact behavior of Thread Scheduler it
is JVM vendor dependent.
✓ Thread Scheduler fallows two algorithms to decide Thread execution.
1) Preemptive algorithm.
2) Time slicing algorithm.
✓ We can’t expect exact behavior of the thread scheduler it is JVM vendor dependent. So we can’t say
expect output of the multithreaded examples we can say the possible outputs.
Preemptive scheduling:
In this highest priority task is executed first after this task enters into waiting state or dead
state then only another higher priority task come to existence.
Time Slicing Scheduling:
A task is executed predefined slice of time and then return pool of ready tasks. The scheduler
determines which task is executed based on the priority and other factors.
272 | P a g e
Corejava Material RATANIT Mr. Ratan
Running state: If thread scheduler allocates CPU for particular thread then thread goes to running
state. The Thread is running state means the run() is executing.
Blocked State: If the running thread got interrupted of goes to sleeping state at that moment it goes
to the blocked state.
Dead State: If the business logic of the project is completed means run() over thread goes dead state.
273 | P a g e
Corejava Material RATANIT Mr. Ratan
✓ In the case of t.start() Thread class start() is executed, it register user defined thread into thread
scheduler then decide thread is created.
✓ But in the case of t.run() method, no new thread will be created , run() is executed like a normal
method call by the main thread.
class ThreadDemo
{ public static void main(String[] args)
{ //anonymous inner class
Thread t1 = new Thread()
{ public void run()
{ System.out.println("user Thread-1");
}
};
t1.start();
274 | P a g e
Corejava Material RATANIT Mr. Ratan
ex 7 :
✓ It is not recommended to override start method, If we are overriding start() method then JVM is
executes override start() method thread is not created.
✓ Thread is created only when thread class start method is executed.
ex 8 : It is possible to overload run() but start() method always calling 0-arg run() method.
275 | P a g e
Corejava Material RATANIT Mr. Ratan
ex-9 : possible to write the logics in different method then just call those methods in run() method.
class MyThread extends Thread
{ public void run()
{ m1();
m2();
m3();
}
void m1(){System.out.println("m1 method");}
void m2(){System.out.println("m2 method");}
void m3(){System.out.println("m3 method");}
}
class ThreadDemo
{ public static void main(String[] args)
{ MyThread t=new MyThread();
t.start();
}
}
ex-10 : Sleep() is overloaded method
sleep() method is a static method used to stop the thread particular amount of time. Once the
time expires, thread goes to ready state.
sleep() method throws InterruptedException & it is a checked exception so must handle the
exception by using try-catch or throws keyword.
276 | P a g e
Corejava Material RATANIT Mr. Ratan
}
public static void main(String[] args)
{ MyThread t = new MyThread();
t.start();
}
}
ex-11 :
✓ Here all threads are performing same tasks.
✓ JVM will create separate stack memory for each and every thread.
✓ The below application contains four thread hence JVM will create four stack memories.
277 | P a g e
Corejava Material RATANIT Mr. Ratan
ex-12 :
✓ Here different threads are performing different tasks.
✓ JVM will create separate stack memory for each and every thread.
✓ The below application contains four thread hence JVM will create four stack memories.
278 | P a g e
Corejava Material RATANIT Mr. Ratan
Only one thread is allows to access synchronized methods, these methods are thread safe
methods but performance will be decreased.
More than one thread is allows to access non synchronized methods, these methods are not a
thread safe methods but performance will be increased.
class A
{ public static synchronized void status(String msg)
{ for (int i=0;i<3;i++)
{ System.out.println("hi="+msg);
try{Thread.sleep(1000);}catch(InterruptedException ie){ie.printStackTrace();}
}
}
}
class MyThread1 extends Thread
{ public void run(){
A.status("ratan"); }
}
class MyThread2 extends Thread
279 | P a g e
Corejava Material RATANIT Mr. Ratan
✓ To set the name use setName() & to get the name use getName(),
Public final String getName()
Public final void setName(String name)
280 | P a g e
Corejava Material RATANIT Mr. Ratan
{
}
class ThreadDemo
{ public static void main(String args[])
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.setName("ratan");
t2.setName("anu");
Thread.currentThread().setName(“durga”);
✓ Thread priority decide when to switch from one running thread to another this process is called
context switching.
✓ Must set the priority before starting the thread.
✓ If the more than one thread is having same priority then thread execution decide by thread
scheduler.
281 | P a g e
Corejava Material RATANIT Mr. Ratan
Case : Priority range 1-10 if we set more than 10 JVM will generate IllegalArgumentException.
MyThread t1 = new MyThread();
t1.setPriority(15); // java.lang.IllegalArgumentException
✓ Yield() method causes to pause current executing Thread for giving the chance for waiting
threads of same priority.
✓ When we called yield() method the thread is not enter into waiting state, it will enter into ready
state.
✓ If there are no waiting threads or all threads are having low priority then the same thread will
continue its execution once again.
282 | P a g e
Corejava Material RATANIT Mr. Ratan
✓ To stop the current executing thread until completion of target thread use join() method.
✓ Join method allows one thread to wait for the completion of another thread.
✓ Join() method throws interrupted exception it is a checked exception hence handle the checked
exception by using try-catch blocks or throws keyword.
join() method throws InterruptedException & it is a checked exception so must handle the
exception by using try-catch or throws.
283 | P a g e
Corejava Material RATANIT Mr. Ratan
}
}
}
class ThreadDemo
{ public static void main(String[] args)
{ MyThread t1=new MyThread();
t1.start();
try{ t1.join(); }
catch (InterruptedException ie) {ie.printStackTrace();}
//logics of main thread
for (int i=0;i<5;i++)
{ System.out.println(“main thread”);
try{ Thread.sleep(2000); }
catch(InterruptedException e){e.printStackTrace();}
}
}
}
ex 18: Java.lang.Thread.Interrupted()
✓ A thread can interrupt another sleeping or waiting thread.
✓ The interrupt() is effected whenever our thread enters into waiting state or sleeping state and if
our thread doesn’t enters into the waiting/sleeping state interrupted call will be wasted.
284 | P a g e
Corejava Material RATANIT Mr. Ratan
To get the Runtime class object use static factory method getRuntime()
Runtime r = Runtime.getRuntime();
To add the shutdown hook to JVM use addShutdownHook(obj) method of Runtime Class.
public void addShutdownHook(java.lang.Thread);
To remove the shutdown hook from JVM use removeShutdownHook(obj) method of Runtime Class.
public boolean removeShutdownHook(java.lang.Thread);
285 | P a g e
Corejava Material RATANIT Mr. Ratan
Factory method: One java class method is able to return same class object or different class object is
called factory method.
✓ Generally all threads are created by user are called user threads if want make the daemon
thread use the fallowing method.
public final void setDaemon(boolean); used to specify the daemon thread.
public final boolean isDaemon(); to check the thread is daemon or not.
286 | P a g e
Corejava Material RATANIT Mr. Ratan
Step 1: Our normal java class will become Thread class when we are implementing Runnable interface.
class MyRunnable implements Runnable
{
}
Step 4: start the thread by using Thread class start method of thread class.
287 | P a g e
Corejava Material RATANIT Mr. Ratan
Example-8:-
class MyThread implements Runnable
{ public void run()
{ System.out.println("Thread is running.......");
}
public static void main(String[] args)
{ MyThread r = new MyThread();
Thread t = new Thread(r);
t.start();
}
}
288 | P a g e
Corejava Material RATANIT Mr. Ratan
Example-5Creating two threads by implementing Runnable interface using anonymous inner classes
class ThreadDemo
{ public static void main(String[] args)
{ //application with anonymous inner classes
Runnable r1 = new Runnable()
{ public void run()
{ System.out.println("user Thread-1");
}
};
Thread t1 = new Thread(r1);
t1.start();
Volatile:-
✓ Volatile modifier is also applicable only for variables.
✓ If the values of a variable keep on changing such type of variables we have to declare with volatile
modifier. If a variable declared as a volatile then for every Thread a separate local copy will be
created. Every intermediate modification performed by that Thread will take place in local copy
instead of master copy.
289 | P a g e
Corejava Material RATANIT Mr. Ratan
✓ Once the value got finalized just before terminating the Thread the master copy value will be
updated with the local stable value. The main advantage of volatile modifier is we can resolve the
data inconsistency problem.
✓ But the main disadvantage is creating and maintaining a separate copy for every Thread
✓ Increases the complexity of the programming and effects performance of the system.
synchronized blocks:-
✓ Synchronized vlock can be used to perform synchronization on any specific resource of the code.
✓ if the application method contains 100 lines but if we want to synchronized only 10 lines of code
use synchronized blocks.
✓ The synchronized block contains less scope compare to method.
Syntax:-
synchronized(object)
{ //code
}
Example 25 :
class Heroin
{ public void message(String msg)
{ synchronized(this){
System.out.println("hi "+msg+" "+Thread.currentThread().getName());
try{Thread.sleep(5000);}
catch(InterruptedException e){e.printStackTrace();}
}
System.out.println("hi Sravyasoft");
}
};
290 | P a g e
Corejava Material RATANIT Mr. Ratan
Wait vs Sleep :-
Example-26 :-
class MyThread extends Thread
{ int total;
public void run()
{ synchronized(this){
for (int i=0;i<10 ;i++)
{ total=total+i;
}
notify();
291 | P a g e
Corejava Material RATANIT Mr. Ratan
}
}
}
class ThreadDemo
{ public static void main(String[] args)
{ MyThread t = new MyThread();
t.start();
synchronized(t)
{ System.out.println("MyThrad total is waiting for MyThread completion...");
try{
t.wait();}
catch(InterruptedException ie){System.out.println(ie);}
}
System.out.println("MyThrad total is ="+t.total);
}
}
292 | P a g e
Corejava Material RATANIT Mr. Ratan
System.out.println(tg1.getName());
tg1.list();
}
}
Example-29 : ThreadGroup interruption
class MyRunnable implements Runnable
{ public void run()
{ System.out.println(Thread.currentThread().getName());
try{Thread.sleep(1000);}catch(InterruptedException ie){ie.printStackTrace();}
}
}
class ThreadDemo
{ public static void main(String[] args)
{ ThreadGroup tg1 = new ThreadGroup("Ratan");
new Thread(tg1,new MyRunnable()).start();
new Thread(tg1,new MyRunnable()).start();
tg1.interrupt();
}
}
293 | P a g e
Corejava Material RATANIT Mr. Ratan
Multithreading
294 | P a g e
Corejava Material RATANIT Mr. Ratan
Nested classes
Declaring the class inside another class is called nested classes it is introduced in the 1.1 version.
295 | P a g e
Corejava Material RATANIT Mr. Ratan
Important points:
class Outer
{ class Inner
{
}
}
Note 1: The compiler will generate .class files for both inner & outer classes.
Outer class .class file name : Outer.class
Inner class .class file name : Outer$Inner.class
Note 2: It is possible to create the objects for both inner & outer classes.
Outer class Object creation : Outer o = new Outer();
Inner class object creation : Outer.Inner I = new Outer().new Inner();
Note 3: By using outer class object it is possible to call only outer class properties.
By using inner class object it is possible to call only inner class properties.
Note 4: The inner class methods are able to access outer class methods but,
Outer class methods are unable to access inner class methods.
✓ It is the way logically grouping classes that are only used in the one place.
If one class required another class only one time then it is logically embedded it into that classes
make the two classes together.
• it increase the encapsulation
• it improves readability
• the inner class is able to access outer class private properties.
296 | P a g e
Corejava Material RATANIT Mr. Ratan
Nesting the classes within the top level classes at that situation placing the code is very closer to
the top level class. It improves maintenance of the project.
✓ Code optimization :
Anonymous inner classes reduce the length of the code.
Without existing one type of object there is no chance of existing another type of object we
should use Inner classes.
One functionality can exists with presence of another functionality use inner cclasses.
ex : University contains several departments but without university no chance of existing departments.
class University //outer class
{ class Department //inner class
{
}
}
ex : Map is a collection of key-value pairs & each key-value pair is entry. So map contains group of
entry’s .The entry can exists with presents of Map only.
interface Map
{ interface Entry
{
}
}
1. Member inner classes / regular inner classes / normal inner classes / instance inner classes:
Declaring the class inside another class is called normal inner classes.
ex- 1:
class Outer
{ private int a=10,b=20;
void m1()
{ System.out.println("outer class m1()");
}
class Inner
297 | P a g e
Corejava Material RATANIT Mr. Ratan
{ int i=100,j=200;
void m2()
{ System.out.println("inner class m2()");
System.out.println(a+b);
System.out.println(i+j);
m1();
}
}
}
class Test
{ public static void main(String... ratan)
{ Outer o = new Outer();
o.m1();
Outer.Inner i = o.new Inner();
i.m2();
}
}
class Outer
{ int a=10,b=20;
class Inner
{ int x=100,y=200;
void add(int i,int j)
{ System.out.println(i+j);
System.out.println(x+y);
System.out.println(a+b);
}
}
public static void main(String[] args)
{ new Outer().new Inner().add(1000,2000);
}
}
o It is possible to declare the main method inside the outer class.
298 | P a g e
Corejava Material RATANIT Mr. Ratan
}
public static void main(String... ratan)
{ new Outer().new Inner().m1(1000,2000);
}
}
ex-4 : inside the inner class not possible to declare static members.
class Outer
{ class Inner
{ public final static int a=10;
}
}
error: Illegal static declaration in inner class Outer.Inner
✓ Inside the inner classes it is not possible to declare static members.
✓ Inside the inner classes it is not possible to declare main method because main is static.
299 | P a g e
Corejava Material RATANIT Mr. Ratan
{
}
}
}
300 | P a g e
Corejava Material RATANIT Mr. Ratan
301 | P a g e
Corejava Material RATANIT Mr. Ratan
App with anonymous inner classes reduce the length of the code : declaration of class out side of main
class TestClient
{ public static void main(String[] args)
{ A a = new A()
{ void m1(){System.out.println("m1 method");}
void m2(){System.out.println("m2 method");}
};
a.m1();
a.m2();
}
}
Example :-
class A //predefined class
{ void m1(){}
}
class TestClient
{ A a = new A()
{ void m1()
{ System.out.println("m1 method");
System.out.println(a.getClass().getName());
302 | P a g e
Corejava Material RATANIT Mr. Ratan
}
};
public static void main(String[] args)
{ TestClient t = new TestClient();
t.a.m1();
}
}
G:\>java TestClient
m1 method
TestClient$1
✓ In above example when we create the object of A class internally A class object is not creating,
the compiler will generate one new class that class object will be created & that class is called
anonymous inner class.
✓ To get the compiler generated class use getClass() method of Object class.
TestClient$1 (.class file code ) open by using java de-compiler software
class TestClient$1 extends A
{ void m1()
{ System.out.println("m1 method");
System.out.println(a.getClass().getName());
}
final TestClient this$0;
TestClient$1()
{ this$0 = TestClient.this;
super();
}
}
The above example different ways :- reducing length of the code
public static void main(String[] args)
{ A a = new A()
{ void m1(){ System.out.println("m1 method");}
};
a.m1();
}
public static void main(String[] args)
{ A a = new A()
{ void m1(){ System.out.println("m1 method");}
}.m1();
}
Example :Abstract classes vs. Anonymous inner class.
abstract class Animal
{ abstract void eat();
};
class Test
{ public static void main(String[] args)
{ Animal a=new Animal()
{ void eat(){ System.out.println("animals eating gross"); }
};
303 | P a g e
Corejava Material RATANIT Mr. Ratan
a.eat();
new Animal()
{ void eat(){ System.out.println("animals eating gross"); }
}.eat();
}
}
new It1()
{ public void m1(){System.out.println("m1 method");}
}.m1();
}
}
Example :
interface It1
{ void m1();
}
class A
{ void firstMethod(It1 i)
{ i.m1();
}
}
304 | P a g e
Corejava Material RATANIT Mr. Ratan
class Test
{ public static void main(String[] args)
{ //approach-1
new A().firstMethod(new X());
//approach-2
new A().firstMethod(new It1(){public void m1()
{System.out.println("implementation with anonymous inner classes");}});
//approcah-3
new A().firstMethod(()->System.out.println("lambda code"));
}
}
class X implements It1
{ public void m1()
{ System.out.println("implementations in separte class");
}
}
Some possibilities:-
Case 1: Case 3:-
class A interface It1
{ class B { interface It2
{ {
} }
} }
Case 2:- Case 4:-
class A interface It1
{ interface It1 { class A
{ {
} }
} }
✓ Final
✓ Default (no modifier)
305 | P a g e
Corejava Material RATANIT Mr. Ratan
Example 1:- private : it is possible to access private members inside the class only.
class Outer
{ private class Inner1
{
}
}
class Test
{ public static void main(String[] args)
{ Outer.Inner1 i = new Outer().new Inner1();
}
}
Compilation Error: Outer.Inner1 has private access in Outer
Nested classes
306 | P a g e
Corejava Material RATANIT Mr. Ratan
307 | P a g e
Corejava Material RATANIT Mr. Ratan
case 2:Valid : Functional interface contains only one abstract method & default, static methods also.
@FunctionalInterface
interface Greetings
{ void morning();
default void even(){}
static void goodnight(){}
}
case 3:Invalid : The functional interface allows only one abstract method but here we are
declared more than one abstract method.
@FunctionalInterface
interface Greetings
{ void morning();
void evening();
}
Lambda expression
Syntax :-
(Argument-list) -> {body}
308 | P a g e
Corejava Material RATANIT Mr. Ratan
Example :-
interface Message
{ void morn();
}
class Test
{ public static void main(String[] args)
{ //application with anonymous inner class
Message m = new Message()
{ public void morn(){System.out.println("good morning Ratan");}
};
m.morn();
309 | P a g e
Corejava Material RATANIT Mr. Ratan
{System.out.println("arg-1 "+str);
System.out.println("arg-2 "+a);
}
};
m.morn("Anu",10);
Example :
interface isTypeOne
{ void hasOne();
}
interface isTypeTwo
{ void hasTwo();
}
class Test
{ void first(isTypeOne o)
310 | P a g e
Corejava Material RATANIT Mr. Ratan
{ o.hasOne();
}
void second(isTypeTwo t)
{ t.hasTwo();
}
public static void main(String[] args)
{ Test t = new Test();
t.first(()->System.out.println("one"));
t.second(()->System.out.println("second"));
}
}
Example :-
interface Executable
{ void execute();
}
class Runner
{ public void run(Executable e)
{ System.out.println("run method code....");
e.execute();
}
};
public class Test
{ public static void main(String[] args)
{ Runner r = new Runner();
//anonymous inner class
r.run(new Executable(){
public void execute()
{ System.out.println("execute method block of java code.....");
}
});
//lambda expression
r.run(() -> System.out.println("execute method block of code....."));
}
};
311 | P a g e
Corejava Material RATANIT Mr. Ratan
Example :-
interface Executable
{ int execute(int a,int b);
}
class Runner
{ public void run(Executable e)
{ int x = e.execute(100,200);
System.out.println("return value="+x);
}
};
public class Test
{ public static void main(String[] args)
{ int c=10;
new Runner().run((int a,int b) -> a+b+c);
}
};
Meta annotations:-
312 | P a g e
Corejava Material RATANIT Mr. Ratan
Annotation @Retention : Retention policy determines at what point the annotation is available
@Retention(RetentionPolicy.SOURCE)
The marked annotation is retained only in the source level and is ignored by the compiler.
@Retention(RetentionPolicy.CLASS)
The marked annotation is retained by the compiler at compile time, but is ignored by (JVM).
@Retention(RetentionPolicy.RUNTIME)
The marked annotation is retained by the JVM so it can be used by the runtime environment
@Inherited –
Marks another annotation to be inherited to subclasses of annotated class (by default
annotations are not inherited to subclasses).
@Repeatable - Specifies that the annotation can be applied more than once to the same declaration.
Uses of annotations:-
❖ Information for the compiler
Annotations are used by the compiler to detect suppress warnings or errors based on rules.
Example :- @Override this one makes the compiler to check the method correctly override or not
@FunctionalInterfacemakes the compiler to validate interface is functional interface or not.
❖ Documentation
Annotations can be used in software applicationsto ensure the quality of the code like bug
finding, report generation…etc
313 | P a g e
Corejava Material RATANIT Mr. Ratan
❖ Code generation
Annotations used to generate the code or xml files using meta data information present in the
code.
❖ Runtime processing
Annotations that are used in runtime objectives like unit testing, dependency injection…etc
1) @Override
✓ It instructs the compiler to check parent class method is overriding in child class or not if it is
not overriding compiler will generate error message.
✓ In below example if are not declaring @override annotation a new method of marry(int a)
created in child class.
Predefined support :-
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
Example :
class Parent
{ void marry()
{}
};
class Child extends Parent
{ @Override
void mary()
{ }
};
E:\>javac Test.java
error: method does not override or implement a method from a supertype
2) @SuppressWarnings –
✓ Instructs the compiler to suppress the compile time warnings specified in the annotation parameters.
Predefined support :
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {
String[] value();
}
314 | P a g e
Corejava Material RATANIT Mr. Ratan
Example-1:-
import java.util.*;
class Student
{ @SuppressWarnings("unchecked")
public static void main(String[] args)
{ ArrayList al = new ArrayList();
al.add("ratan");
al.add("anu");
al.add("sravya");
System.out.println(al);
}
};
3) @Deprecated - Marks the method as obsolete. Causes a compile warning if the method is used.
This annotation represent the marked element is no longer be used. The compiler generates
warning message when we used that marked element.
Example :-
class Test
{ @Deprecated
void m1()
{ System.out.println(“m1 method”);
}
}
class Demo
{ @SuppressWarnings("deprecation")
public static void main(String[] args)
{ new Test().m1();
}
}
Example -2:-
import java.awt.*;
class Student
{ public static void main(String[] args)
{ Frame f = new Frame();
f.show();
}
}
4) @FunctionalInterface - Specifies that the type declaration is intended to be a functional interface,
since Java 8.Annotations applied to other annotations (also known as "Meta Annotations"):
Predefined support :
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface FunctionalInterface { }
315 | P a g e
Corejava Material RATANIT Mr. Ratan
Example :
@FunctionalInterface
interface It1
{ void m1();
}
316 | P a g e
Corejava Material RATANIT Mr. Ratan
317 | P a g e
Corejava Material RATANIT Mr. Ratan
Week[] w = Week.values();
for (Week ww : w)
{ System.out.println(ww+" "+ww.ordinal());
}
}
}
static
{ MON = new Week("MON", 0);
TUE = new Week("TUE", 1);
WED = new Week("WED", 2);
VALUES = (new Week[] {
MON, TUE, WED
});
}
}
case 2: Inside the enum if we are declaring constants along with some other elements like constructor or
method in this case group of constants must be first line must ends with semicolon.
318 | P a g e
Corejava Material RATANIT Mr. Ratan
enum Week
{ MON,TUE,WED;
Week()
{ System.out.println("0-arg cons");
}
}
ex 5: inside the enum possible to declare the constructor,main method instance,static blocks.
enum Week
{ MON,TUE(10),WED(10,20); //public static final
static
{ System.out.println("staic block");
}
{ System.out.println("ins block");
}
Week()
{ System.out.println("0-arg cons");
}
Week(int a)
{ System.out.println("1-arg cons");
}
Week(int a,int b)
{ System.out.println("2-arg cons");
}
public static void main(String[] args)
{ System.out.println("enum main method");
}
}
if the application contains static variables & static blocks then the execution order is top to bottom.
a. first static constants are executed
b. static blocks are execcuted
E:\>java Week
ins block
0-arg cons
ins block
1-arg cons
ins block
2-arg cons
staic block
enum main method
ex 6 : It is possible to take the enum as a switch argument.
enum Day
{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
class Test
{ public static void main(String args[])
{ Day day = Day.SUNDAY;
switch(day)
{ case SUNDAY: System.out.println("sunday");
319 | P a g e
Corejava Material RATANIT Mr. Ratan
break;
case MONDAY: System.out.println("monday");
break;
default: System.out.println("other day");
break;
}
}
}
in above example we are passing enum as switch argument so the case labels must be enums constants.
320 | P a g e
Corejava Material RATANIT Mr. Ratan
********* Thank you : Completed: Thank you: Believes only practical Knowledge************
Arrays
✓ Arrays are used to represent group of elements as a single entity but these elements are
homogeneous &fixed size.
✓ The size of Array is fixed it means once we created Array it is not possible to increase and
decrease the size.
✓ Array in java is index based first element of the array stored at 0 index.
✓ By using arrays possible to store primitive data & object data.
321 | P a g e
Corejava Material RATANIT Mr. Ratan
Advantages of array:-
✓ Code optimization:Instead of declaring individual variables we can declare group of elements by
using array it reduces length of the code.
✓ Flexibility:We can store the group of objects easily & we are able to retrieve the data easily.
✓ RandomAccess : We can access the random elements present in the any location based on index.
0 1 2 3 4 5 6 7 8 index
Length is 9
Possible syntaxes:
int[] values;
int []values;
int values[];
322 | P a g e
Corejava Material RATANIT Mr. Ratan
//2-way
for(int i=0;i<a.length;i++)
{ System.out.println(a[i]);
}
//3-way
for(int aa:a)
{ System.out.println(aa);
}
}
}
Example :
✓ when we create the array the array is created with default values later initialization is performaed.
package com.dss;
public class Test
{ public static void main(String[] args)
{ int[] a = new int[3];
for(int aa:a)
{ System.out.println(aa);
}
323 | P a g e
Corejava Material RATANIT Mr. Ratan
e[1]=e2;
e[2]=e3;
for (Emp ee:e)
{ //System.out.println(ee); in this line toString() executed prints hashcode
System.out.println(ee.eid+”---”+ee.ename)
}
}
}
✓ In above example if the location contains null value but we are trying to call the e2.eidJVM will
generate NullPointerException so to overcome this problems use if-else condition to check the data.
324 | P a g e
Corejava Material RATANIT Mr. Ratan
Test.java
class Test
{ public static void main(String[] args)
{ Object[] a= new Object[6];
a[0]=new Emp(111,"ratan");
a[1]=new Integer(10);
a[2]=new Student(1,"anu");
a[3]=new String(“ratan”);
325 | P a g e
Corejava Material RATANIT Mr. Ratan
326 | P a g e
Corejava Material RATANIT Mr. Ratan
327 | P a g e
Corejava Material RATANIT Mr. Ratan
}
System.out.println("Array Element sum is="+sum);
}
}
Example :-
class Test
{ public static void main(String[] args)
{ int[][] a={{10,20,30},{40,50,60}};
System.out.println(a[0][0]);//10
System.out.println(a[1][0]);//40
System.out.println(a[1][1]);//50
}
} 0 1
10 20 30 10 20 30
0 1 2 0 1 2
Example:-
class Test
{ public static void main(String[] args)
{ String[][] str={{"A.","B.","C."},{"ratan","ratan","ratan"}};
System.out.println(str[0][0]+str[1][0]);
System.out.println(str[0][1]+str[1][1]);
System.out.println(str[0][2]+str[1][2]);
}
}
Collection definition :
✓ The main objective of collections framework is to represent group of object as a single entity.
✓ In java Collection framework provide very good architecture to store and manipulate the group
of objects.
328 | P a g e
Corejava Material RATANIT Mr. Ratan
✓ Collection API contains group of classes and interfaces that makes it easier to handle group of
objects.
2) Arrays are capable to store primitive & 2) Collections are capable to store only
Object type data object data.
3) Arrays are fixed in size, it means once we 3) Collections can grow and shrink in
created array it is not possible to increase & size automatically when objects are
decrease the size based on our requirement. added or removed.
5) With respect to memory arrays are not 5) With respect to memory collections
recommended to use. are recommended to use.
329 | P a g e
CoreJava Material RATANIT Mr. Ratan
12. Java.util.Map
13. Java.util.SotedMap
14. Java.util.NavigableMap
15. Map.Entry
330 | P a g e
CoreJava Material RATANIT Mr. Ratan
The collections framework contains group of classes but every class is used to represent group of
objects as a single entity but characteristics are different.
Collection frame work classes are non-synchronized except java 1.0 version classes(Vector,HashTable)
331 | P a g e
CoreJava Material RATANIT Mr. Ratan
List interface
extends
Stack(c)
1.0 version
332 | P a g e
CoreJava Material RATANIT Mr. Ratan
Legacy classes: The java classes which are introduced in 1.0 version .
1) HashTable
2) Properties
3) Stack
4) Vector
5) Dictionary <abstract class>
6) Enumeration<interface>
Java.util.ArrayList:
To check the predefined support use javap command,
D:\ratan>javap java.util.ArrayList
✓ Usually collection data is transferred from one JVM instance to other JVM instance. To support
this requirement, every collection class must be inherited from java.io.Serializable interface.
Serializable is a marker interface providing serialization capabilities.
✓ Also, collection data can be copied. Hence, every collection class must be inherited from
java.lang.Cloneable interface. Cloneable is a marker interface providing Cloneing capabilities.
ArrayList:
1) ArrayList Introduced in 1.2 version.
2) ArrayList stores Heterogeneous objects(different types).
3) In ArrayList it is possible to insert Null objects.
4) Duplicate objects are allowed.
5) ArrayList preserved Insertion order it means whatever the order we inserted the data in the same
way output will be printed.
6) ArrayList methods are non-synchronized methods.
7) The under laying data structure is Resizable array.
8) By using cursor we are able to retrieve the data from ArrayList : Iterator , ListIterator
333 | P a g e
CoreJava Material RATANIT Mr. Ratan
ex-1:
Case 1 : Up to 1.4 versions we must create wrapper class object then add that object into ArrayList.
import java.util.ArrayList;
class Test
{ public static void main(String[] args)
{ ArrayList al = new ArrayList();
al.add(new Integer(10));
al.add(new Character('c'));
al.add(new Double(10.5));
System.out.println(al);
System.out.println(al.toString());
}
}
Case 2: From 1.5 versions onwards add the primitive data into ArrayList , that data is
automatically converted into wrapper object format is called Auto boxing.
✓ When we add the primitive data into ArrayList it is automatically converted into wrapper object
format is called autoboxing.
✓ Whenever we are printing arraylist reference internally it calls toString() method on every object.
✓ toString() present in object class returns String representation of object(class-name@hashcode).
✓ String,StringBuffer,all wrapper classes toString() method overriding to return content of the object.
334 | P a g e
CoreJava Material RATANIT Mr. Ratan
Emp.java: Student.java
class Emp class Student
{ int eid; { int sid;
String ename; String sname;
Emp(int eid,String ename) Student(int sid,String sname)
{ //conversion of local to instance { //conversion of local to instance
this.eid=eid; this.sid=sid;
this.ename=ename; this.sname = sname;
} }
} }
Test.java
package com.dss;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(10);
al.add("ratan");
al.add(new Emp(111, "ratan"));
al.add(new Student(1, "anu"));
al.add(null);
System.out.println(al.toString());
for(Object o : al)
{ if(o instanceof Emp)
{ Emp ee = (Emp)o;
System.out.println(ee.eid+"--"+ee.ename);
}
if(o instanceof Student)
{ Student ss = (Student)o;
System.out.println(ss.sid+"---"+ss.sname);
}
if(o instanceof String)
{ System.out.println(o);
}
if(o instanceof Integer)
{ System.out.println(o);
}
if(o==null)
{ System.out.println(o);
}
}
}
}
335 | P a g e
CoreJava Material RATANIT Mr. Ratan
ex 3:
✓ Arrays are by default type safe it means the array contains only specific type of data.
Int array ---> stores only int data
String array ---> stores only String data
✓ Collections are not type safe (no guarantee on data) it means the collections can store different
types of objects.
ArrayList al = new ArrayList();
al.add(10);
al.add(“ratan”);
✓ If the collections are not type safe while reading the data at runtime we have to perform,
1. Type checking
2. Type casting
if the collections are not type safe, while reading the data we have to do (typecheckig& type casting).
package com.dss;
import java.util.ArrayList;
public class Test3 {
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(new Emp(111, "ratan"));
al.add(new Student(1, "durga"));
Student s = (Student)al.get(1);
System.out.println(s.sid+" "+s.sname);
Object o = al.get(0);
if(o instanceof Student)
{ Student s1 = (Student)o;
System.out.println(s1.sid+" "+s1.sname);
}
if(o instanceof Emp)
{ Emp e1 = (Emp)o;
System.out.println(e1.eid+" "+e1.ename);
}
}
}
To overcome above two problems to provide the type safety to the collections use generics.
✓ The generics are used to provide the type safety to the collections, it allows only similar type of data,
if we are trying to add different types of object compiler generates error message.
✓ When we provide type safety to the collection the advantages are ,
o No type checking.
o No type casting.
Generic version of ArrayList used to store only homogeneous data.(type safety)
ArrayList<String> al = new Arrraylist<String>();
al.add(“ratan”);
al.add(“anu”);
336 | P a g e
CoreJava Material RATANIT Mr. Ratan
ex-4:
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
//arrays are type safe
int[] a={10,20,30};
for(int aa:a)
{ System.out.println(aa);
}
Observation : if the generic version contains null values we have to print the data using below code.
ArrayList<Student> a2 = new ArrayList<Student>();
a2.add(new Student(1,"ratan"));
a2.add(new Student(2,"anu"));
a2.add(null);
for (Student s : a2)
{ if(s==null) System.out.println(s);
else System.out.println(s.sid+"---"+s.sname);
}
Note : Arrays are used to store the homogeneous data & collection generic version used to store
homogeneous data but collections provides more flexibility with respect to the memory &
operations.
337 | P a g e
CoreJava Material RATANIT Mr. Ratan
package com.dss;
import java.util.ArrayList;
public class Test5 {
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(10);
al.add(10.5);
al.add("durga");
al.add("ratan");
al.add(10);
al.add(null);
System.out.println(al);
System.out.println(al.size()); //finding size of the ArrayList
observation: when we remove the data by passing numeric value it is by default treated as index value.
ArrayList al = new ArrayList();
al.add(10);
al.remove(10); // java.lang.IndexOutOfBoundsException:
338 | P a g e
CoreJava Material RATANIT Mr. Ratan
ArrayList constructors :
Ex-6 There are two ways to add one collection data into another collection.
i. By using constructor approach.
ii. By using addAll() method
✓ To add only one collection data into another collection use constructor approach.
✓ To add more than one collection into single collection use addAll() method.
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
//constructor approach
ArrayList<String> a1 = new ArrayList<String>();
a1.add("ratan");
ArrayList<String> a2 = new ArrayList<String>(a1);
a2.add("durga");
System.out.println(a2);
339 | P a g e
CoreJava Material RATANIT Mr. Ratan
Ex-7:
import java.util.*;
class Test
{ public static void main(String[] args)
{ Emp e1 = new Emp(111,"ratan");
Emp e2 = new Emp(222,"Sravya");
Emp e3 = new Emp(333,"aruna");
Emp e4 = new Emp(444,"anu");
System.out.println(a2.contains(e1));
System.out.println(a2.containsAll(a1));
a2.remove(e1);
System.out.println(a2.contains(e1));
System.out.println(a2.containsAll(a1));
Observation :
a2.removeAll(a1); // it removes all a1 data except a2.
a2.retainAll(a1); // it removes all a2 data except a1
340 | P a g e
CoreJava Material RATANIT Mr. Ratan
To swap the data from one index position to another index position then use swap() method.
public static void swap(java.util.List<?>, int, int);
package com.dss;
import java.util.ArrayList;
import java.util.Collections;
341 | P a g e
CoreJava Material RATANIT Mr. Ratan
import java.util.*;
class ArrayListDemo
{ public static void main(String[] args)
{
//Conversion of array to ArrayList by using asList() method
String[] str={"ratan","Sravya","aruna"};
ArrayList<String> a1 = new ArrayList<String>(Arrays.asList(str));
a1.add("ratan”);
a1.add("anu");
for (String s: a1)
{ System.out.println(s);
}
Object[] o = a3.toArray();
for (Object oo :o)
{ System.out.println(oo);
}
}
}
342 | P a g e
CoreJava Material RATANIT Mr. Ratan
LinkedList constructors: To check the constructor use javap command or API documentation.
LinkedList(); it builds empty LinkedList.
LinkedList(java/util/Collection) Used to add one collection data into another collection.
l.removeFirst();
l.removeLast();
System.out.println("after deletion first & last:-"+l);
l.remove("E");
l.remove(2);
System.out.println("after deletion :-"+l);
l.set(2,”ratan");
System.out.println("after seting:-"+l);
System.out.println(l.isEmpty());
l.clear();
System.out.println(l.isEmpty());
}
}
343 | P a g e
CoreJava Material RATANIT Mr. Ratan
Ex-2:
package com.dss;
public class Book {
int id;
String name,author;
public Book(int id, String name, String author) {
this.id = id;
this.name = name;
this.author = author;
}
}
package com.dss;
import java.util.LinkedList;
import java.util.ListIterator;
public class Test2 {
public static void main(String[] args) {
LinkedList<Book> l = new LinkedList<Book>();
l.add(new Book(111, "java", "ratan"));
l.add(new Book(222, "c", "durga"));
l.add(new Book(333, "cpp", "anu"));
344 | P a g e
CoreJava Material RATANIT Mr. Ratan
✓ Insertion, remove data on Arraylist is slow because when we perform the operations internally it
requires more shift operations.
But insertion,remove on LinkedList is faster because shift operations are not required.
345 | P a g e
CoreJava Material RATANIT Mr. Ratan
346 | P a g e
CoreJava Material RATANIT Mr. Ratan
Ex-1:
package vectorEx;
import java.util.Iterator;
import java.util.Vector;
Ex-2 : Copying data from Vector to ArrayList:- use copy() method of Collections class.
import java.util.*;
class Test
{ public static void main(String[] args)
{ ArrayList<String> al = new ArrayList<String>();
al.add("ratan");
al.add("anu");
347 | P a g e
CoreJava Material RATANIT Mr. Ratan
ex-3:
package vectorEx;
public class Product {
int id;
String name;
int cost;
public Product(int id, String name, int cost) {
this.id = id;
this.name = name;
this.cost = cost;
}
}
package vectorEx;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Vector;
public class Test3 {
public static void main(String[] args) {
Vector<Product> products = new Vector<Product>();
products.add(new Product(111, "pen", 20));
products.add(new Product(222, "fan", 300));
products.add(new Product(333, "light", 200));
348 | P a g e
CoreJava Material RATANIT Mr. Ratan
ex-1 :
import java.util.*;
class Test
{ public static void main(String[] args)
{ Stack<String> s = new Stack<String>();
s.push("ratan");
s.push("anu");
s.push("durga");
System.out.println(s);
System.out.println(s.size());
System.out.println(s.isEmpty());
s.clear();
System.out.println(s.isEmpty());
}
}
349 | P a g e
CoreJava Material RATANIT Mr. Ratan
There are three ways to read the data from collection classes
1. By using for-each loop
2. By using get() method
3. By using cursor
ListIterator methods:
public abstract boolean hasNext();
public abstract E next();
public abstract boolean hasPrevious();
public abstract E previous();
public abstract int nextIndex();
public abstract int previousIndex();
public abstract void remove();
public abstract void set(E); //replacement
public abstract void add(E);
350 | P a g e
CoreJava Material RATANIT Mr. Ratan
351 | P a g e
CoreJava Material RATANIT Mr. Ratan
//ListIterator cursor : with generic version : print the data forward & backward direction
ListIterator<String> lstr2 = al.listIterator();
while(lstr2.hasNext())
{ String s = lstr2.next();
System.out.println(s);
}
while(lstr2.hasPrevious())
{ String s = lstr2.previous();
System.out.println(s);
}
}
}
ex-4 : Reading the data using (for-each , get() , cursor )
import java.util.*;
class Test
{ public static void main(String[] args)
{ ArrayList<String> al =new ArrayList<String>();
al.add("ratan");
al.add("anu");
al.add("sravya");
352 | P a g e
CoreJava Material RATANIT Mr. Ratan
package com.dss;
import java.util.ArrayList;
import java.util.Iterator;
public class Test {
public static void main(String[] args) {
ArrayList<String> al =new ArrayList<String>();
al.add("ratan");
al.add("anu");
al.add("sravya");
ex -6:
import java.util.*;
class Test
{ public static void main(String[] args)
{ ArrayList<String> al =new ArrayList<String>();
al.add("ratan");
al.add("anu");
al.add("sravya");
353 | P a g e
CoreJava Material RATANIT Mr. Ratan
Ex- 7: Adding Book objects into ArrayList then removing the data using Iterator cursor.
Book.java
package com.dss;
public class Book {
int id;
String name;
String author;
public Book(int id, String name, String author) {
this.id = id;
this.name = name;
this.author = author;
}
}
Test.java
package com.dss;
import java.util.ArrayList;
import java.util.Iterator;
354 | P a g e
CoreJava Material RATANIT Mr. Ratan
✓ It is possible to sort the collection data by using sort() method of Collections class and by default it
perform ascending order .
✓ if we want to perform sorting data must satisfies the below conditions,
o The data must be homogenous
o Must implements Comparable interface.
import java.util.*;
class Test
{ public static void main(String[] args)
{ ArrayList<String> al = new ArrayList<String>();
al.add("ratan");
al.add("anu");
al.add("Sravya");
System.out.println("ArrayList data before sorting="+al);
Collections.sort(al);
System.out.println("ArrayList data after sorting ascending order="+al);
}
}
Case 1: if we are trying to perform sorting of heterogeneous data , while performing comparison(by
using comapreTo() method) JVM will generate java.lang.ClassCastException
ArrayList al = new ArrayList();
al.add("ratan");
al.add(10);
Collections.sort(al);
Case 2: when we perform sorting of data if the data contains null value while performing comparison
(by using compareTo()) JVM will generate java.lang.NullPointerException.
ArrayList al = new ArrayList();
al.add("ratan");
al.add(null);
Collections.sort(al);
355 | P a g e
CoreJava Material RATANIT Mr. Ratan
Ex:
If we want to perform descending order use Collections.reverseOrder() method along with
Collection.sort() method.
Collections.sort(list , Collections.reverseOrder());
package com.dss;
import java.util.ArrayList;
import java.util.Collections;
Java.lang.Comparable :
✓ If we want to sort user defined class like Emp based on eid or ename with default natural sorting
order then your class must implements Comparable interface.
✓ Comparable interface present in java.lang package it contains only one method compareTo(obj) then
must override that method to write the sorting logics.
✓ If your class is implementing Comparable interface then that objects are sorted automatically by
using Collections.sort(). And the objects are sorted by using compareTo() method of that class.
“ratan”.compareTo(“anu”) ==> +ve ==>change the order
“ratan”.compareTo(“ratan”) ==> 0 ==>no change
“anu”.compareTo(“ratan”) ==> -ve ==>no change
356 | P a g e
CoreJava Material RATANIT Mr. Ratan
Ex :
Emp.java: Normal version of comparable performing sorting of eid
class Emp implements Comparable
{ int eid;
String ename;
Emp(int eid,String ename)
{ this.eid=eid;
this.ename=ename;
}
public int compareTo(Object o)
{ Emp e = (Emp)o;
if (eid == e.eid ) return 0;
else if (eid > e.eid) return 1;
else return -1;
}
}
Collections.sort(al);
for(Emp e : al)
{ System.out.println(e.eid+" "+e.ename);
}
}
}
357 | P a g e
CoreJava Material RATANIT Mr. Ratan
3. Sorting method
Int compareTo(Object o1)
int compare(Obj o1,Obj o2)
This method compares this
This method compares o1
object with o1 object and
and o2 objects. and returns a
returnsa integer.Its value has
integer.Its value has
following meaning
following meaning.
positive – this object is
greater than o1
positive – o1 is greater
than o2
zero this object equals to o1
negative this object is less zero –o1 equals to o2
than o1 negative– o1 is less than
o1
4. Method calling to
Collections.sort(List) Collections.sort(List, Compar)
perform sorting
6. which type of sorting Default natual sorting only For customized sorting
order& customized also. order.
358 | P a g e
CoreJava Material RATANIT Mr. Ratan
Comparator sorting:
Emp.java:
class Emp
{ int eid;
String ename;
Emp(int eid,String ename)
{ this.eid=eid;
this.ename=ename;
}
}
EidComp.java:- normal version of comparator : type casting required
import java.util.Comparator;
public class EidComp implements Comparator{
public int compare(Object o1, Object o2) {
Emp e1 = (Emp)o1;
Emp e2 = (Emp)o2;
if(e1.eid==e2.eid) return 0;
else if(e1.eid>e2.eid) return 1;
else return -1;
}
}
359 | P a g e
CoreJava Material RATANIT Mr. Ratan
In Collection frame work every class implements Cloneable & Serializable interfaces to support
cloning process & serialization process.
ex1:
package com.dss;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.RandomAccess;
ex2: Cloning process : The process of creating exactly duplicate objects is called cloneing.
import java.util.*;
class Test
{ public static void main(String[] args)
{ LinkedList<String> linked= new LinkedList<String>();
linked.add("First");
linked.add("Second");
linked.add("Third");
linked.add("Random");
System.out.println("Actual LinkedList:"+linked);
360 | P a g e
CoreJava Material RATANIT Mr. Ratan
ex-3 : Serialization process : To perform serialization the class must implements Serializable interface.
package com.dss;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ArrayList<Emp> al = new ArrayList<Emp>();
al.add(new Emp(111, "ratan"));
al.add(new Emp(222, "anu"));
//Serialization process
FileOutputStream outputStream = new FileOutputStream("abc.txt");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
objectOutputStream.writeObject(al);
outputStream.close();
objectOutputStream.close();
System.out.println("serialization process completed......");
//Deserialization process
FileInputStream inputStream = new FileInputStream("abc.txt");
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
ArrayList<Emp> arraylist = (ArrayList<Emp>)objectInputStream.readObject();
outputStream.close();
objectInputStream.close();
System.out.println("Deserialization process completed......");
for(Emp e:arraylist)
{ System.out.println(e.eid+"---"+e.ename);
}
}
}
Observation :
class Emp implements Serializable { }
class Student { }
class Test
{ public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(new Emp());
al.add(new Student());
}
}
✓ To perform serialization of ArrayList inside the arraylist all objects must be serializable objects.
✓ In above example serialization of Arraylist data is not possible because the Student obj is not
implements seralizable interface.
361 | P a g e
CoreJava Material RATANIT Mr. Ratan
Collection(i) 1.2 v
extends
1.2v
Set(i)
implements extends
extends extends
1.4 v
LinkedHashSet(c) NavigableSet(i) 1.6v
implements
TreeSet(c) 1.2v
List vs. Set : List allows duplicates & set duplicates not allowed.
Java.util.HashSet:
public class java.util.HashSet extendsjava.util.AbstractSet
implements java.util.Set<E>, java.lang.Cloneable, java.io.Serializable
362 | P a g e
CoreJava Material RATANIT Mr. Ratan
Constructors:
1. public HashSet(); it creates default HashSet.
new HashSet();
default capacity: 16 default fill ratio : 0.75
4. Public HashSet(java/util/Collection); Adding one collection data into another collection data.
HashSet<String> h1 = new HashSet<String>();
h1.add("ratan");
HashSet<String> h2 = new HashSet<String>(h1);
h2.add("no1");
System.out.println(h2);
ex: when we insert duplicates it insert the first value & ignores the next occurrences.
import java.util.*;
class Test
{ public static void main(String[] args)
{ HashSet<String> h = new HashSet<String>();
System.out.println(h.add("ratan")); //true
System.out.println(h.add("ratan")); //false
System.out.println(h.add("ratan")); //false
System.out.println(h);
}
}
363 | P a g e
CoreJava Material RATANIT Mr. Ratan
Java.util.LinkedHashSet:
Note : HashSet not preserved insertion order but LinkedHashset preserved insertion order.
Conastructors:-
Public LinkedHashSet();
Public LinkedHashSet(java/util/Collection<? extends E>);
Public LinkedHashSet(int capacity);
Public LinkedHashSet(int capacity,float fillRatio);
364 | P a g e
CoreJava Material RATANIT Mr. Ratan
ex : inserting Emp data into LinkedHashSet & removing data using Iterator cursor.
Emp.java :
package com.dss;
public class Emp {
int eid;
String ename;
public Emp(int eid, String ename) {
this.eid = eid;
this.ename = ename;
}
}
Test.java:
package com.dss;
import java.util.Iterator;
import java.util.LinkedHashSet;
for(Emp e : h)
{ System.out.println(e.eid+" "+e.ename);
}
}
}
365 | P a g e
CoreJava Material RATANIT Mr. Ratan
Java.util.TreeSet:
TreeSet Constructors:
TreeSet() Constructs a new, empty tree set, sorted according to the natural ordering of its elements.
TreeSet(SortedSet<E> s)
Constructs a new tree set containing the same elements and using the same ordering as the
specified sorted set.
Ex-1:
package com.dss;
import java.util.TreeSet;
366 | P a g e
CoreJava Material RATANIT Mr. Ratan
✓ When we insert the data in TreeSet, by default it prints the data in sorting order(ascending or
alphabetical order) because it is implementing SortedSet interface.
✓ To perform the sorting internally it uses compareTo() method and it compare the two objects it
returns int value as a return value.
SortedSet<Integer> s2 = t.tailSet(4);
TreeSet<Integer> t2 = new TreeSet<Integer>(s2);
System.out.println(t2);
SortedSet<Integer> s3 = t.headSet(6);
TreeSet<Integer> t3 = new TreeSet<Integer>(s3);
System.out.println(t3);
}
}
367 | P a g e
CoreJava Material RATANIT Mr. Ratan
package com.dss;
import java.util.Comparator;
import java.util.TreeSet;
368 | P a g e
CoreJava Material RATANIT Mr. Ratan
Product.java
package com.dss;
public class Product {
int id;
String name;
double cost;
public Product(int id, String name, double cost) {
this.id = id;
this.name = name;
this.cost = cost;
}
}
Test.java
package com.dss;
import java.util.Comparator;
import java.util.TreeSet;
for(Product p : t1)
{ System.out.println(p.id+" "+p.name+" "+p.cost);
}
}
}
369 | P a g e
CoreJava Material RATANIT Mr. Ratan
ex -5 program to insert StringBuffer data into TreeSet to perform sorting in alphabetical order.
import java.util.*;
class Test
{ public static void main(String[] args)
{ TreeSet<StringBuffer> t = new TreeSet<StringBuffer>(new MyComp());
t.add(new StringBuffer("ccc"));
t.add(new StringBuffer("aaa"));
t.add(new StringBuffer("bbb"));
System.out.println(t);
}
}
class MyComp implements Comparator<StringBuffer>
{ public int compare(StringBuffer sb1,StringBuffer sb2)
{ String s1 = sb1.toString();
String s2 = sb2.toString();
return -s1.compareTo(s2);
}
}
Ex -6 : write a program to insert String & StringBuffer object into TreeSet perform sorting.
import java.util.*;
class Test
{ public static void main(String[] args)
{ TreeSet t = new TreeSet(new MyComp());
t.add("ratan");
t.add(new StringBuffer("sravya"));
t.add("anu");
t.add(new StringBuffer("suneelbabu"));
t.add("sri");
System.out.println(t);
}
}
class MyComp implements Comparator
{ public int compare(Object o1,Object o2)
{ String s1 = o1.toString();
String s2 = o2.toString();
return -s1.compareTo(s2);
}
}
370 | P a g e
CoreJava Material RATANIT Mr. Ratan
import java.util.*;
class Test
{ public static void main(String[] args)
{
TreeSet<Integer> t=new TreeSet<Integer>();
t.add(50);
t.add(20);
t.add(40);
t.add(10);
t.add(30);
System.out.println(t); //10 20 30 40 50
System.out.println(t.headSet(30)); //[10,20]
System.out.println(t.tailSet(30)); //[30,40,50]
System.out.println(t.subSet(20,50)); //[20,30,40]
371 | P a g e
CoreJava Material RATANIT Mr. Ratan
Queue interface
import java.util.Iterator;
import java.util.PriorityQueue;
public class Test {
public static void main(String[] args) {
PriorityQueue<String> pq = new PriorityQueue<String>();
pq.add("ratan");
pq.add("anu");
pq.add("durga");
pq.add("sunny");
pq.add("xxx");
System.out.println(pq);
System.out.println(pq.peek());
System.out.println(pq.poll());
System.out.println(pq);
pq.remove();
372 | P a g e
CoreJava Material RATANIT Mr. Ratan
pq.remove("xxx");
System.out.println(pq);
Assignment : create the class Book with fields : id, name , author, quantity
Create the PriorityQueue add 3-book objects print the data
Note : if we are adding the data in priorityQueue the data must be homogeneous & must
implements comparable interface.
Map interface:-
1.2v
Map(i)
implements implements
extends extends
1.4 v
LinkedHashMap(c NavigableMap(i) 1.6v
)
implements
TreeMap(C) 1.2v
✓ Map is used to store two objects at a time in the form of key value pairs. Here the key is object &
value is object.
✓ The key value pair is known as entry, the map contains group of entries.
✓ In map the keys must be unique but values we can duplicate.
Java.util.HashMap:-
public class java.util.HashMap extendsjava.util.AbstractMap
implements java.util.Map
java.lang.Cloneable,java.io.Serializable
373 | P a g e
CoreJava Material RATANIT Mr. Ratan
Constructors:-
HashMap(); it creates default HashMap.
HashMap(int capacity); It creates the hashmap with specified capacity but the default capacity is 16.
Entry:-
✓ The each and every key value pair is called Entry.The Map contains group of entries.
✓ Entry is sub interface of Map interface hence get the entry interface by using Map interface.
interface Map
{ interface Entry
{ public abstract Object getKey();
public abstract Object getValue();
public abstract Object setValue();
}
}
✓ To get all the keys use keyset() method.
public java/util/Set<K> keySet();
Example :
package com.dss;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
public class Test {
public static void main(String[] args) {
HashMap<Integer, String> h = new HashMap<Integer,String>();
h.put(111, "ratan");
374 | P a g e
CoreJava Material RATANIT Mr. Ratan
h.put(222, "anu");
h.put(333, "durga");
System.out.println(h);
Set<Integer> s = h.keySet();
System.out.println(s);
Collection<String> s1 = h.values();
System.out.println(s1);
Set<Entry<Integer,String>> s2 = h.entrySet();
Iterator<Entry<Integer,String>> iterator = s2.iterator();
while(iterator.hasNext())
{ Entry<Integer, String> e = iterator.next();
System.out.println(e.getKey()+"----"+e.getValue());
}
}
}
Java.util.LinkedHashMap:-
public class java.util.LinkedHashMap extends java.util.HashMap
implements java.util.Map
Constructors:-
LinkedHashMap(); it creates default HashMap. Default capacity : 16 default fill ratio : 0.75
LinkedHashMap(java/util/Map); Used to add one map data into another map.
LinkedHashMap(int user-capacity); It creates the hashmap with specified capacity.
LinkedHashMap(int user-capacity, float fillRatio); creates hashMap with specified capacity & fillRatio.
Test.java:
package com.dss;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
public class Test {
public static void main(String[] args) {
HashMap<Emp, Student> h = new HashMap<Emp,Student>();
h.put(new Emp(111, "ratan"),new Student(1, "aaa"));
h.put(new Emp(222, "anu"),new Student(2, "bbb"));
375 | P a g e
CoreJava Material RATANIT Mr. Ratan
Set<Entry<Emp,Student>> s2 = h.entrySet();
Iterator<Entry<Emp,Student>> iterator = s2.iterator();
while(iterator.hasNext())
{ Entry<Emp, Student> e = iterator.next();
Emp ee = e.getKey();
System.out.println(ee.eid+"----"+ee.ename);
Student ss = e.getValue();
System.out.println(ss.sid+"--"+ss.sname);
}
import java.util.*;
class Test
{ public static void main(String[] args)
{ //constructor approach
LinkedHashMap<Integer,String> h1 = new LinkedHashMap<Integer,String>();
h1.put(111,"ratan");
LinkedhashMap<Integer,String> h2 = new LinkedHashMap<Integer,String>(h1);
h2.put(222,"anu");
376 | P a g e
CoreJava Material RATANIT Mr. Ratan
Java.util.TreeMap:-
public class java.util.TreeMap extends java.util.AbstractMap
implements java.util.NavigableMap,java.lang.Cloneable, java.io.Serializable
Constructors:-
TreeMap(); it will create empty treemap that will be sorted by using natural order of its keys.
TreeMap(java/util/Comparator); It create treemap that will be sorted by using customized sorting oder.
Observations of TreeMap:
Case1:- TreeMap h = new TreeMap();
h.put(444,"ratan");
h.put(222,"anu");
h.put(111,"aaa");
System.out.println(h);//{111=aaa, 222=anu, 444=ratan}
In treemap when we insert the data that will be printed in sorting order based on key.
377 | P a g e
CoreJava Material RATANIT Mr. Ratan
378 | P a g e
CoreJava Material RATANIT Mr. Ratan
379 | P a g e
CoreJava Material RATANIT Mr. Ratan
Example :-
Ceiling() it return current provided value or greater value but if treemap does not contains same
or greater value then it returns null .
floor():- it returns current value or less value but if treemap does notcontains same value or less
then it return null.
pollFirstEntry:- it removes first entry & it prints that entry.
pollLastEntry():- it removes last entry and it prints that entry.
import java.util.*;
class Test
{ public static void main(String[] args)
{ TreeMap h = new TreeMap();
h.put(111,"ratan");
h.put(222,"anu");
h.put(444,"aaa");
System.out.println(h);
System.out.println(h.ceilingKey(222));
System.out.println(h.ceilingEntry(333));
System.out.println(h.floorKey(222));
System.out.println(h.floorEntry(333));
System.out.println(h.ceilingKey(666));
Map.Entry m1 = h.pollFirstEntry();
System.out.println(m1.getKey()+"---"+m1.getValue());
Map.Entry m2 = h.pollLastEntry();
System.out.println(m2.getKey()+"---"+m2.getValue());
System.out.println(h);
}
}
380 | P a g e
CoreJava Material RATANIT Mr. Ratan
Java.util.HashTable:-
public class java.util.Hashtable extends java.util.Dictionary
implements java.util.Map,java.lang.Cloneable, java.io.Serializable
Constructors:-
HashTable();it creates default HashMap.
HashTable (java/util/Map<? extends K, ? extends V> var);
it creates the HashMap by initializing the values specified in var.
HashTable (int capacity);
It creates the hashmap with specified capacity but the default capacity is 11.
HashTable (int capacity, float fillRatio);
It creates the hashMap with specified capacity & fillRatio.
Example:-
import java.util.Hashtable;
import java.util.Collection;
import java.util.Set;
class Test
{ public static void main(String[] args)
{ Hashtable<Integer,String> h = new Hashtable<Integer,String>();
h.put(1,"one");
h.put(2,"two");
h.put(3,"three");
System.out.println(h);
System.out.println(h.get("1"));//one
System.out.println(h.isEmpty());
h.remove(3);
System.out.println(h.containsKey("1"));
System.out.println(h.containsKey("3"));
System.out.println(h.containsValue("one"));
System.out.println(h.size());
System.out.println(h.isEmpty());
h.clear();
System.out.println(h.isEmpty());
}
}
381 | P a g e
CoreJava Material RATANIT Mr. Ratan
Ex:
import java.util.Hashtable;
import java.util.Enumeration;
public class Test {
public static void main(String[] args) {
Enumeration names;
String key;
names = hashtable.keys();
while(names.hasMoreElements()) {
key = (String) names.nextElement();
System.out.println("Key: " +key+ " & Value: " +
hashtable.get(key));
}
}
}
Java.util.IdentityHashMap:-
public class java.util.IdentityHashMap extends java.util.AbstractMap
implements java.util.Map,java.io.Serializable, java.lang.Cloneable
Example:-
import java.util.*;
class Test
{ public static void main(String[] args)
{ //equals() method to identify duplicate keys.
HashMap<Integer,String> h = new HashMap<Integer,String>();
h.put(new Integer(10),"ratan");
h.put(new Integer(10),"anu");
System.out.println(h);
382 | P a g e
CoreJava Material RATANIT Mr. Ratan
System.out.println(h1);
}
}
E:\>java Test
{10=anu}
{10=anu, 10=ratan}
Java.util.WeakHashMap:-
public class java.util.WeakHashMap extends java.util.AbstractMap
implements java.util.Map
HashMap h.put(a,"ratan");
import java.util.*; System.out.println(h);
class A a=null;
{ public String toString() System.gc();
{ return "A"; System.out.println(h);
} }
public void finalize() }
{System.out.println("object destroyed"); E:\>java Test
} {A=ratan}
}; {A=ratan}
class Test
{ public static void main(String[] args) WeakHashMap
{ HashMap h = new HashMap(); import java.util.*;
A a= new A(); class A
383 | P a g e
CoreJava Material RATANIT Mr. Ratan
To get synchronized version of List interface use fallowing Collections class static method
public static List synchronizedList(List l)
ArrayList al = new ArrayList();
List l = Collections.synchronizedList(al);
To get synchronized version of Set interface use fallowing Collections class static method
public static Set synchronizedSet(Set s)
HasSet h = new HashSet();
Set h1 = Collections.synchronizedSet(h);
To get synchronized version of Map interface use fallowing Collections class static method
public static Map synchronized Map(Map m)
HashMap h = new HashMap();
Map m = Collections.synchronizedMap(h);
To get synchronized version of TreeSet use fallowing Collections class static method
Collections.synchronizedSortedSet(SortedSet<T> s)
TreeSet t = new TreeSet();
SortedSet s = Collections.synchronizedSortedSet(t);
384 | P a g e
CoreJava Material RATANIT Mr. Ratan
To get synchronized version of TreeMap use fallowing Collections class static method
Collections.synchronizedSortedMap(SortedMap<K,V> m)
TreeMap t = new TreeMap();
SortedMap s = Collections.synchronizedSortedMap(t);
385 | P a g e
CoreJava Material RATANIT Mr. Ratan
Java.util.Properties:
✓ To get the flexibility of modifications use properties file.
✓ In standalone applications(JDBC) or web-applications(web sites) the data is frequently changing
like,Database username,Database password,url,driver …etc
✓ in above scenario for every change must perform modifications in all .java files but it is
complex.to overcome this problem use properties file.
✓ Properties file is a normal text file with .properties extension & it contains key=value formatted
data but both key and value is string format.
✓ Once we done modifications on .properties file that modifications are reflected all the .java files.
abc.properties :
username = system
password = manager
Test.java:-
import java.util.*;
import java.io.*;
class Test
{ public static void main(String[] args) throws FileNotFoundException,IOException
{ //locate properties file
FileInputStream fis=new FileInputStream("abc.properties");
//load the properties file by using load() method of Properties class
Properties p = new Properties();
p.load(fis);
Collections
386 | P a g e
CoreJava Material RATANIT Mr. Ratan
387 | P a g e
CoreJava Material RATANIT Mr. Ratan
388 | P a g e
CoreJava Material RATANIT Mr. Ratan
INTERNATIONALIZATION (i18N)
➢ Internationalization is also called as i18n because in between I & n 18 characters are present.
➢ By using Locale class and ResourceBundle class we are enable I18n on the application.
➢ Local is nothing but language + country.
➢ For making your application to support I18n we need to prepare local specific properties file it
means for English one properties file & hindi one properties file …etc.
➢ The property file format is key = value
➢ The properties file name fallowed pattern bundlenamewith language code and country code.
o ApplicationMessages_en_US.properties.
➢ In single web application contains different properties file all the properties files key must be
same and values are changed local to Locale.
Java.util.Locale:-
➢ Locale Object is decide properties file based on argument you passed and then it display locale
specific details based on Properties file entry.
Locale l = new Locale(args[0],args[1]);
Locale l = new Locale(en,US);
D:\5batch>javap java.util.Locale
Compiled from "Locale.java"
public final class java.util.Locale extends java.lang.Object i
public static final java.util.Locale ENGLISH;
public static final java.util.Locale FRENCH;
public static final java.util.Locale GERMAN;
public static final java.util.Locale ITALIAN;
public static final java.util.Locale JAPANESE;
public static final java.util.Locale KOREAN;
public static final java.util.Locale CHINESE;
public static final java.util.Locale SIMPLIFIED_CHINESE;
public static final java.util.Locale TRADITIONAL_CHINESE;
public static final java.util.Locale FRANCE;
public static final java.util.Locale GERMANY;
public static final java.util.Locale ITALY;
public static final java.util.Locale JAPAN;
public static final java.util.Locale KOREA;
public static final java.util.Locale CHINA;
public static final java.util.Locale PRC;
public static final java.util.Locale TAIWAN;
public static final java.util.Locale UK;
public static final java.util.Locale US;
public static final java.util.Locale CANADA;
public static final java.util.Locale CANADA_FRENCH;
389 | P a g e
CoreJava Material RATANIT Mr. Ratan
390 | P a g e
CoreJava Material RATANIT Mr. Ratan
Application 1:-
Steps to design application:-
Step-1:- prepare properties files to support different languages and countries.
Application.properties default properties file(base properties file)
Application_fr_FR.properties French properties file
Allication_ratan_RATAN.properties Ratan country properties file
Step 2:- create locale object it identified particular language and country and it decides
execution of properties file.
Locale l = new Locale(“en”,”US”);
The above statement specify language is English and country united states
Locale l = new Locale("fr","CA");
Locale x = new Locale("fr","FR");
The above two locales specifies France language in Canada & France
Instead of hard coding language name and country name get the values from command prompt
at runtime.
Public static void main(String[ ] args)
{ Locale l = new Locale(args[0],args[1]);
}
D:\5batch>java Test fr FR
Application.properties:-
countryname = USA
lang = eng
Application_fr_FR.properties:-
countryname = canada
lang = france
Allication_ratan_RATAN.properties:-
countryname=Ratan
lang= ratan
391 | P a g e
CoreJava Material RATANIT Mr. Ratan
Test.java:-
import java.util.*;
class Test
{ public static void main(String[] args)
{
//if no local is Matched this property file is executed
ResourceBundle bundle1 = ResourceBundle.getBundle("Application");
//it create ResourceBundle with local that is already defined
Locale l1 = Locale.FRANCE;
ResourceBundle bundle2 = ResourceBundle.getBundle("Application",l1);
//it creates ResourceBundle with new user created Locale
Locale l2 = new Locale("ratan","RATAN")
ResourceBundle bundle3 = ResourceBundle.getBundle("Application",l2);
System.out.println(bundle1.getString("countryname")+"--"+bundle1.getString("lang"));
System.out.println(bundle2.getString("countryname")+"--"+bundle2.getString("lang"));
System.out.println(bundle3.getString("countryname")+"--"+bundle3.getString("lang"));
}
}
Output:-
D:\5batch>java Test
USA--eng
Canada--france
Ratan--Ratan
APPLICATION 2:-
import java.util.*;
class Test
{ public static void main(String[] args)
{ //creates local object with the help of arguments
Locale l = new Locale(args[0],args[1]);
//it creates resource bundle with local passed from as command line arguments
ResourceBundle bundle = ResourceBundle.getBundle("Application",l);
System.out.println(bundle.getString("countryname"));
System.out.println(bundle.getString("lang"));
}
}
D:\5batch>java Test x y
USA
eng
D:\5batch>java Test fr FR
canada
france
D:\5batch>java Test ratan RATAN
Ratan
ratan
392 | P a g e
CoreJava Material RATANIT Mr. Ratan
Application.properties:-
wish = hello
lovely = i love you
angry = i hate you
Application_fr_FR.properties:-
wish = hlloe
lovely = i evol you
angry = i etah you
Application_hi_IN.properties:-
wish=\u0c39\u0c46\u0c32\u0c4d\u0c32\u0c4a
lovely=\u0c07 \u0c32\u0c4a\u0c35\u0c46 \u0c2f\u0c4a\u0c09
angry=\u0c07 \u0c39\u0c24\u0c46 \u0c09
import java.util.*;
class Test
{ public static void main(String[] args)
{ Locale l = new Locale(args[0],args[1]);
ResourceBundle rb = ResourceBundle.getBundle("Application",l);
System.out.println(rb.getString("wish"));
System.out.println(rb.getString("lovely"));
System.out.println(rb.getString("angry"));
}
}
D:\5batch>java Test fr FR
D:\5batch>java Test x y hlloe
hello i evol you
i love you i etah you
i hate you D:\5batch>java Test hi IN
??????
? ???? ???
? ??? ?
393 | P a g e
CoreJava Material RATANIT Mr. Ratan
Step 2:- unzip the file and click on index.html page select language and type the words.
Step 3:- copy the content and save the data in text file and while saving select Unicode.
394 | P a g e
CoreJava Material RATANIT Mr. Ratan
Application :-
Application.properties:-
wish = hello
lovely = i love you
angry = i hate you
Application_fr_FR.properties:-
wish = hlloe
lovely = i evol you
angry = i etah you
Application_tl_IN.properties:-
wish=\u0c39\u0c46\u0c32\u0c4d\u0c32\u0c4a
lovely=\u0c07 \u0c32\u0c4a\u0c35\u0c46 \u0c2f\u0c4a\u0c09
angry=\u0c07 \u0c39\u0c24\u0c46 \u0c09
Test.java:-
import java.util.*;
import java.awt.*;
class Test
{ public static void main(String[] args)
{ Locale l = new Locale(args[0],args[1]);
ResourceBundle b = ResourceBundle.getBundle("Application",l);
Frame f = new Frame(); //to create frame
f.setVisible(true); //to provide visibility to frame
f.setSize(300,75);//to align the frame set bounds
f.setLayout(new FlowLayout());//to set the frame proper format
//creation of buttons with labels
Button b1 = new Button(b.getString("wish"));
Button b2 = new Button(b.getString("lovely"));
Button b3 = new Button(b.getString("angry"));
//adding buttons into frame
f.add(b1);
f.add(b2);
f.add(b3);
}
}
395 | P a g e
CoreJava Material RATANIT Mr. Ratan
Test.java:- example
import java.util.*;
public class Test {
static public void main(String[] args) {
String language;
String country;
Locale currentLocale;
ResourceBundle messages;
if (args.length != 2)
{ language = new String("en");
country = new String("US");
}
else
{ language = new String(args[0]);
country = new String(args[1]);
}
currentLocale = new Locale(language, country);
messages = ResourceBundle.getBundle("Application", currentLocale);
System.out.println(messages.getString("wish"));
System.out.println(messages.getString("lovely"));
System.out.println(messages.getString("angry"));
}
}
D:\5batch>java Test
hello
i love you
i hate you
D:\5batch>java Test x y
hello
i love you
396 | P a g e
CoreJava Material RATANIT Mr. Ratan
i hate you
D:\5batch>java Test tl IN
??????
? ???? ???
? ??? ?
D:\5batch>java Test fr FR
hlloe
i evol you
i etah you
Example :- display Date in different Locale.
DateFormat.DEFAULT,
DateFormat.SHORT,
DateFormat.MEDIUM,
DateFormat.LONG,
DateFormat.FULL
Test.java:-
import java.util.*;
import java.text.DateFormat;
class Test
{ public static void main(String[] args)
{
Date d = new Date();
//default locale en US
DateFormat df1 = DateFormat.getDateInstance(DateFormat.DEFAULT,Locale.getDefault());
System.out.println(df1.format(d));
//date of fresh
DateFormat df2 =DateFormat.getDateInstance(DateFormat.MEDIUM,Locale.FRENCH);
System.out.println(df2.format(d));
//date of Italy
DateFormat df3 =DateFormat.getDateInstance(DateFormat.SHORT,Locale.ITALY);
System.out.println(df3.format(d));
}
};
397 | P a g e
CoreJava Material RATANIT Mr. Ratan
import java.util.*;
import java.text.*;
class Test
{ public static void main(String[] args)
{Date d = new Date();
DateFormat df1 = DateFormat.getTimeInstance(DateFormat.DEFAULT,Locale.getDefault());
System.out.println(df1.format(d));
DateFormat df2 = DateFormat.getTimeInstance(DateFormat.MEDIUM,Locale.FRENCH);
System.out.println(df2.format(d));
DateFormat df3 = DateFormat.getTimeInstance(DateFormat.SHORT,Locale.ITALY);
System.out.println(df3.format(d));
}
};
Example on both data and Time format:-
import java.util.*;
import java.text.*;
class Test
{ public static void main(String[] args)
{ Date d = new Date();
DateFormat df1 = DateFormat.getDateTimeInstance(DateFormat.FULL,DateFormat.FULL,Locale.getDefault());
System.out.println(df1.format(d));
DateFormat df2 = DateFormat.getDateTimeInstance(DateFormat.FULL,DateFormat.FULL,Locale.FRENCH);
System.out.println(df2.format(d));
}
};
398 | P a g e
CoreJava Material RATANIT Mr. Ratan
Internationalization
399 | P a g e
CoreJava Material RATANIT Mr. Ratan
JVM Architecture
✓ JVM is a software it is a specification that provide the runtime environment in which the java
byte code executed.
✓ JVM is a platform dependent software(installing along with JDK software).
✓ Java is developed with the concept of WORA which runs on a VM(virtual machine).
✓ The JVM understandable file format is .class file it contains byte code.
Operations of JVM:-
✓ Loading the byte code into memory. Converting byte code instructions into machine instructions.
✓ Allocating sufficient memory space for class properties.
✓ Providing runtime environment in which java byte code is executed.
✓ JVM implementation is known as JRE(java runtime environment)
✓ JVM is interpreter to execute java program line by line.
JVM Architecture:-
400 | P a g e
CoreJava Material RATANIT Mr. Ratan
401 | P a g e
CoreJava Material RATANIT Mr. Ratan
Emp.java
class Emp
{ private int eid;
private String ename;
public void setEname(String ename)
{ this.ename=ename;
}
public void setEid(int eid)
{ this.eid=eid;
}
public int getEid()
{ return eid;
}
public String getEname()
{ return ename;
}
}
Test.java
import java.lang.reflect.*;
class Test
{ public static void main(String[] args) throws ClassNotFoundException
{ Class c = Class.forName("Emp");
//To get declared methods
Method[] m = c.getDeclaredMethods();
for (Method mm :m)
{ System.out.println(mm);
}
402 | P a g e
CoreJava Material RATANIT Mr. Ratan
System.out.println(c1.hashCode());
System.out.println(c2.hashCode());
System.out.println(c1==c2);
}
}
G:\>java Test
705927765705927765true
Different types of Class loader:-
1) Bootstrap class loader.
✓ It loads the predefined class present in rt.jar file. rt.jar contains all predefined
classes.(c:/program files/java/jdk/jre/rt.jar)
✓ It is developed in non-java code.
2) Extension class loader.
✓ It loads the .calss fils present in ext folder. This folder present C:\Program
Files\Java\jdk1.8.0_65\jre\lib
✓ It is implemented in java code. The class file name is
sun.misc.Launcher$AppClassLoader@15db9742
3) Application class loader.
✓ It loads the .class files present application level path (Test.class, Emp.class)
✓ It is implemented in java. The class file name is
sun.misc.Launcher$ExtClassLoader@5c647e05
Jar file creation :-G:\>jar -cvf Emp.jar Emp.class [It will create Emp.jar file]
To load this jar file place this jar file ext folder.
class Test
{ public static void main(String[] args)
{ //String is predefined class present in rt.jar
System.out.println(String.class.getClassLoader());
// Application level class present in current directory
System.out.println(Test.class.getClassLoader());
//present in ext folder (in the form of jar)
System.out.println(Emp123.class.getClassLoader());
}
}
G:\>java Test
null
sun.misc.Launcher$AppClassLoader@15db9742
sun.misc.Launcher$ExtClassLoader@5c647e05
403 | P a g e
CoreJava Material RATANIT Mr. Ratan
Heap area:-It is used to store the Objects. Class object is stored in heap memory.
Runtime data area:-this is the memory resource used by the JVM and it is 5 types
Method Area:-It is used to store the class data and method data.
Java stacks:-
➢ Whenever new thread is created for each and every new thread the JVM will creates PC(program
coubter) register and stack.
➢ If a thread executing java method the value of pc register indicates the next instruction to
execute.
➢ Stack will stores method invocations of every thread. The java method invocation includes local
variables and return values and intermediate calculations.
➢ The each and every method entery will be stored in stack. And the stack contains grounp of
enteries and each and every entry stored in one stack frame hence stack is group of stack
frames.
➢ Whenever the method complets the entry is automatically deleted from the stach so whatever
the functionalities declared in method it is applicable only for respective methods.
Java native method stack is used to store the native methods invocations.
404 | P a g e
CoreJava Material RATANIT Mr. Ratan
Execution engine:-
It is used to execute the instructions are available in the methods of loaded classes.
It contains JIT(just in time compiler) and interpreter used to convert byte code instructions into machine
understandable code.
405 | P a g e
CoreJava Material RATANIT Mr. Ratan
Networking(java.net package)
Introduction to networking:-
1) The process of connecting the resources (computers) together to share the data is called
networking.
2) Java.net is package it contains number of classes by using that classes we are able to
connection between the devices (computers) to share the information.
3) Java socket programming provides the facility to share the data between different
computing devices.
4) In the network we are having to components
a. Sender(source) :The person who is sending the data is called sender.
b. Receiver(destination) : The person who is receiving the data is called receiver
In the network one system can acts as a sender as well as receiver.
5) In the networking terminology we have client and server.
Client:- who takes the request & who takes the response is called client.
Server:- The server contains the project
1. It takes the request from the client
2. It identifies the requested resource
3. It process the request
4. It will generate the response to client
Categories of network:-
We are having two types of networks
1) Per-to-peer network.
2) Client-server network.
Client-server:- In the client server architecture always client system acts as a client and server system
acts as a server.
Peer-to-peer:- In the peer to peer client system sometimes behaves as a server, server system
sometimes behaves like a client the roles are not fixed.
Types of networks:-
Intranet:- It is also known as a private network. To share the information in limited area
range(within the organization) then we should go for intranet.
Extranet:- This is extension to the private network means other than the organization , authorized
persons able to access.
Internet:- It is also known as public networks. Where the data maintained in a centralized server
hence we are having more sharability. And we can access the data from anywhere else.
406 | P a g e
CoreJava Material RATANIT Mr. Ratan
7) Socket.
IP Address:-
1) IP Address is a unique identification number given to the computer to identify the computer
uniquely in the network.
2) The IP Address is uniquely assigned to the computer it is should not duplicated.
3) The IP Address range is 0-255.
125.0.4.255 ----> Valid 124.654.5.6 ----> Invalid
4) Each and every website contains its own IP Address we can access the sites through the
names otherwise IP Address.
Site Name :-www.google.com IP Address :-74.125.224.72
Example:-
import java.net.*;
import java.util.*;
class Test
{ public static void main(String[] args) throws Exception
{ Scanner s = new Scanner(System.in);
System.out.println("please enter site name");
String sitename=s.nextLine();
InetAddress in=InetAddress.getByName(sitename);
System.out.println("the ip address is:"+in);
}
}
G:\ratan>java Test
please enter site name
www.google.com
the ip address is:www.google.com/216.58.199.196
G:\ratan>java Test
please enter site name
aaa
Exception in thread "main" java.net.UnknownHostException: aaa
Protocol:-
The protocol is a set of rules fallowed in communication.
✓ TCP(Transmission Control Protocol)(connection oriented protocol)
✓ UDP (User Data Gram Protocol)(connection less protocol)
✓ Telnet
✓ SMTP(Simple Mail Transfer Protocol)
✓ IP (Internet Protocol)
Port number:
The port number is used to identify the different applications uniquely .And it is associated with the ip
address for communication between two applications.
407 | P a g e
CoreJava Material RATANIT Mr. Ratan
Connection Oriented:-
a) In this type of communication we are using combination of two protocols TCP,IP.
b) In this communication acknowledgement sent by receiver so it is reliable but slow.
To achieve the fallowing communication the java peoples are provided the fallowing classes.
a. Socket
b. ServerSocket
408 | P a g e
CoreJava Material RATANIT Mr. Ratan
Socket:-
1) Socket is used to create the connection between the client and server.
2) Socket is nothing but a combination of IP Address and port number.
3) The socket is created at client side.
Socket s=new Socket(int IPAddress, int portNumber);
Socket s=new Socket(“125.125.0.5”,123); Server IP Address. Server port number.
Socket s=new Socket(String HostName, int PortNumber); Socket s=new Socket(Sravyasoft,123);
Client.java:-
import java.net.*;
import java.io.*;
class Client
{ public static void main(String[] args)throws Exception
{ //to write the data to server
Socket s=new Socket("localhost",5555);
String str="ratan from client";
OutputStream os=s.getOutputStream();
PrintStream ps=new PrintStream(os);
ps.println(str); //write the data to server
//read the data from server
InputStream is=s.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String str1=br.readLine();
System.out.println(str1);
}
}
Server.java:-
import java.io.*;
import java.net.*;
class Server
{ public static void main(String[] args) throws Exception
{ //To read the data from client
ServerSocket ss=new ServerSocket(5555);
Socket s=ss.accept();
System.out.println("connection is created ");
Thread.sleep(2000);
//Read the data from client
InputStream is=s.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String data=br.readLine();
System.out.println(data);
Thread.sleep(2000);
//write the data to the client
data=data+"this is from server";
OutputStream os=s.getOutputStream();
PrintStream ps=new PrintStream(os);
ps.println(data);
}
}
409 | P a g e
CoreJava Material RATANIT Mr. Ratan
Java.awt package
✓ AWT(Abstract Window Tool kit) is an API to develop GUI , window based applications in java.
✓ AWT components are platform dependent it displays the application according to the view of
operating system.
✓ AWT is a package it will provide very good predefined support to design GUI applications.
✓ Awt is heavy weight because these components are using operating system resources.
✓ By using java.awt package we are able to prepare static components to provide the dynamic nature
to the component use java.awt.event package.(it is a sub package of java.awt).
Window :- Window class creates a top level window. Window does not have borders and menu bar.
Panel : it is a sub class of Container. Panel does not contain title bar, menu bar or border.
Frame : The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.
410 | P a g e
CoreJava Material RATANIT Mr. Ratan
Java.awt.Frame:-
✓ Frame is a container it contains other components like title bar, Button, Text Field...etc.
✓ When we create a Frame class object. Frame will be created automatically with invisible mode, so to
provide the visible nature to the frame use setVisible() method of Frame class.
public void setVisible(boolean b) where b=true visible mode b=false invisible mode.
✓ When we created a frame, the frame is created with initial size 0 pixel heights & 0 pixel width hence
it is not visible.To provide particular size to the Frame use setSize() method.
public void setSize(int width,int height)
✓ To provide title to the frame use,public void setTitle(String Title)
✓ When we create a frame, the default background color of the Frame is white. If you want to provide
particular color to the Frame we have to use the following method.
public void setBackground(color c)
411 | P a g e
CoreJava Material RATANIT Mr. Ratan
Layout Managers:-
When we are trying to add the components into container without using layout manager the
components are overriding hence the last added component is visible on the container instead of all.
To overcome above problem to arrange the components into container in specific manner use
layout manager.
Definitions:-
The layout managers are used to arrange the components in a Frame in particular manner. or
A layout manager is an object that controls the size and the position of components in a container
Different layouts in java,
1) java.awt.FlowLayout
2) java.awt.BorderLayout
3) java.awt.GridLayout
4) java.awt.CardLayout
5) java.awt.GridBagLayout
java.awt.FlowLayout
The FlowLayout is used to arrange the components into row by row format. Once the first row is
filled with components then it is inserted into second row. And it is the default layout of the applet.
412 | P a g e
CoreJava Material RATANIT Mr. Ratan
Java.awt.BorderLayout:-
The BoderLayout is dividing the frame into five areas north,south,east,west,center so we can
arrange the components in these five areas.
To represent these five areas borderlayout is providing the fallowing 5-constans
import java.awt.*;
class MyFrame extends Frame
{ Button b1,b2,b3,b4,b5;
MyFrame()
{ //this keyword is optional because all methods are current class methods only
this.setSize(400,400);
this.setVisible(true);
this.setTitle("BorderLayout");
this.setLayout(new BorderLayout());
b1=new Button("Boys");
b2=new Button("Girls");
b3=new Button("management");
b4=new Button("Teaching Staff");
b5=new Button("non-teaching staff");
this.add("North",b1);
this.add("Center",b2);
this.add("South",b3);
this.add("East",b4);
this.add("West",b5);
}
}
class Demo
{ public static void main(String[] args)
{ MyFrame f=new MyFrame();
}
};
413 | P a g e
CoreJava Material RATANIT Mr. Ratan
f.add(new Button("NORTH"),BorderLayout.NORTH);
f.add(new Button("SOUTH"),BorderLayout.SOUTH);
f.add(new Button("EAST"),BorderLayout.EAST);
f.add(new Button("WEST"),BorderLayout.WEST);
f.add(new Button("CENTER"),BorderLayout.CENTER);
}
}
414 | P a g e
CoreJava Material RATANIT Mr. Ratan
Preparation of components:-
Label: -Label is a constant text which is displayed along with a TextField or TextArea.
Constructor: Label l=new Label();
Label l=new Label(“user name”);
TextField:-TextField is an editable area&it is possible to provide single line of text.Enter Button doesn’t
work on TextField.
To set Text to the textarea : t.setText(“Sravya”);
To get the text form TextArea : String s=t.getText();
Constructors: TextFiled tx=new TextFiled();
TextField tx=new TextField(“ratan”);
f.add(l1);
f.add(tx1);
f.add(l2);
f.add(tx2);
f.add(b);
}
public static void main(String[] args)
{ MyFrame f = new MyFrame();
}
}
415 | P a g e
CoreJava Material RATANIT Mr. Ratan
1. Choice:-List is allows to select multiple items but choice is allow to select single Item.
Choice ch=new Choice();
✓ To add items to the choice :add()
✓ To remove item from the choice based on String :choice.remove(“HYD”);
✓ To remove the item based on the index position :choice.remove(2);
✓ To remove the all elements : ch.removeAll();
✓ To inset the data into the choice based on the position :choice.insert(2,”ratan”);
✓ To get selected item from the choice :String s=ch.getSelectedItem();
✓ To get the selected item index number : int a=ch.getSelectedIndex();
416 | P a g e
CoreJava Material RATANIT Mr. Ratan
3. Checkbox: - The user can select more than one checkbox at a time.
Checkbox cb2=new Checkbox(“MCA”);
Checkbox cb3=new Checkbox(“BSC”,true);
✓ To set a label to the CheckBox explicitly : cb.setLabel(“BSC”);
✓ To get the label of the checkbox :String str=cb.getLabel();
✓ To get state of the CheckBox : Boolean b=ch.getState();
4. RADIO BUTTON:-
✓ AWT does not provide any predefined support to create Radio Buttons directly.
✓ It is possible to create RadioButton by using two classes.
o CheckboxGroup
o Checkbox
step 1:- Create Checkbox group object. CheckboxGroup cg=new CheckboxGroup();
step 2:- pass Checkboxgroup object to the Checkbox class argument.
Checkbox cb1=new Checkbox(“male”,cg,true);
Checkbox cb2=new Checkbox(“female”,cg,false);
✓ To get the status of the RadioButton :String str=Cb.getState();
✓ To get Label of the RadioButton :String str=getLabel().
Example:-
import java.awt.*;
class Test
{ public static void main(String[] args)
{ Frame f=new Frame();
f.setVisible(true); f.setTitle("ratan");
f.setBackground(Color.red); f.setSize(400,500);
f.setLayout(new FlowLayout());
417 | P a g e
CoreJava Material RATANIT Mr. Ratan
2. To make static component into dynamic component we have to add some actions to the Frame.
To attach these actions to the Frame component we need event delegation model.
Event: Event is nothing but a particular action generated on the particular component.
1. When an event generates on the component the component is unable to respond because
component can't listen the event.
2. To make the component listen the event we have to add listeners to the component. Wherever
we are adding listeners to the component the component is able to respond based on the
generated event.
3. java.awt.event package contains listeners and event classes for event handling.
4. The listeners are different from component to component.
A component delegate event to the listener and listener is designates the event to appropriate
method by executing that method only the event is handled. This is called Event Delegation Model.
Delegates
Handling method
component Delegates listeners Delegates
Delegates
Click the button(event is raised)
Handling method
418 | P a g e
CoreJava Material RATANIT Mr. Ratan
419 | P a g e
CoreJava Material RATANIT Mr. Ratan
420 | P a g e
CoreJava Material RATANIT Mr. Ratan
421 | P a g e
CoreJava Material RATANIT Mr. Ratan
422 | P a g e
CoreJava Material RATANIT Mr. Ratan
Example : CardLayout
import java.awt.*;
class MyFrame extends Frame
{ MyFrame()
{ this.setSize(400,400);
this.setVisible(true);
this.setLayout(new CardLayout());
Button b1=new Button("button1");
Button b2=new Button("button2");
Button b3=new Button("button3");
Button b4=new Button("button4");
Button b5=new Button("button5");
this.add("First Card",b1);
this.add("Second Card",b2);
this.add("Thrid Card",b3);
this.add("Fourth Card",b4);
this.add("Fifth Card",b5);
}
}
class Demo
{ public static void main(String[] args)
{ MyFrame f=new MyFrame();
}
};
423 | P a g e
CoreJava Material RATANIT Mr. Ratan
Example :- GRIDLAYOUT
import java.awt.*;
class MyFrame extends Frame
{ MyFrame()
{ this.setVisible(true);
this.setSize(500,500);
this.setTitle("rattaiah");
this.setBackground(Color.red);
this.setLayout(new GridLayout(4,4));
for (int i=0;i<10 ;i++ )
{ Button b=new Button(""+i);
this.add(b);
}
}
};
class Demo
{ public static void main(String[] args)
{ MyFrame f=new MyFrame();
}
};
Example :-ACTIONLISTENER
The below example we are preforming addition and multiplications when we click add & mul
buttons. So whenever we clicking button the button is able to listen the even to do this add the Listener
to button.
The appropriate listener for button is ActionListener.
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame implements ActionListener
{ TextField tx1,tx2,tx3;
Label l1,l2,l3;
Button b1,b2;
int result;
MyFrame()
{ this.setSize(250,400);
this.setVisible(true);
this.setLayout(new FlowLayout());
l1=new Label("First Value :");
l2=new Label("Second Value :");
l3=new Label("Result :");
tx1=new TextField(25);
tx2=new TextField(25);
tx3=new TextField(25);
b1=new Button("add");
b2=new Button("mul");
424 | P a g e
CoreJava Material RATANIT Mr. Ratan
425 | P a g e
CoreJava Material RATANIT Mr. Ratan
b=new Button("login");
b.addActionListener(this);
tx2.setEchoChar('*');
this.setLayout(new FlowLayout());
426 | P a g e
CoreJava Material RATANIT Mr. Ratan
Example :
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame implements ActionListener
{ String label="";
MenuBar mb;
Menu m1,m2,m3;
MenuItem mi1,mi2,mi3;
MyFrame()
{ this.setSize(300,300);
this.setVisible(true);
this.setTitle("myFrame");
this.setBackground(Color.green);
mb=new MenuBar();
this.setMenuBar(mb);
m1=new Menu("new");
m2=new Menu("option");
m3=new Menu("edit");
mb.add(m1);
mb.add(m2);
mb.add(m3);
mi1=new MenuItem("open");
mi2=new MenuItem("save");
mi3=new MenuItem("saveas");
mi1.addActionListener(this);
mi2.addActionListener(this);
mi3.addActionListener(this);
m1.add(mi1); m1.add(mi2); m1.add(mi3);
}
public void actionPerformed(ActionEvent ae)
{ label=ae.getActionCommand();
repaint();
}
public void paint(Graphics g)
{ Font f=new Font("arial",Font.BOLD,25);
g.setFont(f);
g.drawString("Selected item....."+label,50,200);
}
}
class Demo
{ public static void main(String[] args)
{MyFrame f=new MyFrame();
}
};
427 | P a g e
CoreJava Material RATANIT Mr. Ratan
428 | P a g e
CoreJava Material RATANIT Mr. Ratan
c1=new Checkbox("BSC");
c2=new Checkbox("BTECH");
c3=new Checkbox("MCA");
cg=new CheckboxGroup();
c4=new Checkbox("Male",cg,false);
c5=new Checkbox("Female",cg,true);
c1.addItemListener(this);
c2.addItemListener(this);
c3.addItemListener(this);
c4.addItemListener(this);
c5.addItemListener(this);
429 | P a g e
CoreJava Material RATANIT Mr. Ratan
if(c5.getState()==true)
{ gen=c5.getLabel();
}
repaint();
}
public void paint(Graphics g)
{ Font f=new Font("arial",Font.BOLD,20);
g.setFont(f);
this.setForeground(Color.green);
g.drawString("qualification------>"+qual,50,100);
g.drawString("gender-------------->"+gen,50,150);
qual="";
gen="";
}
}
class Demo
{ public static void main(String[] args)
{ myframe f=new myframe();
}
};
Example :-KEYLISTENER INTERFACE
import java.awt.*;
import java.awt.event.*;
class myframe extends Frame
{ myframe()
{ this.setSize(400,400);
this.setVisible(true);
this.setBackground(Color.green);
this.addKeyListener(new keyboardimpl());
}
};
class keyboardimpl implements KeyListener
{ public void keyTyped(KeyEvent e)
{ System.out.println("key typed "+e.getKeyChar());
}
public void keyPressed(KeyEvent e)
{ System.out.println("key pressed "+e.getKeyChar());
}
public void keyReleased(KeyEvent e)
{ System.out.println("key released "+e.getKeyChar());
}
}
class Demo
{ public static void main(String[] args)
{ myframe f=new myframe();
}
};
430 | P a g e
CoreJava Material RATANIT Mr. Ratan
l=new List(3,true);
l.add("c"); l.add("c++"); l.add("java");
l.addItemListener(this);
ch=new Choice();
ch.add("hyd"); ch.add("chenni"); ch.add("Banglore");
ch.addItemListener(this);
431 | P a g e
CoreJava Material RATANIT Mr. Ratan
Example :- AdjustmentListener
import java.awt.*;
import java.awt.event.*;
class myframe extends Frame implements AdjustmentListener
{ Scrollbar sb;
int position;
myframe()
{ this.setSize(400,400);
this.setVisible(true);
this.setLayout(new BorderLayout());
sb=new Scrollbar(Scrollbar.VERTICAL);
this.add("East",sb);
sb.addAdjustmentListener(this);
}
public void adjustmentValueChanged(AdjustmentEvent e)
{ position=sb.getValue();
}
public void paint(Graphics g)
{ g.drawString("position:"+position,100,200);
repaint();
}
}
class scrollbarex
{ public static void main(String[] args)
{ myframe f=new myframe();
}
};
432 | P a g e
CoreJava Material RATANIT Mr. Ratan
SWINGS
1. Sun Micro Systems introduced AWT to prepare GUI applications but awt components not satisfy
the client requirement.
2. An alternative to AWT Netscape Communication Corporation has provided set of GUI
components in the form of IFC(Internet Foundation Class) but IFC also provide less performance
and it is not satisfy the client requirement.
3. In the above context[sun &Netscape] combine and introduced common product to design GUI
applications is called JFS(java foundation classes) then it is renamed as swings.
433 | P a g e
CoreJava Material RATANIT Mr. Ratan
434 | P a g e
CoreJava Material RATANIT Mr. Ratan
Example :-
package swingss;
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class MyFrame extends JFrame{
public MyFrame() {
setVisible(true);
setSize(300, 300);
setTitle("MyFrame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
JLabel label = new JLabel("Hello World:");
JButton button = new JButton("click me");
add(label);
add(button);
}
public static void main(String[] args) {
MyFrame f = new MyFrame();
}
}
Example 2:-
package swingss;
import java.awt.*;
import javax.swing.*;
class Test2 extends JFrame
{ JLabel l1,l2,l3,l4,l5,l6,l7;
JTextField tf;
JPasswordField pf;
JCheckBox cb1,cb2,cb3;
JRadioButton rb1,rb2;
JList l;
JComboBox cb;
JTextArea ta;
JButton b;
Container c;
Test2()
{ setVisible(true);
setSize(150,500);
setTitle("SWING GUI COMPONENTS EXAMPLE");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
getContentPane().setBackground(Color.red);
435 | P a g e
CoreJava Material RATANIT Mr. Ratan
setBackground(Color.green);
l1=new JLabel("User Name");
l2= new JLabel("password");
l3= new JLabel("Qualification");
l4= new JLabel("User Gender");
l5= new JLabel("Technologies");
l6= new JLabel("UserAddress");
l7= new JLabel("comments");
tf=new JTextField(15);
tf.setToolTipText("TextField");
pf=new JPasswordField(15);
pf.setToolTipText("PasswordField");
cb1=new JCheckBox("BSC",false);
cb2=new JCheckBox("MCA",false);
cb3=new JCheckBox("PHD",false);
rb1=new JRadioButton("Male",false);
rb2=new JRadioButton("Female",false);
ButtonGroup bg=new ButtonGroup();
bg.add(rb1); bg.add(rb2);
String[] listitems={"cpp","c","java"};
l=new JList(listitems);
String[] cbitems={"hyd","pune","bangalore"};
cb=new JComboBox(cbitems);
ta=new JTextArea(5,20);
b=new JButton("submit");
add(l1);
add(tf); add(l2); add(pf);
add(l3); add(cb1); add(cb2); add(cb3);
add(l4); add(rb1); add(rb2); add(l5);
add(l); add(l6); add(cb); add(l7);
add(ta); add(b);
}
public static void main(String[] args)
{ Test2 f=new Test2();
}
};
436 | P a g e
CoreJava Material RATANIT Mr. Ratan
Example 3:
package swingss;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
437 | P a g e
CoreJava Material RATANIT Mr. Ratan
Example 4:-
package swingss;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
public class MyFrame2 extends JFrame implements ActionListener {
JRadioButton button1,button2;
JButton button;
public MyFrame2() {
setVisible(true);
setTitle("MyFrame");
setSize(300, 300);
setLayout(new FlowLayout());
438 | P a g e
CoreJava Material RATANIT Mr. Ratan
Example 5:
package swingss;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class MyFrame3 extends JFrame {
public MyFrame3() {
setVisible(true);
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String[][] data={{"101","ratan","10000"},{"102","anu","20000"},{"101","durga","30000"}};
String[] col={"Eid","Ename","Esal"};
JTable jTable = new JTable(data,col);
add(jTable);
Application 6: - JCOLORCHOOSER
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class MyFrame extends JFrame implements ChangeListener
{ JColorChooser cc;
Container c;
MyFrame()
{ this.setVisible(true);
this.setSize(500,500);
this.setTitle("SWING GUI COMPONENTS EXAMPLE");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
439 | P a g e
CoreJava Material RATANIT Mr. Ratan
c=getContentPane();
cc=new JColorChooser();
cc.getSelectionModel().addChangeListener(this);
c.add(cc);
}
public void stateChanged(ChangeEvent c)
{ Color color=cc.getColor();
JFrame f=new JFrame();
f.setSize(400,400);
f.setVisible(true);
f.getContentPane().setBackground(color);
}
}
class Demo
{ public static void main(String[] args)
{ MyFrame f=new MyFrame();
}
};
Application 7: JFILECHOOSER
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class MyFrame extends JFrame implements ActionListener
{ JFileChooser fc;
Container c;
JLabel l;
JTextField tf;
JButton b;
MyFrame()
{ this.setVisible(true);
this.setSize(500,500);
this.setTitle("SWING GUI COMPONENTS EXAMPLE");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c=getContentPane();
l=new JLabel("Select File:");
440 | P a g e
CoreJava Material RATANIT Mr. Ratan
tf=new JTextField(25);
b=new JButton("BROWSE");
this.setLayout(new FlowLayout());
b.addActionListener(this);
c.add(l); c.add(tf); c.add(b);
}
public void actionPerformed(ActionEvent ae)
{ class FileChooserDemo extends JFrame implements ActionListener
{ FileChooserDemo()
{ Container c=getContentPane();
this.setVisible(true);
this.setSize(500,500);
fc=new JFileChooser();
fc.addActionListener(this);
fc.setLayout(new FlowLayout());
c.add(fc);
}
public void actionPerformed(ActionEvent ae)
{ File f=fc.getSelectedFile();
String path=f.getAbsolutePath();
tf.setText(path);
this.setVisible(false);
}
}
new FileChooserDemo();
}
}
class Demo
{ public static void main(String[] args)
{ MyFrame f=new MyFrame();
}
};
441 | P a g e
CoreJava Material RATANIT Mr. Ratan
Java.awt.Applet
✓ The applet is runs on browser window to display the dynamic content on browser window.
✓ The applet does not contains main methods to start the execution but it contains life cycle
methods these methods are automatically called by web browser.
✓ To run the applet in browser window we need to install plugin in.
442 | P a g e
CoreJava Material RATANIT Mr. Ratan
Firstapplet.html
<html>
<body>
<applet code="Test.class" height="300" width="300"/>
</body>
</html>
Execution : appletviewer Firstapplet.html
Running applet:-
It is possible to run the applet in two ways
1) By using html file
Configure the applet in html file then open the html file in browser window.
Click on Firstapplet.html then the applet is displayed on browser window.
443 | P a g e
CoreJava Material RATANIT Mr. Ratan
Application 2:
Test.java:-
import java.awt.*;
import java.applet.*;
public class Test extends Applet
{ String msg="";
public void paint(Graphics g)
{ Font f=new Font("arial",Font.BOLD,20);
g.setFont(f);
g.drawString("Durga Software Solutions "+msg,100,200);
}
public void init()
{ msg=msg+"initialization"+" ";
System.out.println("init()");
}
public void start()
{ msg=msg+"starting"+" ";
System.out.println("start()");
}
public void stop()
{ msg=msg+"stoping";
System.out.println("stop()");
}
public void destroyed()
{ msg=msg+"destroyed";
System.out.println("destroy()");
}
};
Configuration of Applet:-
<html>
<applet code="Test.class" width="500" height="500">
</applet>
</html>
444 | P a g e
CoreJava Material RATANIT Mr. Ratan
Test.java:
import java.awt.*;
import java.applet.*;
public class Test extends Applet {
Image picture;
public void init() {
picture = getImage(getDocumentBase(),"flower.jpg");
}
public void paint(Graphics g) {
g.drawImage(picture, 30,30, this);
}
}
Firstapplet.html
<html>
<body>
<applet code="Test.class" height="300" width="300"></applet>
</body>
</html>
445 | P a g e
CoreJava Material RATANIT Mr. Ratan
446 | P a g e
CoreJava Material RATANIT Mr. Ratan
447 | P a g e
CoreJava Material RATANIT Mr. Ratan
448 | P a g e