JAVA REFERNCE Notes
JAVA REFERNCE Notes
15. Multithreading u n i t 3
Single Threaded model vs multithreaded model
Main Thread vs user Thread
Creation of user defined Thread
Life cycle stages of Thread
Thread naming
Thread priority
Thread synchronization
Inter Thread communication
Hook Thread
Daemon Thread
Difference between wait() notify() naifyAll()
16. Nested classesIntroduction
unit 1
Advantages of nested classes
Nested classes vs inner classes
Normal Inner classes
Method local inner classes
Anonymous inner classes 19. Enumeration u n i t 2
Static nested classes Introduction
Advantages of enumeration
17. Lambda expressions Values() vs Ordinal()
Enum vs enum
18. Annotations Diff between enum vs class
Advantages of annotations
Different annotations working 20. Arrays u n i t 1
@Suppress Warnings Introduction
@Functional Interface Declaration of Arrays
@Deprecated Object data & primitive data.
@Override
21. Collection framework &Generics 24. Reflection machanisum
unit 4(complete) Introduction.
Introduction about Arrays Method, Constructor, Field
collection vs. arrays Gathering information about class.
Collection vs Collections
Key interfaces of Collections 25. Networking
Characteristics of Collection framework classes Introduction
Information about cursors Socket and ServerSocket
Introduction about Map interface URL info
List interface implementation classes Client-Server programming
Set interface implementation classes 26. AWT unit 5
Map interface implementation classes Introduction
Comparable vs comparator Frame class
Sorting mechanisms of Collection objects. Different layouts
Components of
22. INTERNATIONALIZATION (I18N) AWT(TextField,RadioButton,Che
Design application to support ckbox….etc)
dif country languages Event Handling or Event
Local class delegation Model
ResourceBundle Different types of Listeners
Date in different formats 27. Swings u n i t 5
Info about properties file Awt vs. swings
Advantages of swings
23. JVM uni1 Different components of
architectureWhat is JVM Swings(TextField ,Checkbox.etc)
Structure of the JVM
Components of JVM Event handling in Swings
28. Applet in java Unit 5
JAVA introduction:
Author : James Gosling
Your Teacher : Mr.K. Trishaank
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 rishisoft.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.
java multi-paradigm:
C-language is procedure-oriented language deals with functions.
java-language is object-oriented programming langauge.
from java-8 version onwards java is functional programming (lambda expression).
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
in above exampe we are using
using printf predefined using cout predefined
function that is present in two classes(String,System) these
function that is present in
stdio.h header file hence classes are present in java.lang
stdio.h header file hence
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()
JAVA Features: (Buzz words)
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
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.
Important overview of technologies & frameworks& servers & database:
Types of java applications:
1. Standalone applications: OOPJAVA
It is also known as window-based applications or desktop applications.
This type of applications is specific to system, like media player, antivirus …etc
By using AWT & Swings we are developing User interface in these types of applications.
This type of application does not require client-server architecture.
These application does not required internet.
In editor everything we have to write code. Where as in IDE most of the code generated.
Auto import : Classes are automatically imported.
Auto compiled
exception handling code generated
setter & getters methods are generated.
constructor auto generated .... etc
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).
Note: JDK internally contains JRE :: JRE internally contains JVM :: JVM used to execute the code.
Right click on mycomputer ---> properties ---> advanced system settings ---> environment var----> user
varaibles --- > click on new
variable name : path
varaible value : C:\Program Files\Java\jdk-15.0.2\bin
ok -- ok -- ok
Once the path setting is completed check the version, open the command pompt check the version.
C:\Users\TRISH>java -version
java version "15 0.2" 2021-01-19
Steps to Design a First Application:
Step-1: Write the application.
Step-2: Save the application.
Step-3: Compilation Process.
Step-4: Execution process.
java language object-oriented programming language deals with classes & object.
case 1: Invalid : inside the class directly writing the business logics are not possible.
class Test
{ System.out.println("Good mornng Trish sir...");
}
case 2: valid : inside the class, declare the method in that method write the logics.
class Test
{ public static void main(String[] args)
{ System.out.println("Good morning trish sir ..... ");
}
}
ex: Open editplus --->file -->new --->click on java (it display java application)
import java.lang.System;
import java.lang.String;
class Test
{ public static void main(String[] args)
{ System.out.println("Trish world");
}
}
class A{
}
class B{
}
Note: The source file is allows to declare 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)
|-->javabytrish (Any folder)
|-->Trish.java (Your file name)
To compile the application Goto the file location, in address bar just type "cmd" click on enter.
then command prompt is open to that location.
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 file to .class file.
Note: Compiler generates .class files based on number of classes present in source file.
Step-4: Execution process. Run /execute the java application by using java command.
Execute the application using java command
a. JVM loads .class file byte code into memory. (Translation of byte code to machine code)
b. After loading the class JVM calls main mehthod to start the execution.
E:\javabytrish>javac Trish.java
E:\javabytrish>java Test
Good Morning Trish sir.....
E:\javabytrish>java A
Error: Main method not found in class A, please define the main method as:
E:\javabytrish>java B
Error: Main method not found in class B, please define the main method as:
E:\javabytrish>java C
Error: Could not find or load main class C
Caused by: java.lang.ClassNotFoundException: C
The java predefined support in the form of packages,The java contains 14-packages,
ex: java.lang, java.io, java.util, java.beans, java.awt, java.time. etc
Note: The default package in java is "java.lang" so no need to import java.lang package classes.
Java keywords :( 50)
Flow-Control : if, else, switch, case, default, break, for, while, do, continue 10
Data Types : byte, short, int, long, float, double, char, Boolean 8
source-file : class, extends, interface, implements, package, import 6
Exception handling : try, catch, finally, throw, throws 5
Object-level : new, this, super, instanceof 4
method-level : void, return 2
1.5 version : enum, assert 2
Unused keywords : goto, const 2
Modifiers : public, private, protected, abstract, final, static, strictfp,
native, transient, Volatile, synchronized 11
Reserved words (53) : Keywords (50) + constants (3) = Reserved Words (53)
Package elements:
Java predefined support in the form of packages,
The packages contians 6-elements,
i. classes
ii. interfaces
iii. enums
iv. annotations
v. exceptions
vi. errors
Class elements:
The class contains 4-elements,
class Test
{ varaibles
methods
constructors
blocks
}
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.
The below code compiled & executed but it is not recommanded because the class-name starts with
lower case.
class test
{ public static void main(String[] args)
{ System.out.println("Trish world Good morning...");
}
}
E:\javabytrish>javac Test.java
E:\javabytrish>java test Trish
world Good morning...
Escape Sequences Characters:
A character preceded by a backslash (\) is an escape sequence and has special meaning to the
compiler. We can apply escape sequence characters only on string data.
class Test
{ public static void main(String[] args)
{ System.out.println("hi trish sir");
System.out.println("hi\t\t trish\t\tsir");
System.out.println("hi\ntrish\nsir");
System.out.println("hi\btrish\bsir");
}
}
class Test
{ public static void main(String[] args)
{ System.out.println("trish");
System.out.println("3sk");
System.out.print("rishi");
System.out.print("likitha");
}
}
E:\>java Test
trish
3sk rishi
likitha
Java main class:
The class contains main method is called main class.
The source is allowing to declare more than one main class, but it is not recommanded because
at runtime it is possible to execute only one class.
class Test
{ public static void main(String[] args)
{ System.out.println("Test class");
}
}
class A
{ public static void main(String[] args)
{ System.out.println("A class");
}
}
class B
{ public static void main(String[] args)
{ System.out.println("B class");
}
}
E:\>javac Test.java
E:\>java Test
Test class
E:\>java A
A class
E:\>java B
B class
Observation:
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).
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 ("vivek");
}
}
Tokens are---------class,test,{,”,[ ................... etc
Observation:
Inside the source file possible to declare more than one class.
Inside the source file possible to declare more than one main class.
Inside the source file possible to declare only one public class.
compiler is a translator it is translating .java file to .class
Whereas JVM is also a translator it is translating .class file to machine code.
Compiler understandable file format is .java file
But JVM understandable file format is.class file.
The .java file contains high level language (English).
But .class file contains byte code instructions it is a platform independent code.
Java is a platform independent language but JVM is platform dependent.
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.
Except Boolean and char remaining all data types consider as a signed data types because we can
represent both +ve & -ve values.
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="trish";
System.out.println(ename); //trish
String str;
System.out.println(str); //null
ex-1: In java the decimal values are by default double values hence to represent float value use f
constant or perform type casting.
float f =10.5f; //using f constant (valid)
float f =(float)10.5; //using type casting (valid)
class Test
{ public static void main(String[] args)
{ float f=10.5f;
System.out.println(f);
double d=20.5;
System.out.println(d);
}
}
ex-2: In java the numaric data is by default int type, so to represent the long value use l or L.
class Test
{ public static void main(String[] args)
{ long cardNumber = 7898787645678970l;
System.out.println(cardNumber);
}
}
ex-3: 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
Java identifiers:
Any name in java like method-name variable-name class-name... is called identifier.
Identifier contains (a-z , A-Z , 0-9 , _ , $) but not start with number & not allowed special characters.
2. Java identifiers are case sensitive. The below two declarations are different & valid.
class Test
{ int a=10;
Int A=20;
}
5. There is no length limit for identifiers but it 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;
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_;
v. it is not possible to take the uderscores before & after the representation.
int a = 0B_00110
int a = _0B00110
int a = _0B_00110
Number system in java:
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)
{ 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));
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");
}
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
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.
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();
}
}
else if: To take more than two options
syntax:
if (condition)
{ st(s)
}
else if (condition)
{ st(s)
}
else if (condition)
{ st(s)
}
else
{ st(s)
}
case-1:
class Test
{ public static void main(String[] args)
{ int a = 10;
if (a==10)
{ System.out.println("Bhagath still alive in our hearts");
}
else if (a==20)
{ System.out.println("Subash still alive in our hearts");
}
else if (a==30)
{ System.out.println("sukdev still alive in our hearts");
}
else
{ System.out.println("rajguru still alive in our hearts");
}
}
}
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("Bhagath still alive in our hearts");
}
else if (a==10)
{ System.out.println("Sukdev still alive in our hearts");
}
}
}
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("Bhagath ");
}
else if (a==10)
{ System.out.println("Sukdev still alive in our hearts");
}
else
{ System.out.println("rajguru still alive in our hearts");
}
}
}
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);
}
}
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("trish");
break;
case 20:System.out.println("3sk");
break;
default:System.out.println("rishi");
break;
}
}
}
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");
}
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("trish");
case 10:System.out.println("vivek");
}
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("trish");
case 10*5 :System.out.println("rishi");
}
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("vivek");
}
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("vivek");
}
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("trish");
case 'a' :System.out.println("rishi");
}
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("trish");
case 128:System.out.println("3sk");
}
case 13 : Unicode values : a=97 A=65
int a=97; char ch='d';
switch (a) switch (ch)
{ case 99:System.out.println("trish"); { case 100:System.out.println("trish");
case 'a':System.out.println("3sk"); case 'a':System.out.println("3sk");
} }
1 2 5 4 7
for (initialization ;condition ;increment/decrement )
{
Body; 3 6
}
Case 1:
With out for loop By using for loop
class Test class Test
{ public static void main(String[] args) { public static void main(String[] args)
{ System.out.println("trish"); { for (int i=1;i<=5;i++)
System.out.println("trish"); { System.out.println("trish");
System.out.println("trish"); }
System.out.println("trish"); }
} }
}
Case 1: increament value
class Test
{ public static void main(String[] args)
{ for (int i=0;i<10;i++)
{ System.out.println("Good morning..."+i);
}
System.out.println("******");
for (int i=1;i<=10;i++)
{ System.out.println("Good evening..."+i);
}
System.out.println("******");
for (int i=1;i<=10;i+=3)
{ System.out.println("Good night..."+i);
}
}
}
Conditional part:
Inside for loop conditional part is optional, if we are not providing any condition at the time of
compilation compiler will generate true constant so the loop iterate infinite times.
for (int i=0;;i++)
{ System.out.println("trish");
}
increment/decrement:
case 1 : Inside the for loop increment/decrement part is optional.
for (int i=0;i<10;)
{ System.out.println("rishi");
}
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("vivek");
i++;
}
General cases:
case 1: The below code gives infinite loop because the condition is by default true.
for ( ; ; )
{ System.out.println("trish world...");
}
case 2: in below example we delcare the variable inside the loop, so it is local to for loop we can not
access outside of the loop. error: cannot find symbol
class Test
{ public static void main(String[] args)
{ for (int i=1;i<=10;i++)
{ System.out.println("trish world .... ");
}
System.out.println(i);
}
}
case 3: To access the outside the the for loop use below code.
class Test
{ public static void main(String[] args)
{ int i;
for (i=1;i<=10;i++)
{ System.out.println("ram world");
}
System.out.println(i);
}
}
Break vs. Continue:
break : is used to stop the loop execution
continue : is used to skip the iteration.
Case 1:
class Test
{ public static void main(String[] args)
{ for (int i=1;i<=10;i++)
{ if (i==5)
{ break;
}
System.out.println(i);
}
System.out.println("**********");
class Test
{ public static void main(String[] args)
{ if (true)
{ System.out.println("Trish");
break;
System.out.println("Trish");
}
}
}
error: break outside switch or loop
Unreachable Code:
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.
syntax:
for (datatype temp_var : iterate_data)
{ System.out.println(temp_var);
}
ex:
class Test
{ public static void main(String[] args)
{ int[] a = {10,20,30,40};
System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);
System.out.println(a[3]);
for (int x : a)
{ System.out.println(x);
}
String[] s = {"trish","rishi","vivek"}
for (String str : s)
{ System.out.println(str);
}
}
}
Syntax: do
{ Logics
} while(Boolean-condition);
Case 1:
class Test
{ public static void main(String[] args)
{ do
{ System.out.println("Good Morning");
}while (20<10);
}
}
Case 2:
class Test
public static void main(String[] args)
{ int i=0;
do
{ System.out.println("trish");
i++;
}while (i<10);
}
}
Case 3:
class Test
{ public static void main(String[] args)
{ do
{ System.out.println("Good Morning");
}while (false);
System.out.println("Good Evening");
}
}
Flow control statement interview Questions
*********** ****************
Java class concept
Java Variables:
Variables are used to store the constant values by using these values we are achieving project
requirements.
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);
}
}
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
}
Instance variables (non-static variables):
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.
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);
}
}
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(“trish”+”aank”); //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);
}
}
Static variables (class variables):
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.
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);
class Test
{ static int x=100; //static variable
public static void main(String[] args)
{
System.out.println(Test.a); //1-way(By using class name)
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
}
}
Variables vs. default values:
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);
}
}
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.
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);
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.
Introduction:
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.
case 1: Invalid: Inside the class, it is not possible to write the business logics directly.
class Test
{ int a = 10;
int b = 20;
System.out.println(a+b);
}
case 2: valid: inside the class write the logics with in the methods.
class Test
{ int a=10;
int b=20;
void add(){
System.out.println(a+b);
}
}
Inside the class it is possible to declare ‘n’ number of instance &static methods based on the
developer requirement.
Whether it is an instance method or static method the methods are used to provide business logics of
the application.
Instance method: Access the instance method using object-name.
void add()
{ body : logics here : instance area
}
Method Syntax:
//static methods
static void courseInfo(String name,long mobile,String courseName)
{ if (courseName.equals("java"))
{ System.out.println("hi "+name+" java by Mr.Trish Fee $5000");
}
else if (courseName.equals("python"))
{ System.out.println("hi "+name+" Python by Mr.Trish Fee $5000");
}
else
{ System.out.println("hi "+name+" The course is not available........ ");
}
}
static void disp(int a,char ch,boolean b,double d)
{ System.out.println(a+" "+ch+" "+b+" "+d);
}
}
class TestClient
{ public static void main(String[] args)
{ Services s = new Services();
s.wish();
s.add(10,20);
Services.courseInfo("savithri",9000160099L,"java"
);Services.disp(10,'a',true,10.5);
}
}
Case 2: 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(int a)
{ System.out.println("m1 method");
}
void m1(int b)
{ System.out.println("m1 method");
}
}
error: m1() is already defined in Test
Case 4: It is possible to call the same method multiple times by passing different inputs.
class Test
{ static void add(int num1,int num2)
{ System.out.println(num1+num2);
}
public static void main(String[] args)
{ Test.add(10,20);
Test.add(100,200);
Test.add(1000,2000);
}
}
ex-3 : Different ways of passing arguments to method.
import java.util.Scanner;
class Test
{ static void add(int a,int b)
{ System.out.println("Addition of two numbers:"+res);
}
public static void main(String[] args)
{ //1-way : Directly passing the constants
Test.add(10,20);
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-5 :
case 1: local & instance variables are having differnet names.
class Test
{ int i=10,j=20;
void add(int x,int y)
{ System.out.println(x+y);
System.out.println(i+j);
}
public static void main(String[] args)
{ Test t = new Test();
t.add(100,200);
}
}
System.out.println(this.i+this.j);
}
public static void main(String[] args)
{
Test t = new Test();
t.add(100,200);
}
}
If the application contains both instance & local varibles with same names, in this case to represent
the instance variables use object name,And in place of object it is possible to use this keyword.
this keyword represent the current class object.
It is possible to use this keyword only inside the instane area. inside the static area this keyword is
not allowed.
Test.m2(10.5f);
Test.m2(10);
Test.m2('a');
Test.m2((byte)5);
}
}
Ex-8: 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 name 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);
}
}
Ex-9: 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();
}
}
ex 10: Method recursion method is calling itself during execution is called recursion.
class RecursiveMethod
{ static void withoutrecursive(int a)
{ System.out.println("number is : "+a);
}
static void withrecursive(int a)
{ System.out.println("number is : "+a);
if (a==5)
return;
withrecursive(++a);
}
public static void main(String[] args)
{ RecursiveMethod.withoutrecursive(1);
RecursiveMethod.withoutrecursive(2);
RecursiveMethod.withoutrecursive(3);
RecursiveMethod.withoutrecursive(4);
RecursiveMethod.withoutrecursive(5);
RecursiveMethod.withrecursive(1);
}
}
ex-11: Method return type.
class Services
{ double calculateBill(String productName,double cost,int quantity)
{ double bill;
bill = quantity * cost;
return bill;
}
String productOrder(String produtname,String address,int amount)
{ if (address.equals("hyderabad"))
{ return "HYD23854";
}
else if (address.equals("wnp"))
{ return "GUN01347";
}
else
{ return "OTH78434";
}
}
static String login(String username,String password)
{ if (username.equals("trish") && password.equals("3sk"))
{ return "sucsess";
}
else
{ return "fail";
}
}
static boolean status()
{ return true;
}
}
class TestClient
{ public static void main(String[] args)
{ Services s = new Services();
double totalBill = s.calculateBill("pen",12.5,5);
System.out.println("Your total bill. .. "+totalBill);
case 2: 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”.
class Test
{ int disp()
{ System.out.println("Good morning");
}
}
error: missing return statement
case 3: when we declare the return statement without return value then we will get error.
class Test
{ int disp()
{ System.out.println("Good morning");
return ;
}
}
error: incompatible types: missing return value
case 4: After first return the data will be ignored.Inside the method only one return statement is allowed.
class Test
{ int disp()
{ System.out.println("Good morning");
return 10;
return 20;
}
}
error: unreachable statement
System.out.println("*********");
//directly printing the return value
System.out.println("return value..."+Test.disp());
}
}
Ex-13:
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);
}
}
**************Methods Completed***************
CONSTRUCTORS
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.
Rules to declare constructor:
1) Constructor name class name must be same.
2) It is possible to provide parameters to constructors (just like methods).
3) Constructor not allowed explicit return type even void.
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.
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.
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.
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();
}
}
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);
Emp e2 = Test.m2();
System.out.println("m2 method return value="+e2);
}
}
Student s = Test.m2();
System.out.println("Return value="+s);
}
}
Application with nameless object Approach:
class Dog{
}
class Puppy{
}
class Animal{
}
class Student{
}
class Test
{ void m1(Dog d,Puppy p,Animal a)
{ System.out.println("m1 method");
System.out.println(d+" "+p+" "+a);
}
static Student m2()
System.out.println("m2 method");
return new Student();
}
public static void main(String[] args)
{ Test t = new Test();
t.m1(new Dog(),new Puppy(),new Animal());
Student s = Test.m2();
System.out.println("Return value="+s);
}
}
Solution: only one time we are creating object at instance level using multiple times.
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…
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();
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
ex-2:
class Test
{ Test()
{ this(10);
System.out.println("0-arg constructor...");
}
Test(int a)
{ System.out.println("1-arg constructor...");
}
{ System.out.println("instance block...");
}
public static void main(String[] args)
{ new Test();
}
}
a. Instance blocks execution depends on object creation but not constructor execution.
b. In above example two constructors executed but only one object is created so the instance blocks
executed only once.
ex-3: final instance & final static variables.
case 1: it is not possible to make the default values as final constants.
It is possible to initialize the final instance variables either by using instance blocks or by using
constructor but not both.
class Test
{ final int num;
Test()
{ num = 200;
}
public static void main(String[] args)
{ Test t = new Test();
System.out.println(t.num);
}
}
case 2:
class Test
{ int num; // 0 // 100 // 200
Test()
{ num = 200;
}
{ num = 100;
}
public static void main(String[] args)
{ Test t = new Test();
System.out.println(t.num);
}
}
a. Initial value of of num = 0
b. During object creation first instance block will be executed num=100
c. After instance block constructor will be executed num = 200
class Test
{ static final int num;
static
{ num = 100;
}
public static void main(String[] args)
{ System.out.println(Test.num);
}
}
Ex-4: Loading the .class file.
class Demo
{ static
{ System.out.println("Demo class static block...");
}
void wish()
{ System.out.println("Good morning from Demo...");
}
}
class Test
{ public static void main(String[] args)throws ClassNotFoundException
{ //Demo d = new Demo();
//d.wish();
Class.forName("Demo");
}
}
a. when we create the object, the class loaded then the static block executed.
b. Wihtout object creation just to load the class programatically use forName() method it is a
static method of Class.
c. forName() method throws ClassNotFoundException it is a checked exception so must handle
the checked exception using try-catch or throws keyword.
case 1: The below code is valid upto java 1.6 without main method it is possible to execute static blocks.
class StaticBlock{
static{
System.out.println("class without a main method");
System.exit(0);
}
}
case 2: Below code is Invalid from java1.7 To execute the static block inside the class main method is
mandatory.
class StaticBlock{
static{
System.out.println("class without a main method");
System.exit(0);
}
}
Ex-6:
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");
}
int a=m1();
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();
int m1()
{ System.out.println("m1() method called by variable");
return 100;
}
{ System.out.println("instance block");
}
public static void main (String[] args)
{ new Test();
}
}
D:\morn11>java Test
m1() method called by variable
instance block
Ex-7:
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.
**************** *******************
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.
Unary operator:
System.out.println(31>>1);
System.out.println(31>>2);
}
}
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
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);
}
}
Assignment operator :
Dog is a single class but here we created three objects means three different memories are created.
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.
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;
}
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();
}
}
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
}
}
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.
//Movies.java
class Movies
{ int tmov,bmov;
Movies(int tmov,int bmov)
{ this.tmov = tmov;
this.bmov = bmov;
}
}
//Address.java
class Address
{ int dno;
String street;
String state;
Address(int dno,String street,String state)
{ this.dno = dno;
this.street = street;
this.state = state;
}
}
//Hero.java
class Hero
{ String name;
int age;
double height;
Movies mov;
Address addr;
void disp()
{ System.out.println("Hero name..."+name);
System.out.println("Hero Age..."+age);
System.out.println("Hero height..."+height);
System.out.println("Hero movies..."+mov.tmov+" "+mov.bmov);
System.out.println("Hero Address..."+addr.dno+" "+addr.street+" "+addr.state);
}
System.out.println("*************");
new Test().m1();
new Test().m2();
new Test().m3();
Emp e = Test.m2();
System.out.println("Return value. .. "+e);
}
}
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 t1 = new Test1(10,20);
Test2 t2 = new Test2(true,true);
Test3 t3 = new Test3('a','b');
MainTest main1 = new MainTest(t1,t2,t3);
main1.display();
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
}
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.
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();
}
}
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();
}
}
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);
}
}
Super class instance blocks & static blocks :
Instance blocks are executed during object creation: In parent and child relationship first parent
class instance blocks are executed then child class instance blocks are executed.
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
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.
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.
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...).
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.......
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
ex-2: All child classes overriding the getRateOfInterest() method.
class Bank{
int getRateOfInterest(){return 0;}
}
class SBI extends Bank{
int getRateOfInterest(){return 7;}
}
class ICICI extends Bank{
int getRateOfInterest(){return 8;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
class Test{
public static void main(String args[]){
SBI s = new SBI();
ICICI I = new ICICI();
AXIS a = new AXIS();
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
Case 2: valid
class Parent
{ Object mrg(){ return new Animal(); }
}
class Child extends Parent
{ Dog mrg() { return new Dog(); }
}
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(); }
}
Method overriding rule-5: static methods are not possible to override.
class Parent
{ static void m1(){ System.out.println("parent m1()"); }
}
class Child extends Parent
{ static void m1(){ System.out.println("child m1()"); }
public static void main(String[] args)
{ Parent p = new Child();
p.m1();
}
}
Instance methods are bounded with object it is possible to override instance methods in java.
Static methods are bounded with class it is not possible to override static methods in java.
The above example seems to be overriding but it is method hiding concept.
If a subclass defines a static method with the same signature as a static method in the super
class, then the method in the subclass hides the one in the super class.
In method overriding method execution depends on object creation but in method hiding
method execution depends on class-name.
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
{ static void m1(){ System.out.println("parent m1()"); }
}
class Child extends Parent
{ static void m1(){ System.out.println("child m1()"); }
}
Case 3: Invalid
class Parent
{ static void m1(){ System.out.println("parent m1()"); }
}
class Child extends Parent
{ void m1(){ System.out.println("child m1()"); }
} error: m1() in Child cannot override m1() in Parent: overridden method is static
case 4: Invalid
class Parent
{ void m1(){ System.out.println("parent m1()"); }
}
class Child extends Parent
{ static void m1(){ System.out.println("child m1()"); }
} error: m1() in Child cannot override m1() in Parent : overriding method is static
Method overriding rule : 6
In java not possible to override private methods because these methods are specific to class.
class Base
{ private void fun(){ }
}
class Derived extends Base
{ private void fun() {}
}
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.
Case 1: same type exception: Valid Case 3: sub class exception: valid
class Parent class Parent
{ void m1()throws ArithmeticException { void m1()throws Exception
{ {
} }
class Child extends Parent class Child extends Parent
{ void m1()throws ArithmeticException { void m1()throws ArithmeticException
{ {
} }
} }
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("trish"));
t.m1(new Character('a'));
t.m1(null);
}
}
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... trish)
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.
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...trish)
{ System.out.println("hello trish sir this is main method");
}
}
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[] trish)
{ System.out.println(trish.length);
System.out.println(trish[0]);
System.out.println(trish[1]);
System.out.println(trish[0]+trish[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]);
}
}
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.
Arrays : Here must create the String[] object then pass the data.
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();
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
void xxx(){System.out.println("xxx method implementation");} // user specific normal method
}
class Test2 extends Test
{ void m2(){System.out.println("m2 method");}
void yyy(){System.out.println("yyy method implementation");}
}
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;
}
public void setSname(String sname)
{ this.sname=sname;
}
public int getSid()
{ return sid;
}
public String getSname()
{ return sname;
}
};
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 trish.3sk;
class A{
}
class B{
}
Folder structure:
trish
|--> 3sk
| --> 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;
Declaring the different modules.
Company: tcs
project name: bank
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:
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:\trish Test.java
The folder structure is stored in local disk F in trish 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()
{ System.out.println("Test class 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.oopjava;
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.oopjava.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 |-->oopjava
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;
}
class Child extends Parent
{ void m1()
{ System.out.println(a);
}
public static void main(String[] arghs)
{ Child c = new Child();
c.m1();
}
}
error: a has private access in Parent
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.Rishi.*;
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.*;
Rishi.java:
package com.dss;
public class Rishi
{ 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.
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("Trish 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.
A.java: C.java:
package com.dss; package com.dss;
public class A public class C
{ {
} }
B.java: D.java:
package com.dss; package com.dss;
public class B public class D
{ {
} }
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
Rishi.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?
4. Is it possible to declare package statement any statement of the source
file?
5. What is the difference between user’s defined package and predefined
package?
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();
}
abstract class Dev1 implements Bank
{ void deposit()
{ implementation here....
}
}
abstract class Dev2 extends Dev1
{ void withdraw()
{ implementation here.....
}
}
class TestClient
{ public static void main(String[] rgs)
{ Dev3 d = new Dev3();
d.account();
d.loan();
d.deposit();
d.withdraw();
}
}
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
{ must override all interface methods.
}
class MyClass extends abstarctclass
{ Just override the abstarct methods present in abstarct class.
}
class MyClass extends normalclass
{ override required methods.
}
class MyClass extends Adaptorclass
{ override required methods.
}
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.
user defined empty interfaces are not a marker interface.
interface It1
{ }
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 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();
static void m2(){}
static void m3(){}
default void m4(){}
default void m5(){}
}
********* *********
Garbage Collector
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("trish");
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
trish
trish
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;
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();
}
}
********* **************
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="trish";
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'};
String str4=new String(ch1,2,2); // starts from 2 & 2-characters
System.out.println(str4);
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,2); // starts from 3 & 2-characters
System.out.println(str6);
}
}
E:\>java Test
trish
trish
trish at
ABCDEF
DEF
Creating a string without using new operator: Creating a string object by using new operator
When we create String object without using When we create String object by using new
new operator the objects are created in SCP operator the object created in heap area.
(String constant pool) memory.
Heap area
In String constant pool memory just before
object creation it is always checking When we create object in Heap area
previous objects. instead of checking previous objects it
o If the previous objects are not available directly creates objects.
then JVM will create new object.
o If the previous object is available with
the same content then it won’t create Heap memory allows duplicate objects.
new object that reference variable
pointing to existing object.
SCP does not allow duplicate objects.
class Test
{ public static void main(String[] args)
{ String str1 = "trish";
String str2 = "rishi";
String str3 = "trish";
System.out.println(str1==str2);
System.out.println(str1==str3);
System.out.println(str2==str3);
System.out.println("*****");
String s1 = new String("trish");
String s2 = new String("rishi");
String s3 = new String("trish");
System.out.println(s1==s2);
System.out.println(s1==s3);
System.out.println(s2==s3);
}
}
Ex-3: equals() method
equals() method present in object class used for reference comparison it return Boolean value.
If two reference variables are pointing to same object returns true otherwise false.
String is child class of object and it is overriding equals() methods used to perform data comparison.
If two objects’ data 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.
class Test
{ public Test(String string) {
}
public static void main(String[] args)
{ Test t1 = new Test("trish");
Test t2 = new Test("trish");
System.out.println(t1.equals(t2)); // false
System.out.println(str1==str2);
System.out.println(str1==str3);
System.out.println(str2==str3);
System.out.println(str1.equals(str2));
System.out.println(str1.equals(str3));
System.out.println(str2.equals(str3));
}
}
Ex-4: 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... trish)
{
String str1 =
"rajguru"; String str2
= "rishi"; String str3 =
"rajguru";
System.out.println(str1.equals(str2));
System.out.println(str1.equals(str3));
System.out.println(str2.equals(str3));
System.out.println("trish".equals("TRISH"));
System.out.println("trish".equalsIgnoreCase("TRISH"));
System.out.println(str1.compareTo(str2));
System.out.println(str1.compareTo(str3));
System.out.println(str2.compareTo(str1));
System.out.println("trish".compareTo("subash"));
System.out.println("trish".compareTo("TRISH"));
System.out.println("trish".compareToIgnoreCase("TRISH"));
System.out.println("3sk".compareTo("3sktnrtrt"));
System.out.println("3sktnrtrt".compareTo("3sk"));
}
}
System.out.println("**********");
String s2 = "trishit";
System.out.println(s2.substring(2));
System.out.println(s2.substring(2,5));
//System.out.println(s2.substring(3,15)); java.lang.StringIndexOutOfBoundsException
System.out.println("**********");
System.out.println("**********");
String s4 = "trishitat";
System.out.println(s4.indexOf('a'));
System.out.println(s4.indexOf('x'));
System.out.println(s4.lastIndexOf('a'));
System.out.println(s4.lastIndexOf('x'));
System.out.println("**********");
System.out.println("*********");
System.out.println("*******");
System.out.println("*******");
System.out.println("*******");
System.out.println("*****");
int[] a = {10,20,30,40};
System.out.println(a.length); //length variable find length of the array.
System.out.println("trish".length()); //length() method find length of the String.
}
}
System.out.println("\n*******");
String s2 = "ABC";
byte[] b = s2.getBytes();
for(byte bb : b)
{ System.out.println(bb);
}
System.out.println("********");
System.out.println("".isEmpty());
System.out.println("trish".isEmpty());
}
}
ex-6: StringBuffer methods
class Test
{ public static void main(String[] args)
{ StringBuffer sb1 = new StringBuffer("trishit");
System.out.println(sb1.delete(2, 4));
System.out.println(sb1.deleteCharAt(3));
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="trish";
str.concat("soft");
System.out.println(str); //trish
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="trish";
String str1 = str.concat("soft");
System.out.println(str1);
}
}
Observation:
class Test
{ public static void main(String[] args)
{ String str="trish";
str = str.concat("soft");
System.out.println(str); // 3shaank
}
}
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.
Case 3:
class Test
{ public static void main(String... trish)
{
String[] str={"119d","madhapur","hyderabad"};
StringBuffer sb = new StringBuffer();
for (String s:str)
{ sb.append(s+",");
}
String s = sb.toString();
System.out.println(s);
}
}
import java.util.StringTokenizer;
public class Test8{
public static void main(String[] args) {
StringTokenizer st = new StringTokenizer("hi sir class completed");
while(st.hasMoreElements())
{ String s = (String) st.nextElement();
System.out.println(s);
}
*********
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.
Advantages of wrapper classes:
When we wrap the primitive into object format we have fallowing advantages,
1. The Collection framework support only objects data but not primitive data in this case must
convert your primitive data into object data.
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.
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
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="trish";
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("trish".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.
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("vivek");
}
catch(NullPointerException e)
{ System.out.println(10/2);
}
System.out.println("rest of the app");
}
}
E:\vivek>java Test
vivek
rest of the app
class Test
{ public static void main(String[] args)
{ try
{ System.out.println("vivek");
}
System.out.println("rest of the app");
}
}
E:\vivek>javac Test.java
Test.java:4: 'try' without 'catch' or 'finally' or resources
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("trish".charAt(10));
}
catch (ArithmeticException ae)
{ System.out.println("Trishit");
}
catch (StringIndexOutOfBoundsException se)
{ System.out.println("rishisoft");
}
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("trish".charAt(10));
}
catch (Exception e)
{ System.out.println("Trishit="+e);
}
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(“trish”.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
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("trish".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
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);
} }
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
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.
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.
Finally block code is always executed irrespective of try and catch block code. It is used to write
the resource releasing code like,
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
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("trish");
System.exit(0);
}
finally
{ System.out.println("finally block");
}
System.out.println("rest of the code");
}
}
D:\>java Test
Trish
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("trish".charAt(20));
}
finally
{ int[] a={10,20,30};
System.out.println(a[9]);
}
G:\>java Test
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 9
Statement -17
Statement -18
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.
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();
}
}
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();
}
}
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();}
}
}
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
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.
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
Differences between checked Exception & unchecked Exception:-
User checked Exception User un-checked Exception
1. Our normal java class will become 1. Our normal java class will become un-
checked Exception class when extends checked Exception class when extends
Exception class. Exception class.
class InvalidAgeException extends Exception class InvalidAgeException extends RuntimeException
{ //logics here { //logics here
} }
2. Must handle the checked Exceptions by 2. Handling unchecked Exceptions is
using try-catch block or throws optional but it is recommended.
keyword.
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
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
trish
Exception in thread "main" java.util.InputMismatchException
ClassCastException:-
String s = new String("trish");
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:-
static int a=10/0;
ExceptionInInitializerErrorCaused by: java.lang.ArithmeticException: / by zero
// 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("Trish");
}
}
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.
Output stream:-Program uses output stream to write the data to a destination one item at a time.
//creation of directory
File f1 = new File("rishi");
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;
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;
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.
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.
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("trish.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);
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.
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.
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.
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,"trish");
//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
{ }
class Test
{ void serialization() throws Exception
{ Employee e = new Employee(111,"trish");
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:
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
******** ********
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.
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:
class Test
{ public static void main(String[] args) //main thread starts
{ System.out.println("Hello World!"); //main thread executing
} //main thread ended
}
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();
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.
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.
ex-2 : Difference between t.start() and t.run():-
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();
//anonymous inner class with nameless object
new Thread()
{ public void run(){System.out.println("user Thread-1"); }
}.start();
}
}
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.
class MyThread extends Thread
{ public void run()
{ System.out.println("run o-arg method");
}
public void run(int a)
{ System.out.println("run 1-arg method");
}
}
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.
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.
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("trish"); }
}
class MyThread2 extends Thread
{ public void run()
{ A.status("rishi");
}
}
class MyThread3 extends Thread
{ public void run()
{ A.status("any");
}
}
class ThreadDemo
{ public static void main(String[] args)
{ new MyThread1().start();
new MyThread2().start();
new MyThread3().start();
}
}
method is non-synchronized: method is synchronized:-
G:\>java ThreadDemo G:\>java ThreadDemo
hi=rishi hi=trish
hi=trish hi=trish
hi=any hi=trish
hi=rishi hi=any
hi=trish hi=any
hi=any hi=any
hi=trish hi=rishi
hi=rishi hi=rishi
hi=any hi=rishi
ex-14 :- Thread name& id & isAlive
Every Thread in java having name, default name of the main thread is main & default name of
user threads starts from Thread-0.
t1 -->Thread-0
t2 -->Thread-1
t3 -->Thread-2
To set the name use setName() & to get the name use getName(),
Public final String getName()
Public final void setName(String name)
t1.setName("trish");
t2.setName("3sk");
Thread.currentThread().setName(“rishi”);
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.
class MyThread extends Thread
{ public void run()
{ System.out.println("current Thread name = "+Thread.currentThread().getName());
System.out.println("current Thread priority = "+Thread.currentThread().getPriority());
}
};
class ThreadDemo
{ public static void main(String[] args)//main thread started
{ MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();
}
};
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.
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.
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.
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);
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.
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.
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();
}
}
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.
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 3shaank");
}
};
class MyThread1 extends Thread
{ Heroin h;
MyThread1(Heroin h)
{ this.h=h;
}
public void run()
{ h.message("Vivek");
}
};
class MyThread2 extends Thread
{ Heroin h;
MyThread2(Heroin h)
{ this.h=h;
}
public void run()
{ h.message("Trish");
}
};
class ThreadDemo
{ public static void main(String[] args)
{ Heroin h = new Heroin();
MyThread1 t1 = new MyThread1(h);
MyThread2 t2 = new MyThread2(h);
t1.start();
t2.start();
}
};
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();
}
}
}
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);
}
}
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("Trish");
new Thread(tg1,new MyRunnable()).start();
new Thread(tg1,new MyRunnable()).start();
tg1.interrupt();
}
}
Multithreading
****** ******
Nested classes
Declaring the class inside another class is called nested classes it is introduced in the 1.1 version.
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.
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
{ 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... trish)
{ 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.
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.
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());
}
};
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"); }
};
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();
}
}
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)
Nested classes
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}
Argument-list: It can be empty or non-empty as well.
Arrow-token: It is used to link arguments-list and body of expression.
Body: It contains expressions and statements for lambda expression.
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 Trish");}
};
m.morn();
}
};
m.morn("3sk",10);
Example :
interface isTypeOne
{ void hasOne();
}
interface isTypeTwo
{ void hasTwo();
}
class Test
{ void first(isTypeOne o)
{ 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. ... "));
}
};
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:-
It specifies information about annotation. These are present in java.lang.annotation package.
The meta annotations are
o @Retention
o @Target
o @Documented
o @Inherited
o @Repeatable
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
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();
}
Example-1:-
import java.util.*;
class Student
{ @SuppressWarnings("unchecked")
public static void main(String[] args)
{ ArrayList al = new ArrayList();
al.add("trish");
al.add("3sk");
al.add("vivek");
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 { }
xample :
@FunctionalInterface
interface It1
{ void m1();
}
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.
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");
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.
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.
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[];
//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);
}
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.
Test.java
class Test
{ public static void main(String[] args)
{ Object[] a= new Object[6];
a[0]=new Emp(111,"trish");
a[1]=new Integer(10);
a[2]=new Student(1,"3sk");
a[3]=new String(“trish”);
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."},{"trish","trish","trish"}};
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 definitions:
Collection framework provide very good architecture to store and manipulate the group of
objects.
The main objective of collections framework is used to represent the group of objects as a
single entity.
Collection API contains group of classes & interfaces that makes it easier to handle group of
objects.
Arrays vs. Collections:
Both Arrays and Collections are used to represent group of objects as a single
entity but the differences are as shown below.
Limitations of Arrays Advantages of Collections
1) Arrays are used to store homogeneous 1) Collections to store both
data (similar data). homogeneous & heterogeneous data.
2) Arrays store primitive & Object data 2) Collections store only object data.
5) With respect to memory arrays are not 5) With respect to memory collections
are recommended to use.
recommended to use. 6) In performance point of view
6) If you know size in advance arrays are collections will give low performance
recommended to use because it provides compare to arrays.
good performance.
Collection frame work classes are non-synchronized except java 1.0 version classes.
Only java1.0 classes (Vector, Stack, HashTable.... ) methods are synchronized.
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:
public class java.util.ArrayList<E> extends java.util.AbstractList<E>
implements java.util.List<E>,
java.util.RandomAccess,
java.lang.Cloneable,
java.io.Serializable
ArrayList Constructors:
1. ArrayList()
ArrayList objs = new ArrayList();
Constructs an empty list with an initial capacity of ten.
once it will reach max capacity the new capacity
new capacity = old capacity * 3/2+1
2. ArrayList(int initialCapacity)
ArrayList objs = new ArrayList(20);
Constructs an empty list with the specified initial capacity.
primitive data types : byte, short, int, long, float, double, char, boolean
wrapper classes : Byte, Short, Integer, Long, Float, Double, Character, Boolean
Autoboxing : Automatic conversion of primitive to wrapper object is called autoboxing.
ex-1:
package com.tcs;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList objs = new ArrayList();
objs.add(10); objs.add("trish");
objs.add(10);
objs.add(null);
objs.add(10.5);
System.out.println(objs);
}
}
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.
package com.tcs;
import java.util.ArrayList;
public class ArrayListEx2 {
public static void main(String[] args) {
ArrayList objs = new ArrayList();
objs.add(new Emp(111, "trish"));
objs.add(new Student(1, "3sk"));
objs.add(null);
Student s = (Student)objs.get(1);
System.out.println(s.sid+" "+s.sname);
}
}
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(new Emp(111,"trish"));
al.add(new Student(222,"3sk"));
If the collections are not type safe then while reading the data at runtime we have to perform
Type conversion process, but it is not recommanded.
To overcome above problems to provide the type safety to the collections use generics.
ex 3: Application with generics
package com.tcs;
import java.util.ArrayList;
public class ArrayListEx3 {
public static void main(String[] args) {
//Arrays are type safe
int[] a = {10,20,30};
for(int aa : a)
{ System.out.println(aa);
}
Emp e = emps.get(1);
System.out.println(e.eid+" "+e.ename);
}
}
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. So while reading the data at runtime, we have to perform type conversion.
ArrayList al = new ArrayList();
al.add(new Emp(111, "trish"));
al.add(new Student(1, "rishi"));
To overcome above problem to provide the type safety to the collections use generics.
//Here ArrayList can store only String data.
ArrayList<String> al = new Arrraylist<String>();
al.add(“trish”);
al.add(“3sk”);
//Here ArrayList can store only Emp data.
ArrayList<Emp> emps = new ArrayList<Emp>();
emps.add(new Emp(111, "trish"));
emps.add(new Emp(222, "3sk"));
Note-1 : Collections are introduces in java 1.2 without generics & autoboxing.
generics & autoboxing are introduced in java5.
java 5 version onwards the collections are more powerfull.....
Note-2: Arrays are used to store the homogeneous data & collections generic version also used
to store homogeneous data but collections provide more flexibility with respect to the
memory & operations.
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,"trish"));
a2.add(new Student(2,"3sk"));
a2.add(null);
for (Student s : a2)
{ if(s==null) System.out.println(s);
else System.out.println(s.sid+"---"+s.sname);
}
al.add(3, "3sk");
System.out.println(al);
al.remove(2);
al.remove("trish");
System.out.println(al);
al.set(1, "rani");
System.out.println(al);
System.out.println(al.isEmpty());
al.clear();
System.out.println(al.isEmpty());
}
}
Note: If we want to insert or remove the data frequently then Arraylist is not recommanded. Because it
will take more shift operations.
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:
ex-3: Taking input from enduser adding into ArrayList object.
package com.tcs;
import java.util.ArrayList;
import java.util.Scanner;
public class Takinginput {
public static void main(String[] args) {
//Taking Different values from end user store into ArrayList.
Scanner scanner = new Scanner(System.in);
System.out.println("Enter first obj Integer");
int val1 = scanner.nextInt();
System.out.println("Enter second obj Double");
double val2 = scanner.nextDouble();
System.out.println("Enter third obj string");
String val3 = scanner.next();
ArrayList objs = new ArrayList();
objs.add(val1); objs.add(val2); objs.add(val3);
System.out.println("Arraylist Data:"+objs);
//Taking 5 Integer values from end user store into ArrayList
ArrayList<Integer> intobjs = new ArrayList<Integer>();
for(int i=1;i<=5;i++)
{ System.out.println("Enter "+i+" value :");
intobjs.add(scanner.nextInt());
}
System.out.println("ArraYList Data:"+intobjs);
scanner.close();
}
}
Ex-6 Adding One collection data into another collection.
There are two ways to add one collection data into another collection.
a. By using constructor approach : one to one [a1 is added in a2]
b. By using addAll() method : many to one [b1,b2 is added in b3]
To add only one collection data into another collection use constructor approach.
To add more than one collection into single collection use addAll() method.
package com.tcs;
import java.util.ArrayList;
public class ArrayListEx6 {
public static void main(String[] args) {
//Constructor Approach : Adding one collection into another collection : one to one
ArrayList<String> a1 = new ArrayList<String>();
a1.add("trish");
a1.add("3sk");
ArrayList<String> a2 = new ArrayList<String>(a1);
a2.add("rani");
a2.add("usman");
System.out.println(a2);
//addAll() Approach : Adding many Collections into another collection : many to one
ArrayList<Integer> objs1 = new ArrayList<Integer>();
objs1.add(10);
objs1.add(20);
ArrayList<Integer> objs2 = new ArrayList<Integer>();
objs2.add(100);
objs2.add(200);
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.tcs;
import java.util.ArrayList;
import java.util.Collections;
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));
package com.tcs;
import java.util.ArrayList;
public class ArrayListex8 {
public static void main(String[] args) {
ArrayList<Emp> a1 = new ArrayList<Emp>();
a1.add(new Emp(111,"trish"));
a1.add(new Emp(222,"Vivek"));
for(Emp e : a2)
{ System.out.println(e.eid+" "+e.ename);
}
System.out.println("operations are completed ... ");
}
}
Ex-10: conversion process
import java.util.*;
class ArrayListDemo
{ public static void main(String[] args)
{
//Conversion of array to ArrayList by using asList() method
String[] str={"trish","Vivek","aruna"};
ArrayList<String> a1 = new ArrayList<String>(Arrays.asList(str));
a1.add("trish”);
a1.add("3sk");
for (String s: a1)
{ System.out.println(s);
}
Object[] o = a3.toArray();
for (Object oo :o)
{ System.out.println(oo);
}
}
}
Note-1: Arrays are performance good
ArrayList al = new ArrayList(); // initial capacity : 10
once we create the ArrayList with size 10, once it reaches maximum capacity the new Arraylist
memory created with new capacity.After that old data is copied to new memory. The old data is garbage
collected.
Note2:
ArrayList al = new ArrayList(); // valid but not recommanded
List al = new ArrayList(); // valid & recommanded
List al = sahilaja.getObjects();
ex-4:
package com.tcs;
import java.util.ArrayList;
import java.util.List;
class Ramya
{ public ArrayList<String> getObjects()
{ ArrayList<String> data = new ArrayList<String>();
data.add("trish");
data.add("3sk");
return data;
}
}
public class ArrayListEx7 {
public static void main(String[] args) {
Ramya ramya = new Ramya();
//This code will not work if the getObjects() return type changed
ArrayList<String> objs = ramya.getObjects();
System.out.println(objs);
//This code will not work if the getObjects() return type changed
List<String> newobjs = ramya.getObjects();
System.out.println(newobjs);
}
}
Collection framework Cursors:
There are four ways to read the data from collection classes
1. By using for-each loop
2. By using get() method
3. By using cursor
a. Enumeration
b. Iterator
c. ListIterator
4. By using forEach() method.
System.out.println("*******");
System.out.println("*******");
System.out.println("*******");
// Reading the data using forEach() method : using method reference : java 8
objs.forEach(System.out::println);
}
}
Method reference is a short form of lambda expression.
In method reference the variable name decides internally.
@FunctionalInterface
public interface Consumer<T>{
void accept(T t)
}
T = type
ex-2: Assignment
Book : id name author
ex:
//Book.java
package com.tcs;
public class Book {
Integer bid;
String bname;
String bauthor;
public Book(Integer bid, String bname, String bauthor) {
this.bid = bid;
this.bname = bname;
this.bauthor = bauthor;
}
}
Ex:
package com.tcs;
import java.util.ArrayList;
import java.util.ListIterator;
System.out.println("************************");
System.out.println("************************");
System.out.println("***********************");
while(lstr.hasNext())
{ String s = lstr.next();
if(s.equals("naresh"))
lstr.remove();
if(s.equals("3sk"))
lstr.set("vivek");
}
System.out.println(objects);
}
}
when we create the cursor the cursor is created at first location. so, when we add the data using cursor
the data is added at frist location.
ex-3: Reading the data forward & backward direction.
package com.tcs;
import java.util.ArrayList;
import java.util.ListIterator;
System.out.println("*******");
while(lstr.hasPrevious())
{ String str = lstr.previous();
System.out.println(str);
}
}
}
Test.java
package com.tcs;
import java.util.ArrayList;
import java.util.ListIterator;
ArrayList : Methods are non-synchronized : more than one thread can access : not thread safe
Vector : Methods are synchronized : only one thread can access : thread safe.
As of the Java 2 platform v1.2, this class was retrofitted to implement the List interface,
making it a member of the Java Collections Framework. Unlike the new collection
implementations, Vector is synchronized so it is thread-safe. If a thread-safe implementation is
not needed, it is recommended to use ArrayList in place of Vector.
Vector Constructor:
Vector()
Constructs an empty vector so that its internal data array has size 10 and its standard
capacity increment is zero.
Vector(int initialCapacity)
Constructs an empty vector with the specified initial capacity once it reaches maximum
capacity the capacity becomes double.
import java.util.ArrayList;
import java.util.Vector;
System.out.println("********");
System.out.println("********");
System.out.println("********");
ArrayList<String> al = new ArrayList<String>();
al.add("3sk");
Vector<String> v = new Vector<String>(al);
v.add("trish");
System.out.println(v);
}
}
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.*;
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));
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,”trish");
System.out.println("after seting:-"+l);
System.out.println(l.isEmpty());
l.clear();
System.out.println(l.isEmpty());
}
}
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", "trish"));
l.add(new Book(222, "c", "rishi"));
l.add(new Book(333, "cpp", "3sk"));
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.
.
Stack: (legacy class introduced in 1.0 version)
1) It is a child class of vector.
2) Introduce in 1.0 version, it is a legacy class.
3) It is designed for LIFO(last in fist order ).
ex-1 :
import java.util.*;
class Test
{ public static void main(String[] args)
{ Stack<String> s = new Stack<String>();
s.push("trish");
s.push("3sk");
s.push("rishi");
System.out.println(s);
System.out.println(s.size());
System.out.println(s.isEmpty());
s.clear();
System.out.println(s.isEmpty());
}
}
.
System.out.println(stack);
}
}
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("trish");
al.add("3sk");
al.add("Vivek");
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("trish");
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("trish");
al.add(null);
Collections.sort(al);
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.
“trish”.compareTo(“3sk”) ==> +ve ==>change the order
“trish”.compareTo(“trish”) ==> 0 ==>no change
“3sk”.compareTo(“trish”) ==> -ve ==>no change
.
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);
}
}
}
Property
.
zero –o1 equals to o2
negative– o1 is less than
Java.util
o1
Collections.sort(List, Compar)
only For customized sorting
order.
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;
}
}
.
Collections.sort(al,new EidComp());
Iterator<Emp> itr = al.iterator();
while (itr.hasNext())
{ Emp e = itr.next();
System.out.println(e.eid+"---"+e.ename);
}
}
}
Sorting of emp name : Collections.sort(al,new EnameComp());
Sorting of emp id : Collections.sort(al,new EidComp());
Collection data Cloning & serialization process
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);
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, "trish"));
al.add(new Emp(222, "3sk"));
//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.
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
.
7) Methods are non-synchronized.
8) It supports only Iterator cursor to retrieve the data.
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("trish");
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("trish")); //true
System.out.println(h.add("trish")); //false
System.out.println(h.add("trish")); //false
System.out.println(h);
}
}
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);
.
integers.add(10);
integers.add(0);
integers.add(-1);
System.out.println("Original set: " +integers);
// Collections.sort(integers); This throws error since sort method accepts list not collection
List list = new ArrayList(integers);
Collections.sort(list);
System.out.println("Sorted set: "+list);
Collections.sort(list, Collections.reverseOrder());
System.out.println("Reversed set: " +list);
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);
.
}
}
}
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;
.
t.add("3sk");
t.add("rishi");
System.out.println(t);
.
System.out.println(t1);
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);
}
}
Ex-3: constructor-3 example
TreeSet(Comparator<? super E> comparator)
Constructs a new, empty tree set, sorted according to the specified comparator.
package com.dss;
import java.util.Comparator;
import java.util.TreeSet;
.
return -i1.compareTo(i2);
}
}
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);
}
}
}
.
{ @Override
public int compare(Product p1, Product p2) {
return -p1.name.compareTo(p2.name);
}
}
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("trish");
t.add(new StringBuffer("vivek"));
t.add("3sk");
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);
}
}
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]
.
System.out.println("final elements="+t); //20 40
}
}
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("trish");
pq.add("3sk");
.
pq.add("rishi");
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();
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
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, "trish");
h.put(222, "3sk");
h.put(333, "rishi");
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, "trish"),new Student(1, "aaa"));
h.put(new Emp(222, "3sk"),new Student(2, "bbb"));
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,"trish");
LinkedhashMap<Integer,String> h2 = new LinkedHashMap<Integer,String>(h1);
h2.put(222,"3sk");
.
//by using putAll() to add the data
LinkedHashMap<Integer,String> h11 = new LinkedHashMap<Integer,String>();
h1.put(111,"trish");
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.
.
TreeMap(java/util/Map); adding one map data into another map
Observations of TreeMap:
Case1:- TreeMap h = new TreeMap();
h.put(444,"trish");
h.put(222,"3sk");
h.put(111,"aaa");
System.out.println(h);//{111=aaa, 222=3sk, 444=trish}
In treemap when we insert the data that will be printed in sorting order based on key.
.
}
.
//creation of new TreeMap by passing SortedMap data
SortedMap s1 = h.headMap(333);
TreeMap t1 = new TreeMap(s1);
System.out.println(t1);
import java.util.*;
class Test
{ public static void main(String[] args)
{ TreeMap h = new TreeMap();
h.put(111,"trish");
h.put(222,"3sk");
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);
}
}
.
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());
}
}
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),"trish");
h.put(new Integer(10),"3sk");
System.out.println(h);
Java.util.WeakHashMap:-
public class java.util.WeakHashMap extends java.util.AbstractMap
implements java.util.Map
.
public void finalize() { public String toString()
{System.out.println("object destroyed"); { return "A";
} }
}; public void finalize()
class Test {System.out.println("object destroyed");
{ public static void main(String[] args) }
{ HashMap h = new HashMap(); };
A a= new A(); h.put(a,"trish"); class Test
System.out.println(h); { public static void main(String[] args)
a=null; {WeakHashMap h = new WeakHashMap();
System.gc(); A a= new A();
System.out.println(h); h.put(a,"trish");
} System.out.println(h);
} a=null;
E:\>java Test System.gc();
{A=trish} System.out.println(h);
{A=trish} }
}
WeakHashMap E:\>java Test
import java.util.*; {A=trish}
class A {}
object destroyed
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);
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);
.
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
.
37) What is the difference between Enumeration vs Iterator Vs ListIterator?
38) What are the applicable cursors on ArrayList,Vector,LinkedList?
39) List out implementation classes of set interface?
40) What is the difference between HashSet & linkedHashSet?
41) What is the purpose of TreeSet class?
42) What is the difference between Set & List interface?
43) How to perform the sorting of collection data?
44) To perform the sorting what are the conditions?
45) To perform the default sorting it internally uses which method?
46) What is the difference between collection & collections?
47) What is the difference between comparable & comparator?
48) When we will get ClassCastException?
49) When we will get the NullPointerException?
50) In Comparable by using which method we are writing sorting logics?
51) Is it possible to compare two different objects?
52) What is the difference between compreTo() & equals() method?
53) In Comparator by using which method we are writing sorting logics?
54) What is the purpose of Map interface?
55) List out implementation classes of map interface?
56) What do you mean by entry.
57) How to get all values objects , key objets,entry objects?
58) What is the difference between HashMap & LinkedHashMap?
59) How many ways are there to add one map data into another Map?
60) What is the difference between TreeSet and TtreeMap?
61) What is the difference between IdentityHashMap & WeakHashMap?
62) What is the difference between HashTable and Properties file key=value pairs?
63) HashTable null values are allowed or not?
64) What do you mean by properties file and what are the advantages of properties file?
65) By using properties file we can declare different type of data or not?
66) What is the difference between HashTable & HasMap?
67) How to convert non-synchronized version of method into synchronized version method?
********** ***********
.
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;
.
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_trish_TRISH.properties Trish 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_trish_TRISH.properties:-
countryname=Trish
lang= trish
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("trish","TRISH")
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
Trish--Trish
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 trish TRISH
Trish
trish
Application before internationalization:-
import java.util.*;
class Test
{
public static void main(String[] args)
{ System.out.println("hello");
System.out.println("i like you");
System.out.println("i hate you");
}
}
We are decide to print this messages in different languages like Germany, French…..etc then we must
translate the code in different languages by moving the message out of source code to text file it looks
the program need to be internationalized(supporting different languages).
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
??????
? ???? ???
? ??? ?
Conversion of any language to Unicode values:-
Step 1:- download Unicode editor from internet www.higopi.com
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.
.
Syntax:- native2ascii -encoding encoding-name source-file destination-file
D:\>native2ascii -encoding unicode t.txt output.txt
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);
}
}
.
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
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));
}
};
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));
}
};
Internationalization
****** *******
.
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:-
.
Class loader subsystem:-
1. It is used to load the .class file into memory. Read the data from .class file hard disk loading into
2. It verifies the byte code instructions.
3. It allots the memory required for the program.
It perform three activities,
a. Loading
Reading .class file information and storing .calss file binary information in
method area.
The JVM will create the class Class object to access the class binary information.
b. Linking
a. Verification
Byte code verifier will verify whether the generated byte code proper or not. If
the verification fails we will get Verification error.
b. Preparation
JVM will allocate memory for static variables & assign default values but not
original values & original values are assigned in initialization.
c. Resolution
c. Initialization
Load he student class---> create the class obj ---> stored in heap (form of class obj not student object)
.
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);
}
.
Class class object :-
For every loaded .class file only one Class obj is created by JVM eventhough we are using that
class multiple times.
class Test
{ public static void main(String[] args)
{ Emp e1 = new Emp();
Class c1 = e1.getClass();
System.out.println(c1.hashCode());
System.out.println(c2.hashCode());
System.out.println(c1==c2);
}
}
G:\>java Test
705927765705927765true
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
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.
.
Runtime data areas exclusive to each thread.
PcRegister : it store the next instruction to be executed.
Native method interface:-
Native method interface is a program that connects native methods libraries (C header files)
with JVM for executing native methods.
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.
.
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.
.
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:\trish>java Test
please enter site name
www.google.com
the ip address is:www.google.com/216.58.199.196
G:\trish>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.
.
URL(Uniform Resource Locator):-
1) URL is a class present in the java.net package.
2) By using the URL we are accessing some information present in the world wide web.
http://www.3shaank.com:10/Oopjava_trish.asp
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
.
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(3shaank,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="trish 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);
}
}
.
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.
.
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)
.
Example : Displaying text on the screen
To display some textual message on the frame override paint() method.
public void paint(Graphics g)
To set a particular font to the text use Font class present in java.awt package
Font f=new Font(String type,int style,int size);
Font f= new Font("arial",Font.Bold,30);
import java.awt.*;
class MyFrame extends Frame
{ MyFrame()
{ setVisible(true);
setSize(500,500);
setTitle("myframe");
setBackground(Color.red);
}
public static void main(String[] args)
{ MyFrame t = new MyFrame();
}
public void paint(Graphics g)
{ Font f=new Font("arial",Font.ITALIC,25);
g.setFont(f);
g.drawString("hi trish how r u",100,100);
}
}
In above example when we create the MyFrame class object ,jvm will executes MyFrame class
constructor just before this JVM will execute Frame class zero argument constructor.
The Frame class zero argument constructor calling repaint() method & this method will access
predefined Frame class paint() method. But as per the requirement overriding paint() method
will be executed.
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.
.
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();
}
};
.
Example 2: project level reduce the length of the code.
import java.awt.*;
class Test
{ public static void main(String[] args)
{ Frame f = new Frame("BorderLayout");
f.setVisible(true);
f.setSize(300,300);
f.setLayout(new BorderLayout());
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);
}
}
.
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(“Vivek”);
To get the text form TextArea : String s=t.getText();
Constructors: TextFiled tx=new TextFiled();
TextField tx=new TextField(“trish”);
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();
}
}
.
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,”trish”);
To get selected item from the choice :String s=ch.getSelectedItem();
To get the selected item index number : int a=ch.getSelectedIndex();
.
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("trish");
f.setBackground(Color.red); f.setSize(400,500);
f.setLayout(new FlowLayout());
.
Event delegation model:-
1. When we create a component the components visible on the screen but it is not possible to
perform any action on that component because those components are by default static.
Example:Whenever we create a Frame it can be minimized and maximized and resized but it is
not possible to close the Frame even if we click on Frame close Button. Because frame is a static
component so it is not possible to perform actions on the Frame.
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
.
Appropriate Listeners for Components:-
GUI Component Event Name Listner Name Lisener Methods
1. Frame Window Event Window Listener 1.Public Void WindowOpened(WindowEvent e)
2. Public Void WindowActivated(WindowEvent e)
3.Public Void WindowDeactivated(WindowEvent e)
4.Public Void WindowClosing(WindowEvent e)
5.Public Void WindowClosed(WindowEvent e)
6.Public Void WindowIconfield(WindowEvent e)
7.Public Void WindowDeiconified(WindowEvent e)
.
Event handling code:-
It is possible to write the event handling code in fallowing ways
In different class.
zSame class
By using anonymous inner classes.
.
In below example we are providing even handling code in separate class :-
***PROVIDING CLOSING OPTION TO THE FRAME****
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame
{ MyFrame()
{ this.setSize(400,500); //here this keyword is optional because it is a current class
this.setVisible(true);
this.setTitle("myframe");
this.setBackground(Color.green);
this.addWindowListener(new myclassimpl());
}
}
class myclassimpl implements WindowListener
{ public void windowActivated(WindowEvent e)
{ System.out.println("window activated");
}
public void windowDeactivated(WindowEvent e)
{ System.out.println("window deactivated");
}
public void windowIconified(WindowEvent e)
{ System.out.println("window iconified");
}
public void windowDeiconified(WindowEvent e)
{ System.out.println("window deiconified");
}
public void windowClosed(WindowEvent e)
{ System.out.println("window closed");
}
public void windowClosing(WindowEvent e)
{ System.out.println("window closing");
System.exit(0);
}
public void windowOpened(WindowEvent e)
{ System.out.println("window Opened");
}
};
class Demo
{ public static void main(String[] args)
{ MyFrame f=new MyFrame();
}
};
.
**PROVIDING CLOSEING OPTION TO THE FRAME BY USING WINDOWADAPTOR CLASS **
In above example when our implements the windowListener interface then we must
override all (7)the methods of WindowListener interface .but to close the frame we required only
one method that is windowCloseing( ) method.
To overcome above limitation use WindowAdaptor class it contains all empty
implementations of interface methods.
Note : if our class implements WindowListener interface we must override all the methods of
windowListener interface . But if our class extends windowAdaptor class it is possible to override
application required methods.
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame
{ MyFrame()
{ this.setVisible(true);
this.setSize(500,500);
this.addWindowListener(new Listenerimpl());
}
};
class Listenerimpl extends WindowAdapter
{ public void windowClosing(WindowEvent we)
{ System.exit(0);
}
};
class Demo
{ public static void main(String[] args)
{ MyFrame f=new MyFrame();
}
};
Writing event handling code in anonymous inner class:-
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame
{ MyFrame()
{ this.setVisible(true);
this.setSize(500,500);
this.addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent we)
{ System.exit(0);
}
});
}
}
class Demo
{ public static void main(String[] args)
{ MyFrame f=new MyFrame();
}
};
.
Example :- WRITE SOME TEXT INTO THE FRAME
import java.awt.*;
class MyFrame extends Frame
{ MyFrame()
{ this.setVisible(true);
this.setSize(500,500);
this.setBackground(Color.red);
this.setTitle("trish");
}
public void paint(Graphics g)
{ Font f=new Font("arial",Font.BOLD,20);
g.setFont(f);
this.setForeground(Color.green);
g.drawString("HI BTECH ",100,100);
g.drawString("good boys &",200,200);
}
}
class FrameEx
{ public static void main(String[] args)
{ MyFrame f=new MyFrame();
}
};
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();
}
};
.
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");
.
b1.addActionListener(this);// this represent current class object
b2.addActionListener(this);
this.add(l1);
this.add(tx1);
this.add(l2);
this.add(tx2);
this.add(l3);
this.add(tx3);
this.add(b1);
this.add(b2);
}
public void actionPerformed(ActionEvent e)
{ try{
int fval=Integer.parseInt(tx1.getText());
int sval=Integer.parseInt(tx2.getText());
String label=e.getActionCommand();
if (label.equals("add"))
{ result=fval+sval;
}
if (label.equals("mul"))
{ result=fval*sval;
}
tx3.setText(""+result);
}
catch(Exception ee)
{ ee.printStackTrace();
}
}
};
class Demo
{ public static void main(String[] args)
{ MyFrame f=new MyFrame();
}
};
.
Example :LOGIN STATUS
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame implements ActionListener
{ Label l1,l2;
TextField tx1,tx2;
Button b;
String status="";
MyFrame()
{ setVisible(true);
setSize(400,400);
setTitle("girls");
setBackground(Color.red);
l1=new Label("user name:");
l2=new Label("password:");
tx1=new TextField(25);
tx2=new TextField(25);
b=new Button("login");
b.addActionListener(this);
tx2.setEchoChar('*');
this.setLayout(new FlowLayout());
.
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();
}
};
Example :- MOUSELISTENER INTERFACE
import java.awt.*;
import java.awt.event.*;
class myframe extends Frame implements MouseListener
{ String[] msg=new String[5];
myframe()
{ this.setSize(500,500);
this.setVisible(true);
this.addMouseListener(this);
}
public void mouseClicked(MouseEvent e)
{ msg[0]="mouse clicked ..... ("+e.getX()+","+e.getY()+")";
repaint();
}
public void mousePressed(MouseEvent e)
{ msg[1]="mouse pressed. ... ("+e.getX()+","+e.getY()+")";
repaint();
}
public void mouseReleased(MouseEvent e)
{ msg[2]="mouse released. .... ("+e.getX()+","+e.getY()+")";
repaint();
}
public void mouseEntered(MouseEvent e)
{ msg[3]="mouse entered. .... ("+e.getX()+","+e.getY()+")";
repaint();
}
public void mouseExited(MouseEvent e)
{ msg[4]="mouse exited. .... ("+e.getX()+","+e.getY()+")";
repaint();
}
public void paint(Graphics g)
{ int X=50;
int Y=100;
for(int i=0;i<msg.length;i++)
{ if (msg[i]!=null)
{ g.drawString(msg[i],X,Y);
Y=Y+50;
}
}
}
};
class Demo
{ public static void main(String[] args)
{ myframe f=new myframe();
}
};
Example : ITEMLISTENER INTERFACE
import java.awt.*;
import java.awt.event.*;
class myframe extends Frame implements ItemListener
{ String qual="",gen="";
Label l1,l2;
CheckboxGroup cg;
Checkbox c1,c2,c3,c4,c5;
Font f;
myframe()
{ this.setSize(300,400);
this.setVisible(true);
this.setLayout(new FlowLayout());
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);
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();
}
};
Example : CHECK LIST AND CHOICE
import java.awt.*;
import java.awt.event.*;
class myframe extends Frame implements ItemListener
{ Label l1,l2;
List l;
Choice ch;
String[] tech;
String city="";
myframe()
{ this.setSize(300,400);
this.setVisible(true);
this.setLayout(new FlowLayout());
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);
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();
}
};
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.
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);
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();
}
};
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;
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());
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","trish","10000"},{"102","3sk","20000"},{"101","rishi","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);
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:");
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();
}
};
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.
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.
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>