Java Free Book Rel 1 Upto V12
Java Free Book Rel 1 Upto V12
Java Free Book Rel 1 Upto V12
By. Chidambaram.S
Book starts with basic concepts and
covers the features of Java versions
5,6,7,8,9,10,11 and 12
This book is the free copy for learning purpose and you can
share to any one freely without modifying the original content.
[email protected]
The book work is provided “as is". Because of the possibility of human or
mechanical error we make no guarantees or warranties as to the accuracy, adequacy
or completeness of or results to be obtained from using the work, including any
information that can be accessed through the work via hyperlink or otherwise, and
expressly disclaim any warranty, express or implied.
Oracle and Java are registered trademarks of oracle corporation and/or its
affiliates. All other trademarks and logos are the property of their respective
owners,
This book is the free copy for learning purpose and you can share to any one
freely without modifying the original content.
You are agree to above terms and conditions if you continue to read this book.
Table of Contents
Java’s Magic........................................................................................................................................................................ 23
Abstraction ......................................................................................................................................................................... 27
Encapsulation ..................................................................................................................................................................... 28
Polymorphism .................................................................................................................................................................... 30
Inheritance ......................................................................................................................................................................... 33
Constructor ........................................................................................................................................................................ 38
Instance variables ............................................................................................................................................................... 38
Aggregation ........................................................................................................................................................................ 45
Composition ....................................................................................................................................................................... 45
Identifiers ........................................................................................................................................................................... 47
Literals ................................................................................................................................................................................ 47
Comments .......................................................................................................................................................................... 48
if ..................................................................................................................................................................................... 67
if else .............................................................................................................................................................................. 67
if..else if .......................................................................................................................................................................... 68
else if ladder................................................................................................................................................................... 68
Nested if ......................................................................................................................................................................... 69
switch ............................................................................................................................................................................. 70
while(condition) ............................................................................................................................................................. 72
do..while ........................................................................................................................................................................ 72
Array ................................................................................................................................................................................... 80
public ............................................................................................................................................................................. 91
private ............................................................................................................................................................................ 91
default ............................................................................................................................................................................ 91
protected ....................................................................................................................................................................... 91
Object creation for super class and sub classes ........................................................................................................... 106
Allowed casting syntaxes between sub class and superclass ...................................................................................... 106
Chapter 19 - Auto Box and Auto Unbox, Transient, Volatile and instance of ....................................................................... 123
Chapter 21 - Inner Class, A variable can return an object and Factory Method .................................................................. 132
finally............................................................................................................................................................................ 150
throw............................................................................................................................................................................ 150
try catch - with multiple exception in one catch (Added in 1.7) .................................................................................. 154
java.lang.String............................................................................................................................................................. 193
LinkedList.......................................................................................................................................................................... 279
Constructors................................................................................................................................................................. 290
SortedMap........................................................................................................................................................................ 298
Cloning.............................................................................................................................................................................. 373
Multiple invocation example with one Functional Interface type ............................................................................... 580
Usage the variable declared outside can be used in try with resources .......................................................................... 611
JEP 296: Consolidate the JDK Forest into a Single Repository.......................................................................................... 626
JEP 324: Key Agreement with Curve25519 and Curve448 ............................................................................................... 643
JEP 320: Remove the Java EE and CORBA Modules ......................................................................................................... 644
JEP 333: ZGC: A Scalable Low-Latency Garbage Collector (Experimental) ....................................................................... 646
JEP 336: Deprecate the Pack200 Tools and API ............................................................................................................... 647
JEP 346: Promptly Return Unused Committed Memory from G1.................................................................................... 651
What is Java
The learner must learn core Java in depth then he can able to choose any one of
the above field to build the career. This book is the correct place to start
Core Java.
Page 22 of 660
Java Book - Chidambaram.S
Java Standards
Java’s Magic
In C and C++, the source code will be converted by machine code by compiler.
Then the machine code goes to OS at run time to execute the program. The
Page 23 of 660
Java Book - Chidambaram.S
problem is that the windows based machine code will not run under other than
windows OS such as linux, unix. For linux and unix, the compiler will differ
and source code too.
In web based programming, the program should run in any platform without
modifying the source code, Java does it. The diagram of below explains the
Java’s magic
Page 24 of 660
Java Book - Chidambaram.S
Compile Time
Run Time
JRE
Machine Code
JIT Compiler
Byte Code
OS
Page 25 of 660
Java Book - Chidambaram.S
JVM(Java Virtual Machine) is the compiler of Java and it compiles your source
code to byte code(class file). JIT(Just In Time) is the part of JVM converts
needed portion of byte code to machine code with the help of JRE(Java Runtime
Environment)
What is program?
Two Paradigms
Who is being affected - means which object should be affected for the
each statement.
Page 26 of 660
Java Book - Chidambaram.S
Abstraction
Encapsulation
Polymorphism
Inheritance
Abstraction
Abstraction provides the feature without including the background details and
explanations.
Another example is car brake. Applying brake performs the action to slow / stop
the car and user no need to know about how brake internally invokes other parts
of car. The benefit of this system is that the improvements of braking system
won't affect the usage of brake, which means that the drum brake can be
improved to disc without affecting how brake is used by user.
Page 27 of 660
Java Book - Chidambaram.S
Abstraction in Java
In Java using access modifiers like private, we can hide the data or method to
outside world. The visible method can invoke the hidden private method / data,
so we can access the visible metod in turn to access the private member.
Encapsulation
It is the mechanism that binds together code and data. It means change the
state of an object (instance variables) by using behavior of an object
(instance methods).
1. class PrivateDemo {
2. /*
3. * private modifier restricts access "mark" variable directly from otherclas
ses
4. */
5. private int mark;
6. /*
7. * only the "mark" variable can be accessed using getmark() method
8. */
9. public int getMark() {
10. return mark;
11. }
12. /*
Page 28 of 660
Java Book - Chidambaram.S
13. /* only the mark variable can be assigned using setmark(int mark) method.
*/
14. public void setMark(int mark) {
15. this.mark = mark;
16. }
17.
18. public static void main(String args[])
19. {
20. PrivateDemo privateMember = new PrivateDemo();
21. /* with below statement the program will not be compiled
22. system.out.println(privatemember.mark);
23. */
24. /* below is the correct usage .
25. */
26. privateMember.setMark(100);
27. System.out.println("mark="+privateMember.getMark());
28.
29. }
30. }
31.
32. Output
33.
34. mark=100
If setter is not present, there is no way to set the value through other
classes and the same class can only set the value.
If getter is not present, there is no way to read this value through other
classes, and the same class can only read the value for internal usage.
Page 29 of 660
Java Book - Chidambaram.S
Polymorphism
One interface can act vary as per given input. Runtime polymorphism is
implemented when we have “IS-A” relationship between objects.
Types of Polymorphism
Same method names with different parameters in one class can be known as Method
over loading. It is the way to implement compile time polymorphism. Here
compiler will decide what method should be invoked.
class PolymorphismDemo
void m1()
System.out.println("m1");
Page 30 of 660
Java Book - Chidambaram.S
void m1(int x)
polymorphismDemo.m1();
polymorphismDemo.m1(5);
polymorphismDemo.m1(5,10);
class Parent
Page 31 of 660
Java Book - Chidambaram.S
void m1()
System.out.println("m1 of Parent");
void m1()
System.out.println("m1 of Child");
class MainClass
child.m1();
Page 32 of 660
Java Book - Chidambaram.S
Inheritance
Deriving existing technology to the new one without rewriting it and reuse the
same. It is the Process of one object can acquire the properties of another
object. The benefit is that the new technology needs not to concentrate the
code for already available features and it can concentrate to the newly needed
features.
Existing technology can be called as base class or super class, the new
technology can be called as derived class or sub class. In OOPS, the concept of
inheritance provides reusability. The real power of inheritance mechanism is
reusability.
Diagram Explanation
Left box contains the behavior of car and right box contains the state of car.
If you use the break of car1, car2 will not be affected. Recall the meaning of
“Who is being affected”.
The whole OOPS concepts can be understood after understanding the below
diagram.
Page 33 of 660
Java Book - Chidambaram.S
Plan of Car
Car1
Car2
Break Move/Stop
Break Move/Stop
Gear 1/2/3
Gear 1/2/3
Steering Left/Right/Straig
Steering Left/Right/Straig
ht
ht
Page 34 of 660
Java Book - Chidambaram.S
What is Class?
It is a user defined data type and behaves like the built in types.
The entire set of data and code of an object can be made as a user defined data
type, with the help of class.
Structure of class
//constructors
//instance methods
//static methods
Page 35 of 660
Java Book - Chidambaram.S
Example code
1. class A
2. {
3. // instance variables
4. int x,y;
5. //static variables
6. static int p,q;
7. //constructor
8. A()
9. {
10. //code
11. }
12. void get(int x,int y) // instance method
13. {
14. //code
15. }
16. static void getter(int p,int q) //static method
17. {
18. //code
19. }
20. }
Page 36 of 660
Java Book - Chidambaram.S
What is an object?
Object is a runtime memory which has the copy of instance members of the class.
A ob = new A();
In above sentence,
Object creation
A ob; - It is a reference.
ob.get();
Page 37 of 660
Java Book - Chidambaram.S
What is Method?
Syntax
//code
Example
Constructor
Constructor can be used to initialize the instance variables of the class and
perform some tasks when the time of object creation.
Instance variables
Page 38 of 660
Java Book - Chidambaram.S
Each one object will have separate memory for instance variables.
class A
x=a;
y=b;
A ob1=new A();
A ob2=new A();
A ob3=new A();
ob1.assignValues(1,2);
ob2.assignValues(5,200);
ob3.assignValues(10,20);
Page 39 of 660
Java Book - Chidambaram.S
1.
2. class A
3. {
4. int a;
5. A(){}
6. A(int c)
7. {
8. a=c;
9. }
10. void print(int x) // called function // formal parameters
11. {
12. System.out.println(x);
13. System.out.println("a="+a);
14. }
15. public static void main(String arg[])
16. {
17. A ob=new A(100);
18. int x=200;
19. ob.print(x); // caller // Actual parameters.
Page 40 of 660
Java Book - Chidambaram.S
In above program, ob,ob1 are the objects and ob,ob1 will have “a” separately.
Listen, “a” is printed from print() without using object in line no 13.
It means when you create an object or calling the method by using an object,
the object will be passed as implicit parameter to the constructor or method.
It means the method / constructor can use the invoking object with or without
this.
Within instance methods and constructors, the object can be referred by using
“this” keyword. It is optional. The “this” keyword may or may not be used to
access the members of class within same class. But using this keyword is highly
recommended because when the program grows it is useful to differentiate
instance and other variables.
Formal parameters will have memory only when actual sends the value.
Instance Method
The method can be called by using an object only, that object can be known as
invoking object.
Instance method can use instance variables and static variables of the class.
Page 41 of 660
Java Book - Chidambaram.S
class A (1)
{ (2)
{(4)
System.out.println(“Welcome To Java”);(5)
}(6)
}(7)
(1)
The Java program must be within class. Class name must be started with capital
letter and each one word’s first character should be capital letter. Even
though it is not compulsory and it is highly recommonded and good practice.
(2)
(3)
public
static
The main will be called by OS without object means before instantiation. So the
main should be a static method.
Page 42 of 660
Java Book - Chidambaram.S
void
main
Method name
String args[]
Arguments can be passed to main, when you run the program. The types of
parameters should be String. The parameters will be stored in args[]. The name
of variable(args) may be differed.
(4)
(5)
System
System.out
println()
(6)
(7)
Page 43 of 660
Java Book - Chidambaram.S
Page 44 of 660
Java Book - Chidambaram.S
Aggregation
It is the special form of association. Here the two objects will have own
life cycle and can be related. For example, car has driver. Now driver can be
related to many cars and car may have many drivers, which reveals these two
objects loosely coupled.
Composition
Using real life example we can explain this one. Consider below two
sentences.
#1) Ford Figo is the car - Inheritance - Here Ford Figo and car are the
objects.
#2) Car has the engine - Association - Composition - Here car and engine are
the objects; they can't live independently
#3) Car has the driver - Association - Aggregation - Here car and driver are
two objects; they live independently.
Page 45 of 660
Java Book - Chidambaram.S
We have seen two different objects in above sentences and their relationships.
Now let's write java classes to create relationships programatically.
class Car
// other properties
Page 46 of 660
Java Book - Chidambaram.S
White space
Identifiers
Example
int a
class A
void sum()
Literals
Page 47 of 660
Java Book - Chidambaram.S
int x=12_34_56;
Comments
Multiline Comment /* … */
public class A
Page 48 of 660
Java Book - Chidambaram.S
int b=40;
public A()
void mul()
A ob=new A();
Page 49 of 660
Java Book - Chidambaram.S
ob.get();
ob.mul();
ob.sum();
Keywords
2 keywords are reserved but not in use. These keywords are goto, const.
Separator
{} - braces
[] - brackets
() – parentheses
. – dot or period
, - comma
; - semicolon
Page 50 of 660
Java Book - Chidambaram.S
Escape Sequences
\’ Single quote
\” Double quote
\\ Backslash
\r Carriage return
\n Newline
\f Formfeed
\t Tab
\b Backspace
In below output "Wel" is replaced with "all". So the new sentence is allcome to
"java" states that how the printing statement prints double quote symbol "
using \".In the same way \' prins ' and vice versa.
1. import java.io.*;
2. class EscapeSequence
3. {
4. public static void main(String ars[])
5. {
6. System.out.print("\nWelcome");
7. System.out.print("\tto");
8. System.out.print("\rall");
9. System.out.println();
10. System.out.println("\"java\"");
11. }
12. }
13.
Page 51 of 660
Java Book - Chidambaram.S
14. Output
15.
16. allcome to
17. "java"
Page 52 of 660
Java Book - Chidambaram.S
Chapter 6 - Operators
Relational operators check the comparison between two operands and always
returns true or false.
Boolean logical operators check the comparison between two or more relational
expressions.
Some Examples
Types of operators.
Page 53 of 660
Java Book - Chidambaram.S
Bitwise operators
Relational operators
Ternary operators
+ Addition
- Subtraction
* Multiplication
% Modulus
/ Division
+=,-=,*=,%=,/=
Types of Increment
'a' - value will be incremented with 1 once the tasks are completed
'a' - value will be incremented first with 1 then the tasks are completed
Types of Decrement
Post Decrement(a--)
Page 54 of 660
Java Book - Chidambaram.S
Example
Post increment
int a=10;
int b;
Answer b=10,a=11
Pre increment
Answer b=11,a=11
Post decrement
int a=10;
int b;
Answer b=10,a=9
Pre decrement
Answer b=9,a=9
Bitwise Operator
| Bitwise OR
Page 55 of 660
Java Book - Chidambaram.S
~ Bitwise NOT
^ Bitwise XOR
operator
Relational operators
== Equal to
!= Not equal to
Page 56 of 660
Java Book - Chidambaram.S
| Logical or
|| Short circuit or
|= Or assignment
^= XOR assignment
Ternary operator
?: Ternary if..then..else
Operator precedence
() []
++ --
* / %
+ -
== !=
&
Page 57 of 660
Java Book - Chidambaram.S
&&
||
?:
= op=
Note
It can be rewritten as
Logical And
Page 58 of 660
Java Book - Chidambaram.S
Example
class TernaryOp
int a=70,b=40;
System.out.println("str:"+str);
Page 59 of 660
Java Book - Chidambaram.S
Java has 8 primitive data types. Each one primitive type has wrapper class
available from java.lang(will discuss in java.lang package).
Following list provides the primitive types and their wrapper classes.
short(Short)
byte(Byte)
The following table illustrates the data types and their size, ranges.
Page 60 of 660
Java Book - Chidambaram.S
Ex
int x,y,z;
int x=1,y,z=5 ;
char ch=’y’ ;
Note
Usage of uninitialized variables in main() will raise the error “Variable might
not have been initialized”. Those variables declared in main will not have default
values.
The instance variables will have default values even we don’t provide the value.
The following table illustrates data types and their wrapper classes, conversion
methods. (Discussed detailed in java.lang package)
Page 61 of 660
Java Book - Chidambaram.S
char Character -
Note
Difficulties to store range in data types discussed in Type conversion and casting
Static variable
Instance Variables
Variables declared within method can be known as local variable. When run time
invokes the method, the local scope variable has the memory and the memory
destroys after runtime exits from method. Other methods can’t use the local
variables.
Page 62 of 660
Java Book - Chidambaram.S
Example
if (x==5)
int y=10;
S.o.p(y); // error
Page 63 of 660
Java Book - Chidambaram.S
Assigning lower data type value to higher data type value can be known as widening
conversion. Here implicit casting(Automatic type conversion) will be done by java
run time automatically.
Assigning higher data type value to lower data type value can be known as
narrowing conversion. The error will be raised for these statements. Because lower
type can’t have enough memory to accommodate the value from higher type. Here
explicit casting must be needed.
int c=100;
Here RHS (Right Hand Side) data type range is lesser than LHS (Left Hand Side)
data type range. Now automatically conversion will be done by JRE.
Casting
float a=10.5f;
int x=900;
byte y=(byte)x;
Page 64 of 660
Java Book - Chidambaram.S
This is legal. The compile time error will not be raised. But how 900 can be
stored in y. Becuase y is byte type and it can accommodate the range between -128
to 127. The below program illustrates how java handles this one.
Here java first calculates 900%256. The remainder is 132. 132 can’t be stored in
y. Because byte range is -128 to 127. So JRE stores -124 in y. How?
1. class A
2. {
3. public static void main(String args[])
4. {
5. for (int x=256;x<=1000;x++)
6. {
7. byte y=(byte)x;
8. System.out.println("x="+x+"y="+y);
9. }
10. }
11. }
In mixed expressions, lower data type will be converted to higher data type
automatically if LHS is higher data type.
Page 65 of 660
Java Book - Chidambaram.S
Page 66 of 660
Java Book - Chidambaram.S
simple if
if..else
if..else if
else if ladder
nested if
switch
if
if(condition)
//code
if else
if(condition)
//code
else
Page 67 of 660
Java Book - Chidambaram.S
//code
if..else if
if(condition1)
//code
else if(condition2)
//code
else
//code
else if ladder
if(condition1)
//code
Page 68 of 660
Java Book - Chidambaram.S
else if(condition2)
//code
else if(condition3)
//code
else
//code
Nested if
if(condition)
if(condition)
//code
else
//code
Page 69 of 660
Java Book - Chidambaram.S
else
//code
switch
switch(ch)
case 1:
statements;
break;
case 2:
Statements;
break;
case 3:
statements;
break;
Page 70 of 660
Java Book - Chidambaram.S
case 4:
Statements;
break;
default:
Statements;
Page 71 of 660
Java Book - Chidambaram.S
while
do..while
for
for each (added in 1.5)
Nested for loop
Entry control loop
for, while
Exit control loop
do..while
while(condition)
Statements;
do..while
do
Statements;
}while(condition);
for
Type 1
for(initialization;condition;inc/dec part)
Page 72 of 660
Java Book - Chidambaram.S
Type 2
for(initialization;condition;)
inc/dec part;
Type 3
intialization;
for(;condition part;)
inc/dec part;
Type 3 Example
int i=0;
for(;i<5;)
i++;
Type 5
Page 73 of 660
Java Book - Chidambaram.S
for each
for each can be used to retrieve the elements from array or collection.(collection
is discussed in java.util)
In this type of loop we don’t need to specify number of iteration and we can’t
change the original value.
for(variablename:arrayname)
statements;
Example
int a[]={1,2,3,4,5};
System.out.println(a[i]);
a[i]=a[i]+5;
for(int i:a)
Page 74 of 660
Java Book - Chidambaram.S
System.out.println(i);
o/p:
for(onedimensionalarrayname[]:twodimensionalarrayname)
for(variablename:onedimensionalarrayname)
Statements;
Jumping Statements
break
continue
return
Page 75 of 660
Java Book - Chidambaram.S
break
continue
Continue is used to ignore the current iteration and loop will continue with next
iteration.
Return
Page 76 of 660
Java Book - Chidambaram.S
When we start the execution of one program, we can provide the startup values to
the program.
s.o.p(arg[0]);
arg[] is unlimited string array. So the user can provide more than one values.
When we run the program we can give the command line input as like follows.
class CommandLineDemo
System.out.println("args[0]="+args[0]);
System.out.println("args[1]="+args[1]);
Page 77 of 660
Java Book - Chidambaram.S
Interactive input
In command line we can get the values during the time of starting program. But we
need to get the values from user during the runtime.
1. import java.io.*;
2. class A
3. {
4. public static void main(String args[])
5. {
6. try // 1
7. {
8. DataInputStream dis=new DataInputStream(System.in); // 2
9. System.out.println(“Enter the name”);
10. String name=dis.readLine(); // 3
11. System.out.println(“Enter the code”);
12. int code=Integer.parseInt(dis.readLine()); // 3
13. }//try
14. catch(Exception e) // 4
15. {
16. e.printStackTrace(); //5
17. }//catch
18. }//main
19. }//class
Page 78 of 660
Java Book - Chidambaram.S
When we create the object, the constructor will be called. For DataInputStream
constructor we must pass java.io.InputStream object.
in - java.io.InputStream
Simply we can say that, DataInputStream object dis refers InputStream, InputStream
refers console, so reading from dis, simply reading from console.
readLine() always gets the values as String only. We must cast the Strings into
needed types by using parseXxx() of java.lang.Number abstract class.
Page 79 of 660
Java Book - Chidambaram.S
Chapter 12 - Array
Array is a collection of same data type variables under one name. Array can be
available in following types.
Size 5
Lowerbound 0
Upperbound 4
Element mark[0],mark[1],….mark[4]
Subscript 0,1,2,3,4
Array
Type 1
Type 2
Page 80 of 660
Java Book - Chidambaram.S
Type 3
datatype variablename[]={value….};
int n[]={1,2,3,4};
String name[]={“java”,”j2ee”};
char ch[]={‘a’,’b’,’c’};
Type 4
int n[];
n=new int[5];
In type 4 the array can be declared as class scope, then it can be resized within
method at more times.
Type 1
Type 2
datatype variablename[][];
Page 81 of 660
Java Book - Chidambaram.S
variablename=new datatype[rowsize][coulmnsize];
int b[][];
b=new int[2][3];
Type 3
datatype variablename[][]={{values},{values}};
int a[][]={{1,2,3},{1,2,3}};
Type 1
Type 2
int a[][][];
a=new int[2][2][2];
Type 1
Type 2
int a[][][][];
a=new int[2][2][2][3];
Jagged arrays
Two or more dimensional can be declared as jagged arrays to allocate memory at run
time.
Page 82 of 660
Java Book - Chidambaram.S
Ex 1
a[0]=new int[3];
a[1]=new int[10];
Ex 2
a[0]=new int[2][3];
a[1]=new int[3][4];
Assigning arrays
Ex 1
Ex 2
Ex 3
Page 83 of 660
Java Book - Chidambaram.S
Ex 4
import java.io.*;
class ArrayAscendingOrder {
int i = 0, j = 0, n = 0;
try {
//dis.readLine() gets the input from user and returns String, so conversion is added
below.
n = Integer.parseInt(dis.readLine());
Page 84 of 660
Java Book - Chidambaram.S
a[i] = Integer.parseInt(dis.readLine());
a[i] = a[j];
a[j] = temp;
} // if
} // inner for
} // outer
System.out.println("Ascending Order:");
System.out.println(a[i]);
} // try
catch (Exception e) {
e.printStackTrace();
}// main
}// class
Output
Page 85 of 660
Java Book - Chidambaram.S
Ascending Order:
Page 86 of 660
Java Book - Chidambaram.S
1. class A {
2. int x;
3. }
4.
5. class B {
6. A findBigObject(A a1, A a2)// (1)
7. {
8. if (a1.x > a2.x)
9. return a1;
10. else
11. return a2;
12. }
13. }
14.
15. class C {
16. public static void main(String args[]) {
17. A ob1 = new A();
Page 87 of 660
Java Book - Chidambaram.S
In above program (1) has the statements to accept A’s two objects and return
A’s object.
(2) Sends two objects and receive object. The technique is that,
findBigObject() returns ob2 and ob2 will be stored in big. Now big refers the
memory of ob2 and big doesn’t have separate memory.
(3) Here we change the x to 300 of big, it reflects ob2 also. Because ob2 and
big are having same memory. The big refers the same memory of ob2.
Call by value
Formal parameters will have memory when actual sends value to formal.
These memories of formal will be destroyed after run time exits from the called
method or block.
Example
1. class A
2. {
3. void sum(int x,int y) // formal parameters
4. {
5. x=x+5;
Page 88 of 660
Java Book - Chidambaram.S
6. y=y+5;
7. System.out.println("sum");
8. System.out.println(x);//15
9. System.out.println(y);//10
10. }
11. public static void main(String arg[])
12. {
13. A ob1=new A();
14. int x=10;
15. int y=5;
16. ob1.sum(x,y);//actual
17. System.out.println("main");
18. System.out.println(x);//10
19. System.out.println(y);//5
20. }
21. }
22.
23. Output
24.
25. sum
26. 15
27. 10
28. main
29. 10
30. 5
Default Constructor
If one class doesn’t have constructor, run time creates default constructor,
when creates the object.
A ob=new A();
Page 89 of 660
Java Book - Chidambaram.S
Empty Constructor
We can define an empty constructor in our program. It will not have any
argument.
A()
//code
More than one constructor can be created in one class. But arguments must be
differentiated. This can be also known as constructor overloading.
We must pass the values to parameterized constructors when we create the objects.
Page 90 of 660
Java Book - Chidambaram.S
Access Modifier
There are four access modifiers available. They provide scope to class members.
public
private
default
protected
It can be accessed in same package and other package other than other package non
subclass.
There are so many non access modifiers available. Some modifiers are listed below.
Other modifiers are discussed in appropriate places of following chapters.
Page 91 of 660
Java Book - Chidambaram.S
public, default
If you don’t provide the modifier, the class will have default modifier by
default.
Note
Variable
Method
Class
Variable
Syntax
Method
Page 92 of 660
Java Book - Chidambaram.S
Syntax
Class
final class A
Static variable
1. class A
2. {
3. static int a=10; // syntax
4. int b=20;
5. public static void main(String arg[])
Page 93 of 660
Java Book - Chidambaram.S
6. {
7. A ob=new A();
8. System.out.println("ob.a:"+ob.a);//10 //objectname.staticvarname
9. A ob1=new A();
10. System.out.println("ob1.a:"+ob1.a);//10
11. ob.a=100;
12. System.out.println("ob.a:"+ob.a);//100
13. System.out.println("ob1.a:"+ob1.a);//100
14. ob.b=30;
15. System.out.println("ob.b:"+ob.b);//30
16. System.out.println("ob1.b:"+ob1.b);//20
17. }
18. }
19.
20. Output
21.
22. ob.a:10
23. ob1.a:10
24. ob.a:100
25. ob1.a:100
26. ob.b:30
27. ob1.b:20
Above program illustrates “static variables are common for all objects”. But
modification of instance variable affects only the invoking object not other
objects.
Within class the static variable can be used by using just using the variable
name.
Classname.staticvariablename
Page 94 of 660
Java Book - Chidambaram.S
Objectname.staticvariablename
Static variables can be declared in top of all declarations and below of class
name only.
Static method
Example
Static variables cannot be declared within static method and instance method,
because static variables can be declared only in the class scope.
Static method can be called from other methods by using following syntaxes.
Page 95 of 660
Java Book - Chidambaram.S
1. class A
2. {
3. static int a=10;//it is a static variable
4. int b=20;//instance variable
5. static void sum()//static method
6. {
7. //static int c;//Error
8. System.out.println(a);
9. //System.out.println(b);//Error
10. A ob1=new A();
11. System.out.println(ob1.b);
12. }
13. public static void main(String arg[])
14. {
15. sum();
16. A.sum();
17. A ob=new A();
18. ob.sum();
19. }
20. }
21.
22. Output
23.
24. 10
25. 20
26. 10
27. 20
28. 10
29. 20
Page 96 of 660
Java Book - Chidambaram.S
Syntax
static
Statements;
To execute statements before calling main, we can use static block. If static
block and p.s.v.m are placed in same class the static block will be called
automatically before main.
If static block is included without main(), the static block of class will be
called, when you create the first object(not for other objects) of the class
before calling constructor.
Anonymous Object
new A().get();
System.out.println(new A().a);
Arrays of object
Syntax
Page 97 of 660
Java Book - Chidambaram.S
Ex:
A ob[]=new A[10];
Above statement creates 10 references (not objects) ranging from ob[0] to ob[9].
ob[0]=new A();
..... ....
ob[9]=new A();
or
ob[i]=new A();
this keyword
It refers current invoking object. When we call one method by using object, the
invoking object will be avialable as implicit parameter to the method. The
implicit parameter can be referred by using “this” keyword.
Usage of this
this.instancevariablename;
Page 98 of 660
Java Book - Chidambaram.S
this.instancemethodname();
Page 99 of 660
Java Book - Chidambaram.S
Inheritance
The class which gives its properties to another class that class is known as base
class or super class.
The class which gets the properties from another class that class is known as sub
class or derived class.
Types of Inheritance
Single Inheritance
Multilevel Inheritance
Multiple Inheritance (*)
Hierarchical Inheritance
Hybrid Inheritance (*)
Note
Single Inheritance
Multilevel Inheritance
Multiple Inheritance
Hierarchical Inheritance
B C
B C D
Hybrid Inheritance
B C
Because sub class can have two or more parents in multiple inheritance. It raises
ambiguity error. See hybrid inheritance diagram. Consider B,C are having get().
When we invoke get() by using D’s object what get() would be called. In C++ to
over come this situation virtual classes are introduced. In java there is no
virtual classes. Because java developers don’t want to add one child two parent
techniques.
About Multilevel
In this type of inheritance, one class can have one direct super class and so many
indirect super classes.
Example
class A
class B extends A
class C extends B
Benefits of multilevel
It can extend more than one class indirectly. But it must get only one immediate
super class.
It can access the direct, indirect class members without using its object.
super
Usage of super
If sub class and super class are having same variable names we can use this
technique.
Syntax
super.variablename;
We never create the super class object. By using sub class object we access the
super class members. When we create the sub class object, run time first invokes
super class empty constructor or default constructor before calling sub class
constructor.
Then how can we call the parameterized constructor in super class. The answer is
super keyword.
But calling super class constructor should be done from only sub class
constructors
Syntax
super();
super(argument);
If sub class and super class are having same method names we can use this
technique.
Calling super class method by using sub class should be done from sub class
methods.
super.methodname();
super.methodname(argument);
Method overriding
Rewrite the method available from super class in sub class can be known as method
overriding.
After overriding, sub class object calls sub class overridden methods. If you
don’t override the methods in sub class, super class method will be called.
Overriding mechanism should have the same signatures in super and sub classes.
It is the technology of run time polymorphism. Because run time can only decide
about the places of called methods either super class or sub class. Compiler can’t
find the method matching in overriding. It is Dynamic Method Dispatch.
If we define same methods, same variables in super and sub classes, now this
object will access the subclass methods and sub class variables.
A ob1=new B();
This object first calls A’s empty or default constructor and B’s empty or default
constructor.
If we define same method name in super and sub class, now this object will call
sub class method. If the method is not available in sub class, it will call method
from super class.
If we declare same variable name in super and sub class, now this object will
access the super class variable. This object can’t access sub class variable.
B ob1=(B)ob;// error
Because sub class can have super class reference. But super class doesn’t have sub
class reference.
In this way super class object can assign in sub class reference.
Below two statements are illegal. Because sub class object cannot be created from
super class object.
B ob2=(ob2)ob1;
B ob2=new A();
Delegation
1. class A
2. {
3. B ob1=new B();
4. }
5. class B
6. {
7. int x;
8. }
9.
10. class C
11. {
12. public static void main(String ar[])
13. {
14. A a1=new A();
15. System.out.println(a1.ob1.x);
16. }
17. }
18.
19. Output
20.
21. 0
Abstract class
Recall, in java there are two types of classes 1.Concrete class 2.Abstract class.
It can have instance methods and concrete methods. Abstract method means that it
has only method declaration with abstract modifier.
Abstract class may come with only instance methods collection or even only
abstract methods collection.
Abstract class can implement interfaces. In this situation abstract classes need
not to override the methods of interfaces. The sub classes of abstract class must
override all abstract methods in abstract class and its super interface.
Object creation is not possible for abstract class, but object can be created by
using following syntax
1. abstract class A {
2. abstract int sum(int i, int j);
3.
39.
40. 11
41. 30
42. Java
43. I am callMe() of abstractClass
Interface
Abstract Interface
Note
Package
What is package?
To classify the classes we can put into packages for understanding purpose only.
Consider you need different classes with same name “Bank”. It is not possible
to provide name “Bank” to two classes. Create two packages and put one “Bank”
class in one package and another “Bank” class in another package.
The above points are not ultimate purpose of package. Consider you are
developing “vehicle Loan Management” project. In this you are having three
entities.
Vehicle
Loan
Buyer
Now you can create three packages “Vehicle” and keep vehicle related classes
into “vehicle” package and so on.
Because of this, if you need to extend or modify any one concept like vehicle
you can concentrate only about vehicle package, you don’t bother about other
packages.
In java all classes are kept in package. java.io has the classes related to
input and output concepts, java.rmi has the classes related to networking. If java
developers need to add some additional functionalities in network concepts, they
can concentrate only java.rmi and not java.io.
Other No No No Yes(with
package non object)
sub class
Creating Package
Syntax
package packagename;
class classname
Save:
Drive:\packagename\classname.java
Ex:
G:\java\pack1\Pack1A.java
Pack1B.java
Pack1C.java
Pack1Main.java
G:\java\pack2\pack2A1.java
Pack2A2.java
Pack2Main.java
Compile Pack1
G:\java\pack1>javac *.java
G:\java\pack1>set classpath=.;G:\java\
Run Pack1Main.java
G:\java\pack1>java pack1.Pack1Main
Compile Pack2
G:\java\pack2>javac *.java
Run
G:\java\pack2>java pack2.Pack2Main
set classpath
When your class files are not found in current folder, you must provide class
path
set path
When java system files are not found, you must provide set path command.
G:\java\>set path=c:\java\jdk1.6\bin
Batch file
If you need to execute your program by executing many commands like set classpath,
you can use batch file.
When you run batch file, the commands of batch file will be run one by one.
Way1
Create .txt file in any text editor and rename the extenstion to .bat
set path=c:\java\jdk1.6\bin
set classpath=g:\java
java pack2.Pack2Main
Date
Then save the file. Double click on the file can be used to execute batch file.
Importing packages
java.util.*; // 1
java.util.Date; // 2
1st statement imports all classes available inutil package. 2nd statement only
imports the Date class. Typically we prefer 2nd way, because it import whatever
needed class for our program. By importing the classes, we don't need to
specify the package name again and again in all the places of program.
For example if you use java.util.Date class in your program at 50 times, you
must use java.util.Date in all placesif you are not importing. We don't follow
this practice.
Instead of this just you can import the java.util package or java.util.Date
class and you can use Date class name in all places instead of using
java.util.Date
To Access the static methods in one class without referring the class name. We
can use following syntax.
It loads Java API classess, presents in jre/lib/rt.jar. API classes means built
in classes in packages like java.lang, java.util etc. These are classes that
are part of JDK (Java Development Kit).
echo %CLASSPATH%
OR
Whenever JVM needs the class to run, it searches the loaded class. If it is not
found it requests the class loader.
If extension class loader found the class then runtime loads it, else searching
will go the bootstrap class loader.
If bootstrap class loader found the class then runtime loads it otherwise
ClassNotFoundException will be raised.
If your CLASSPATH environment variable was set to a value that is not correct,
or if your startup file or script is setting an incorrect path, then you can
unset CLASSPATH with:
set CLASSPATH=
You can get the link to open the System Properties dialog
In System Variables section Click New if CLASSPATH is not added yet. or click
Edit button to edit the class path
New button provides below dialog and type the variable name and variable value
as below. Click ok
Click OK button. Now the value given in dialog will be appeared as like below
and now we are good in class path setup.
AutoBox
Binding value into one number based primitive type object by using assignment
operation can be known as AutoBox.
Integer ob=10;
Auto unboxing
Auto unboxing means retrieving value from object and stored it in one variable
by using assignment statement.
Example
int x=i;
Transient
Ex:
class A
int b=20;//Encrypted
Now you can encrypt ob1. Now JRE encrypts only b. Because transient variable
‘a’ will not be encrypted.
Volatile modifier
instanceof
instanceof is a keyword. It checks the object type with class type. If you need
to create one method to receive A’s object or B’s object, you can use formal
parameter type as Object. In such time you must check what type of object we
receive. It is done by instanceof keyword.
Syntax
Example
if(ob instanceof A)
//code
//code
When you need to define the class with accepting different parameters
dynamically like previous example with Type Safe, you can use Generic class
concepts. Type Safe means, in previous example get() accepts any type, but
generic method only accepts defined types.
class classname<typename>
Ex:
Ex
By using diamond operator <>, we don't need to mention the type in both as like
below example.
1. class Gen<T>
2. {
3. T ob;
4. Gen(T o)
5. {
6. ob=o;
7. }
8.
9. T getOb()
10. {
11. return ob;
12. }
13. void showType()
14. {
15. System.out.println("Type of T is "+ob.getClass().getName());
16. }
17. }
18. class OneTypeGenDemo
19. {
20. public static void main(String args[])
21. {
22. Gen<Integer> iob=new Gen<Integer>(88);
23. iob.showType();
24.
25. int v=iob.getOb();
26. System.out.println("v="+v);
27.
28. Gen<String> iob1=new Gen<String>("Generics");
29. iob1.showType();
30.
31. String s=iob1.getOb();
32. System.out.println("s="+s);
33. Gen<Integer> iob2;
34. // iob=iob1;
35. iob2=iob;
36. }
37. }
38.
39. Output
40. Type of T is java.lang.Integer
41. v=88
42. Type of T is java.lang.String
43. s=Generics
1. class Two<T,V>
2. {
3. T ob1;
4. V ob2;
5. Two(T ob1,V ob2)
6. {
7. this.ob1=ob1;
8. this.ob2=ob2;
9. }
10.
11. void showTypes()
12. {
13. System.out.println("Type of T is ="+ob1.getClass().getName());
bounded and unbounded wildcards in generics are used to bound any Type.
"? extends T" and "? super T" are bounded wild cards. "?" is unbounded wild
card.
Bounded wild cards can be divided as upper bounded wild card and lower bounded
wild card.
? extends T is the upper bounded wild card where all types should be the super
class of T
? super T is the lower bounded wild card where all types should be the sub
class of T
In below example, we are using java.lang.Number class as the type. So the sub
classes can be added in lower bound and upper bound will raise the compile time
error.
import java.util.*;
public class GenericDemo {
numbersList2.add(new Integer(4));
Inner Class
It is possible to define a class within another class; such classes are known
as nested classes.
The scope of nested class is bounded by the scope of its enclosing class. If
class Y is defined within class X, then Y is known to X and not outside of X. A
nested class can access the members of its enclosing class, how ever the
enclosing class does not have access to the members of the nested class.
X – Enclosing class
Y – Nested class
Example
class X
class Y
static inner classes can use enclosing members by using object only. So this
method will be seldom used.
Non static inner classes can use enclosing members directly without object
including private members.
In program printout various inner class examples explain the complete real time
basis techniques.
1. class Outer
2. {
3. int outer_x=100;
4. void test()
5. {
6. Inner inner=new Inner();
7. inner.display();
8. }
9. class Inner
10. {
11. int inner_y=10;
12. void display()
13. {
14. System.out.println("dispaly : outer_x="+outer_x);
15. System.out.println("dispaly : inner_y="+inner_y);
16. }
17. }//inner
18. }//outer
19.
20. class InnerClassDemo
21. {
22. public static void main(String args[])
23. {
24. Outer outer=new Outer();
25. outer.test();
26. Outer.Inner inner = outer.new Inner();
27. inner.display();
28. System.out.println("dispaly : outer_x="+outer.outer_x);
29. }
30. }
31.
32. Output
33.
34. dispaly : outer_x=100
35. dispaly : inner_y=10
1. class Outer
2. {
3. int x=100;
4. Outer()
5. {
6. System.out.println("I am Outer class Constructor");
7. }
8. static class Inner
9. {
10. int y=200;
11. void sum()
12. {
13. System.out.println("I am sum() of Inner");
14. System.out.println("y="+y);
15. }
16. }//inner
17. void outersum()
18. {
19. System.out.println("I am outer sum() of Outer");
20. System.out.println("x="+x);
21. //System.out.println("y="+y);
22. }
23. }//outer
24.
25. class InnerNewMain2
26. {
27. public static void main(String args[])
28. {
You can also create variable to return the object in your class by using
following syntax.
class B
static A getA;
Factory Method
Those which method can be used to create object, this method can be known as
Factory method.
Example
A ob1=A.getA();
Resource Bundle
To add the internationalization to your program, java.util.ResourceBundle class can be
used.
1. package com.book.resourceprgs;
2.
3. import java.util.Locale;
4. import java.util.ResourceBundle;
5.
6. public class ResourceBundleDemo {
7.
8. public static void main(String[] args) {
9.
10. // en_US
11. System.out.println("Current Locale: " + Locale.getDefault());
12. ResourceBundle resourceBundleEnUS = ResourceBundle.getBundle("reso
urce");
13.
14. // read en_US.properties
15. System.out.println("Username : " + resourceBundleEnUS.getString("u
sername"));
16. System.out.println("Password : " + resourceBundleEnUS.getString("p
assword"));
17.
18. Locale.setDefault(new Locale("fr", "FR"));
19.
20. // read fr_FR.properties
21. System.out.println("Current Locale: " + Locale.getDefault());
22.
23. ResourceBundle resourceBundlefrFR = ResourceBundle.getBundle("reso
urce");
24. System.out.println("Username : " + resourceBundlefrFR.getString("u
sername"));
25. System.out.println("Password : " + resourceBundlefrFR.getString("p
assword"));
26.
27. }
28.
29. }
30.
31. Output
32.
33. Current Locale: en_US
34. Username : Username
35. Password : Password
ListResourceBundle
extends ResourceBundle
ListResourceBundle is the abstract class and its sub class must override the
getContents() with return type of an array, where each item in the array is a
pair of objects.
1.
2. import java.util.ListResourceBundle;
3. import java.util.Locale;
4.
5. class MyResources extends ListResourceBundle {
6. protected Object[][] getContents() {
7. return new Object[][] {
8. { "username", "username-eng" }, { "password", "password-
eng" }
9. };
10. }
11. }
12.
Regular Expressions
Pattern p = Pattern.compile("^[a-z]");
Matcher m = p.matcher("abcd");
/* matches() validates the given string with regular expression and returns
boolean value
*/
boolean b = m.matches();
In password regular expression () defines one group and the characters within
each one group is required().
Exception
All Exception types are the sub classes of java.lang.Throwable. It has two
immediate sub classes, Error and Exception. The immediate sub class of
Exception is RuntimeException. The sub classes of RuntimeException will be
raised at runtime. The sub classes of Error will be raised by runtime like
VirtualMachineErrorNormally you need not to manage these errors in your
program.
Benefits of Exception
By handling exception, only runtime terminates try block and calls catch block.
So that the remaining part will be executed without disturbance.
Key Benefits
Log the exception message to track the message by developer to figuer out
when, where and why this exception, so that we can find out root cause and
the solution.
Make useful tasks such as providing clean message to user about exception
instead of runtime’s exception message.
Types of Exception
Compiler verifies these exceptions about handling in your program. For example,
IOException, CloneNotSupportedException. These exceptions are the direct sub
classes of Exception.
Caught Exception
Uncaught Exception
ArithmeticException
S.o.p(5/0); // Infinity
ArrayIndexOutOfBoundsException
ArrayStoreException
ClassCastException
IllegalArgumentException
Class A
Void sum(int a)
A ob=new A();
IllegalMonitorStateException
Refer in Thread
IllegalStateException
Refer in Thread
IllegalThreadStateException
Refer in Thread
IndexOutOfBoundsException
Refer in util
NegativeArraySizeException
NullPointerException
A ob; // ob is a reference
NumberFormatException
int j=Integer.parseInt(“10”);//correct
SecurityException
StringIndexOutOfBoundsException
String str=”Rama”;
UnSupportedOperationException
ClassNotFoundException
Given class file is not found in given path. Refer in Package concepts
CloneNotSupportedException
IllegalAccessException
InstansitationException
InterruptedException
Refer Thread
NoSuchFieldException
NoSuchMethodException
try
catch
finally
throw
throws
try .. catch
Exception blocks can be constituted by using try block. It means one method can
have one or more try blocks.
Each one try block should have one catch and more than one catch is also allowed.
If any exception is raised at runtime, JRE created Exception object (For example,
if we add the calculation like 5/0 in program, JRE creates an object for
java.lang.ArithmeticException) and the object will be handed over to appropriate
catch block.
If catch block is not found, it will be thrown to console and program execution
continues after the try block.
syntax
try{}
catch(Exception e){}
finally
This block will be executed all time either exception is raised or not. If you
need to do some tasks such as closing database connections, closing opened files,
the tasks can be written within finally block.
Syntax
try{}
catch(Exception e){}
finally{}
throw
Syntax
throw ThrowableObject;
Example
throws
It tells compiler, the called function doesn’t have try catch to handle exception
and if exception is raised go to caller to search catch blocks.
Syntax
{
}
try
m1();
m2();
catch(Exception e)
Nested Try
outer try
try
try
catch(Exception e){}
catch(Exception e){//2.3}
catch(Exception e){//1.3}
Above example illustrates how try can be nested. More number of nested is allowed.
If 1.1 portion raises exception all inner try and 1.2 also terminated and 1.3
catch block will be called.
If 1.2 portion raises exception, control exits from try and 1.3 catch block calls.
If 2.1 portion raises exception, only 3 try will be terminated, but code 1.2 will
be executed and 2.3 catch will be called.
Multiple try
In one method we can add more than one try.. catch blocks like follows
void m1()
try{//1}catch(Exception e){}
try{//2}catch(Exception e){}
try{//3}catch(Exception e){}
The benefit is that, if 1 block raises exception, 2,3 will be executed and so on.
try
finally
{
}
If any exception is raised within the try block, exception will be sent to
console, and finally block will be called.
The benefit is that, if we need to do following things, we can use this method.
One try can have more than one catch blocks like follows.
try{}
catch(ArrayIndexOutOfBoundsException ai){}
catch(StringIndexOutOfBoundsException si){}
catch(NumberFormatException nfe){}
The benefit of above technique is that, if any one of three exception is raised
the appropriate catch block will be called at run time.
But other than handled exception is raised, the exception goes to console. To
avoid this, just add following catch block at last.
catch(Exception e){}
It means, if any exception other than handled three exception is raised, the
catch(Exception e){} block will be called by runtime. Because all exception
classes are the sub classes of Exception.
Since java 1.7, we can add more that one exception in catch block instead writing
many catch blocks. Let's see the below example to understand how the block can be
written.
try
int c = a/b;
catch(ArithmeticException | ArrayIndexOutOfBoundsException |
NullPointerException e)
e.printStackTrace();
try with resources is used to close the resources of files or sockets or JDBC
objects etc. The resources (say objects) opened in try block automatically will be
closed when the execution control passes out try block. No need to write separate
code to close the objects. The notable thing is that an object which implements
java.lang.AutoCloseable method is eligible to close automatically.
Example :
try ( // below two objects are eligible to close when try block execution
completed.
catch (IOException e)
e.printStackTrace();
Own Exceptions
We can define our own exceptions like predefined exceptions. Our own exception
class should be the sub class of Exception class.
The benefit is that we can handle our application based run time exceptions like
AgeExceededException, InvalidRupeesFormatException. The name of exceptions can be
defined as per your need and willingness.
Because of you can define your exceptions in separate package and you can separate
the exception handling part from your application.
Once we create the exception handling part it can be used in many applications.
Sample program
Above two classes illustrate how exception should be defined and how the exception
can be thrown. Listen, the AgeExceededException overrides toString() Object class.
It means when GetAge class prints AgeExceededException class object, the
toString() of AgeExceededException class will be called.
String getMessage()
void printStackTrace()
Thread
A multithreaded program contains two or more parts that can run concurrently
(Parallel). Each part of such a program is called a thread, and each thread
defines a separate path of execution.
States of Thread
A thread state. A thread can be in one of the following states:
NEW
A thread that has not yet started is in this state.
RUNNABLE
A thread executing in the Java virtual machine is in this state.
BLOCKED
A thread that is blocked waiting for a monitor lock is in this state.
WAITING
A thread that is waiting indefinitely for another thread to perform a
particular action is in this state.
TIMED_WAITING
A thread that is waiting for another thread to perform an action for up to a
specified waiting time is in this state.
TERMINATED
A thread that has exited is in this state.
Returns the state of this thread. This method is designed for use in monitoring
of the system state, not for synchronization control.
Benefits of Threads
To utilize the CPU’s idle time threads can be used. For example your program
waits to get file path form user. The user takes some seconds to provide the
file path. In the seconds, your program waits, it wastes CPU’s process. In mean
time you can do other tasks in your program by using other threads.
The execution of one thread will not affect another thread’s process.
Types of multitasking
Thread based multitasking is the feature to run two or more parts in one
application. (Running spell check in Msword, and printing the document)
Thread creation
The other way to create a thread is to declare a class that implements the
Runnable interface. The class then override the run method.
Way 1
A ob=new A();
Way 2
A ob=new A();
In way 1, we extend Thread class and override run(). The technique is that the
tasks of thread should be given within run(). The problem of way 1 is that we
can’t extend no other classes. Because java supports multilevel only.
If you need to create Applet, your class must be the sub class of Applet. In
this situation, you can’t do it, if your class is the sub class of Thread.
Java assigns to each thread a priority that determines how that thread should
be treated with respect to others.
A higher priority thread doesn’t run faster than lower priority thread.
A thread’s priority is used to decide when to switch from one running thread to
the next. This is called as context switch.
If more than one thread has same priority. Then OS follows Round Robin
fashion(Time Slicing). By using this method, same priority threads have
particular time to utilize the CPU resource.
Preemptive multitasking
Synchronization
For example GetItem thread gets items from user. In same time Bill thread must
wait to finish the tasks of GetItem thread. After completion of GetItem thread,
the Bill thread makes billing then GetItem thread starts its work to get items
from next customer.
This is synchronization.
1) synchronized as a keyword
synchronized(obj){}
2) synchronized as a modifier
class A
T1, T2 are threads and ob1 is the object which has two methods getItems(),
bill().
T1 enters into getItem() and T2 tries to call bill and it waits until the
completion of T1. Because getItems(), bill() are synchronized methods.
T2 enters into bill and complete 100% code and notifies T1 then it goes to
waiting state.
Synchronization diagram
ob1
synchronized getItem()
{
T1
//code
synchronized bill()
Waits here to
call bill() after t1 {
T2 exits from ob1
//code
ob1
T1 1 synchronized getItem()
{
Waiting state
//75%code
2
wait();
noifty();
synchronized bill()
T2 3 {
//100% code
notify();
wait();
Deadlock diagram
ob1
synchronized m1()
T1 Waits to call
{ m2()
//code
synchronized m2()
//code
ob2
synchronized n1()
{
T2 Waits to call n2()
//code
synchronized n2()
//code
T1 enters into ob1 and calls m1() then it tries to call n2() of ob2.
T2 enters into ob2 and calls n1() then it tries to call m2() of ob1.
This is deadlock
Deadlock occurs when two threads have a circular dependency on a pair of synchronized objects.
1. import java.io.*;
2. class A
3. {
4. B b;
5. void getObject(B b)
6. {
7. this.b=b;
8. }
9. synchronized void m1()
10. {
11. System.out.println("I am m1 method");
12. try
13. {
14. Thread.sleep(1000);
15. }
16. catch(Exception e){}
17. b.n2();
18. }
19. synchronized void m2()
20. {
21. System.out.println("I am m2");
22. }
23. }
24.
25. class B
26. {
27. A ob1;
28. void getObject(A ob1)
29. {
30. this.ob1=ob1;
31. }
32. synchronized void n1()
33. {
Thread()
Thread(Runnable target)
Creates a new Thread object with given target. Here target should be a sub class
of Runnable object. It means starting thread calls target’s run().
Same as above constructor but we can provide the name for our thread.
Thread(String name)
Creates Thread object with target and this thread becomes a member of specified
group.
Returns the number of active threads in the current thread's thread group.
Main is also thread. When you start one program first main() will be called by OS.
It means one thread will be started by default.
Main is also a thread. It means, When you start one new prg , java really starts one
new thread. Below program explains how to obtain the current thread and its usage.
1. class CurrentThread
2. {
3. public static void main(String args[])
4. {
5. Thread ct=Thread.currentThread(); // obtain current thread
6. System.out.println("ct="+ct);
7. System.out.println("ct.getName()="+ct.getName());
8. System.out.println("ct.getPriority()="+ct.getPriority());
9. ct.setName("My Thread");
10. ct.setPriority(10);
11. System.out.println("After Set Priority");
12. System.out.println("ct.getName()="+ct.getName());
13. System.out.println("ct.getPriority()="+ct.getPriority());
14. }
15. }
16.
17. Output
18.
19. ct=Thread[main,5,main]
20. ct.getName()=main
21. ct.getPriority()=5
22. After Set Priority
23. ct.getName()=My Thread
24. ct.getPriority()=10
To stop one thread temporary at given seconds. It is static method, so we can call
this method in any program other than thread program.
By default thread has one name by JRE. You can provide your needed name to
thread by using this method.
String getName()
To set the new priority for one thread. The default priority is 5.
You can alternatively use following Thread class constants instead of provide
the integer numbers. There is no difference between providing integers and
providing following constants of Thread class.
for example
t.setPriority(Thread.MIN_PRIORITY) (or)
To ensure only one thread utilizes the CPU and other joined threads must wait to
completion of first thread.
Here you can recall the synchronization, synchronization ensures no other thread
exits into monitor, if one thread enters into monitor.
But join ensures no other joined threads started until the completion of all tasks
of first thread.
1. class Item {
2. int x;
3.
4. synchronized void get() {
5. System.out.println("I am get");
6. try {
7. Thread.sleep(1000);
8. } catch (Exception e) {
9. e.printStackTrace();
10. }
11. System.out.println("I am get after sleep");
12. }
13.
14. synchronized void put() {
15. System.out.println("I am put");
16. }
17. }
18.
19. class Thread1 implements Runnable {
20. Item ob;
21. Thread t;
22.
23. Thread1(Item ob) {
24. this.ob = ob;
25. t = new Thread(this);
26. t.start();
27. }
28.
29. public void run() {
30. for (int i=0;i<5;i++) {
31. ob.get();
32. try {
33. Thread.sleep(1000);
34. }
35. catch (Exception e) {
36. e.printStackTrace();
37. }
38. }
39. }
40. }
41.
42. class Thread2 implements Runnable {
43. Item ob;
44. Thread t;
45.
46. Thread2(Item ob) {
47. this.ob = ob;
48. t = new Thread(this);
49. t.start();
50. }
51.
52. public void run() {
53. for (int i=0;i<5;i++) {
54. ob.put();
55. try {
56. Thread.sleep(1000);
57. }
58. catch (Exception e) {
59. }
60. }
61. }
62. }
63.
64. class SynchronizedDemo {
65. public static void main(String args[]) {
66. Item ob = new Item();
67. Thread1 t1 = new Thread1(ob);
To stop thread temporarily until calls resume(). The suspended thread can only
be resumed but not restarted, if we try to restart the suspended thread,
java.lang.IllegalThreadStateException will be raised.
The running Thread can be stopped by using stop(). After stopped resume()
cannot be used, but you can call this method. start() cannot be worked after
calling stop(), if so java.lang.IllegalThreadStateException will be raised.
stop() cannot work properly. Use return() statement to stop thread properly.
A suspended Thread can be released by using this method, before using resume()
the thread should be suspended.
void start()
To allow temporarily other thread to utilize the CPU, invoking thread should
have normal priority to work yield() properly.
It tells the calling thread to give up the monitor and go to sleep until some
other thread enters into same monitor and calls notify.
Wakes up all sleeping threads that called wait() of the same object.
1.CountDownLatch
2.Semephore
3.CyclicBarrier
CountDownLatch
It is a class to ensure set of code should be waited until some threads finishes
their execution.
For example main() starts 5 threads to download the file from server. main() needs
to start another one thread to assemble the downloaded file from server after 5
threads execution complete. In this situation you can use this class.
Constructors
CountDownLatch(int count)
Here count can be used to specify number of threads should be finished to start
the code after await().
CountDownLatch
Synchonized
wait(), notify()
1. import java.io.*;
2. import java.util.concurrent.*;
3.
4. class Shop {
5. String itemname[] = new String[10];
6. double qty[] = new double[10];
7. double rpu[] = new double[10];
8. int choice;
9. int q = 0;
10. double total[] = new double[10];
11.
12. synchronized void getItemDetails() {
13. try {
14. DataInputStream dis = new DataInputStream(System.in);
15. System.out.println("Enter Item Name");
16. itemname[q] = dis.readLine();
17. System.out.println("Enter Qty");
18. qty[q] = Double.parseDouble(dis.readLine());
19. System.out.println("Enter Rate Per Unit");
20. rpu[q] = Double.parseDouble(dis.readLine());
21. try {
22. /* invoking wait() gives up cpu to another waiting thread now bill thread
will be invoked
23. */
24. wait(); // Object class
25. } catch (Exception e) {
26. }
27. notify();
28. } catch (Exception e) {
29. }
30. }
31.
32. synchronized void bill() {
33. try {
34. total[q] = qty[q] * rpu[q];
35. q++;
36. /* notify wake up another waiting thread of same object. Here same object
is Shop object*/
37.
38. notify();
39. wait();
40. } catch (Exception e) {
41. }
42. }
43.
44. synchronized void printFormat() {
45. int i = 0;
46. double granttotal = 0;
47. System.out.println("----------------------------------------------
--------------------");
48. System.out.print("S.No ");
49. System.out.print("\t ITEM NAME ");
50. System.out.print("\t ITEM RATE ");
51. System.out.print("\tQUANTITY ");
52. System.out.println("\tTOTAL ");
53. System.out.println("----------------------------------------------
--------------------");
54. for (i = 0; i < 4; i++) {
55. System.out.print(i);
56. System.out.print("\t" + itemname[i]);
57. System.out.print("\t\t" + rpu[i]);
58. System.out.print("\t\t" + qty[i]);
59. System.out.println("\t\t" + total[i]);
60. granttotal = granttotal + total[i];
61. }
62. System.out.println("\t \t \tGRANT TOTAL :" + granttotal);
63. System.out.println("----------------------------------------------
--------------------");
64. }
65. }
66.
67. class GetItemThread implements Runnable {
68. Shop s;
69. Thread t1 = new Thread(this);
70. CountDownLatch cdl;
71.
72. GetItemThread(Shop s, CountDownLatch cdl) {
73. this.s = s;
74. this.cdl = cdl;
75. t1.start();
76. }
77.
78. public void run() {
79. while (true) {
80. System.out.println("Item Thread :" + cdl.getCount());
81. s.getItemDetails();
82. cdl.countDown();
83. }
84. }
85. }
86.
87. class BillThread implements Runnable {
88. Shop s;
89. Thread t2 = new Thread(this);
90. CountDownLatch cdl;
91.
92. BillThread(Shop s, CountDownLatch cdl) {
93. this.s = s;
94. this.cdl = cdl;
95. t2.start();
96. }
97.
98. public void run() {
134. try {
135. /*
136. * Runtime waits here to call below statement until countDownL
atch value reaches
137. * 8 The 8 is given in CountDownLatch Constructor
138. */
139. cdl.await();
140. } catch (Exception e) {
141. System.out.println(e);
142. }
143. git.t1.stop();
144. bill.t2.stop();
145. git.t1 = null;
146. bill.t2 = null;
147. System.out.println("Both Threads Finished");
148. PrintFormatThread pri = new PrintFormatThread(s);
149. System.out.println("Printing Threads Finished");
150. }
151. }
152.
153. Output
154.
155. Item Thread :8
156. Bill Thread :8
157. Enter Item Name
158. item1
159. Enter Qty
160. 2
161. Enter Rate Per Unit
162. 50
163. Item Thread :6
164. Enter Item Name
165. Bill Thread :6
166. item2
167. Enter Qty
168. 3
169. Enter Rate Per Unit
170. 45
171. Item Thread :5
172. Enter Item Name
173. iBill Thread :4
174. tem3
175. Enter Qty
176. 5
177. Enter Rate Per Unit
178. 60
179. Item Thread :3
180. Enter Item Name
181. Bill Thread :2
182. item4
183. Enter Qty
184. 4
185. Enter Rate Per Unit
186. 30
187. Item Thread :1
188. Enter Item NameBoth Threads Finished
189. Printing Threads Finished
190. printthread=1
191. ------------------------------------------------------------------
192. S.No ITEM NAME ITEM RATE QUANTITY TOTAL
193. ------------------------------------------------------------------
194. 0 item1 50.0 2.0 100.0
195. 1 item2 45.0 3.0 135.0
196. 2 item3 60.0 5.0 300.0
197. 3 item4 30.0 4.0 120.0
198. GRANT TOTAL :655.0
199. ------------------------------------------------------------------
200. printthread=2
Methods
The statements found after await() will not executed until count reaches 0.
void countdown()
long getCount()
Semaphore
To ensure particular number of threads can utilize the CPU’s resource at one
time.
Constructors
Semaphore(int permits)
Methods
void acquire()
void release()
It releases the permit from semaphore, and semaphore will provide the
permit to another one thread.
CyclicBarrier
To execute one thread whenever particular number of threads tasks are completed.
Constructors
Methods
int await()
int getParties()
1. /*
2. public CyclicBarrier(int parties,
3. java.lang.Runnable r)
4. public int await()
5. throws java.lang.InterruptedException,
6. BrokenBarrierException
7. public int getParties()
8. */
9. import java.util.concurrent.*;
10.
11. class CyclicBarrierDemo {
12. public static void main(String args[]) {
13. BarAction obj = new BarAction();
14. /*
15. First argument of CyclicBarrierConstructor instructs runtime to invoke obj
thread(second argument) whenever two threads are completed
16. */
86.
87. Thread4(CyclicBarrier cbar, String name) {
88. this.cbar = cbar;
89. this.name = name;
90. new Thread(this).start();
91. }
92.
93. public void run() {
94. try {
95. System.out.println(name);
96. cbar.await();
97. } catch (Exception e) {
98. }
99. }
100. }
101.
102. class BarAction implements Runnable {
103. public void run() {
104. System.out.println("Barrier Reached");
105. }
106. }
107.
108. Output
109.
110. Starting...
111. Thread1
112. Thread2
113. Barrier Reached
114. Thread3
115. 2
116. Thread4
117. Barrier Reached
ThreadGroup
You need to create threads for each one client, those joins in network. In such
time your program uses some other threads to manage other works.
Here you can group the client threads to avoid the complication with other
threads.
The benefit is that you can supend(), resume(), stop(), list() the threads by
using single command.
Constructor
Methods
int activeCount()
void destroy()
Copies into the specified array every active thread in this thread group.
void list()
1. import java.math.BigDecimal;
2. import java.math.MathContext;
3. import java.math.RoundingMode;
4.
5. public class BigDecimalDemo {
6.
7. public static void main(String[] args) {
8. // TODO Auto-generated method stub
9. double d1=2.434534345345d;
10. double d2=5.23453434345345d;
11. System.out.println(d1*d2);
12.
13. BigDecimal b1=new BigDecimal(d1);
14. BigDecimal b2=new BigDecimal(d2);
15. /*
16. * 4 defines number of degits in results
17. * CEILING defines rounding mechanism
18. */
19. BigDecimal b3=b1.multiply(b2,new MathContext(4,RoundingMode.CEILING));
20.
21. System.out.println(b3);
22. }
23.
24. }
25.
26. Output
27.
28. 12.743653641025363
29. 12.75
java.lang.String
Difference 1
For example
String str=”Java”;
str.concat(“Prg”);
In contrast,
sb.insert(4,”Prg”);
now sb=”JavaPrg”
Difference 2
Constructor
String()
String(byte[] a)
Works like above method, but we can also specify start of byte array and
length of byte array.
String(char[] char)
Works like above method, but we can also specify start of char array and
length of char array.
String(StringBuffer sb)
String(String str)
String Methods
Returns the index of first occurrence of ch from invoking string. But searching
starts with given start.
Returns the index of first occurrence of str from invoking string. But searching
starts with given start.
Returns the index within this string of the last occurrence of the specified
character.
Returns the index within this string of the last occurrence of the specified
character, searching backward starting at the specified start.
Returns the index within this string of the last occurrence of the specified
character, searching backward starting at the specified start.
int length()
It returns +1
It returns -1
Compares invoking string with given obj with case sensitive checking.
Returns true if both are same other wise false.
String trim()
Returns a copy of the string, after removing the white spaces occurred left
and right side.
Returns a new string from invoking string between startindex and endindex-1.
Returns a new string from start index to last from invoking string.
byte[] getBytes()
Encodes this String into a sequence of bytes storing the result into a new
byte array. We can use this method to convert string to byte[].
Copies characters from this string into the target character array.
object.
To check the portions of two strings we can use this method. If ignorecase
is true, this method will not see case, other wise it checks case also.
char[] toCharArray()
String toLowerCase()
String toUpperCase()
All above valueOf() can be used to convert given data type to string.
String toString()
It is very important method overridden from Object class, to covert any type to
String.
Works like above method but checking will be started from given start
index.
StringBuffer
Constructors
SringBuffer()
SringBuffer(int capacity)
StringBuffer(String str)
Methods
int capacity()
int length()
StringBuffer append(boolean b)
Appends given boolean with invoking StringBuffer. Instead of b you can also
give int,object,float,long,char[],double,String
StringBuffer reverse()
If newlen is greater with current length, null values are added, otherwise you
will loss data.
Example 1
System.out.println(sb.capacity());//24(16+8)
Sb.ensureCapacity(60);
System.out.println(sb.capacity())//60
Example 2
System.out.println(sb.capacity());//24(16+8)
sb.ensureCapacity(40);
System.out.println(sb.capacity())//50
Example 3
System.out.println(sb.capacity());//24(16+8)
Sb.ensureCapacity(22);
System.out.println(sb.capacity())//24
void trimTosize()
To trim extra bytes allocated for the invoking object. It means current length
becomes new capacity.
In this chapter we will see about database programming using java.sql and
javax.sql.
Database concepts
Table
Database
Database is a collection of tables and other related files such as reports, views….
DBMS
RDBMS
Like DBMS with relationship facility. Relationship means master table and child table
relationship.
Entity
Normalization
Normalization is the process to divide the tables from the collection of entity data.
Entity data is the collection of fields about entity.
When dividing entity data, we must take care about master tables, child tables,
primary key, unique key and foreign key concepts.
Primary key
Unique key
Front End
It is the s/w to visualize the screens to get the inputs and show the outputs and also
having the ability to connect other systems to get and retrieve the data and It can't
store the data itself.
Back End
Driver or Provider
It sends request to back end sent by front end and receives the response from back
end and submits to front end.
SQL
DDL – Data Definition Language
grant,revoke
ResultSet
Statements
Statement
PreparedStatement
CallableStatement
This driver comes with JDK itself in sun.jdbc.odbc package. This type of driver
is purely implemented in ‘C’ language and this is platform dependent in nature.
So Java creators create JDBC – Odbc Driver to avoid programmer can connect
directly ODBC driver.
Example to load the driver and create the connection using Type 1 driver
1. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
2. /* Specifies the DSN name as mydsn and jdbc is the protocol and odbc is the subp
rotocol. scott is the
3. * username and tiger is the password for oracle database
4. */
5. Connection con=DriverManager.getConnection("jdbc:odbc:mydsnorc","scott","tiger")
;
No need to install Type-1 driver separately, since it comes as part of the JDK.
The Type-1 driver is the dependent driver since its depending on ODBC support.
Type -2 driver uses native API supplied by a database vendor to connect with a
database. Type 2 driver converts the JDBC calls into native calls, to connect
with the database.
The Type-2 driver is both platform and database dependent. Hence it is not
suitable for real-time applications.
Net Protocol is a Type-3 JDBC driver. It was written in Java programming. This
network protocol driver uses the middle software like an application server.
The JDBC clients use the standard network sockets to communicate with the
middleware application server.
The middleware application server internally converts the JDBC calls to the
vendor’s specific database protocol.
Since it is a network driver, the middle ware layer may reduce the performance.
The Type-4 driver uses native protocol accepted by the database server to
establish a connection between a java program and database.
On the above connection syntax, “THIN” is a driver name. The thin driver
converts the JDBC calls to the vendor’s specific database calls.
Access
Start -> Settings -> Control Panel -> Administrative Tools -> Data Sources -> ADD ->
Select Microsoft Access Driver -> Finish -> Type DSN Name in Data Source Name text box
-> Click Select Button -> Select Path of mdb file name -> OK
Oracle
Start -> Settings -> Control Panel -> Administrative Tools -> Data Sources -> ADD ->
Select Microsoft ODBC for Oracle -> Finish -> Type DSN Name in Data Source Name text
box -> OK
What is Procedure
Procedure can accept more parameters and it can return more than one values to
caller.
OUT parameters are the returned parameters IN parameters are the argument
parameters.
SQL>ed Pro1.sql
In this time you can list the error by providing following command
Above command list the errors and you must correct the errors
Methods of Statement(I)
It executes all types of query. If result is true, query is select query and
you can get ResultSet object by using below method.
ResultSet getResultSet()
To get the resultset, which has resultant records of executed select query
Select query will be executed using this method and returns the resultant
records as a ResultSet object.
Query should be other than select query. Returns no of records are affected.
int getMaxRows()
Statement
PreparedStatement
CallableStatement
Statement hands over the query before the compilation to back end. So the query
should be completed with necessary values.
PreparedStatement compiles the query first and hands over the query to back
end.
For Example
select * from emp where dob=? Both for access and oracle.
In (2) and (3) points we conclude that usage prepared statement is easier and
when we need to pass sql query as the same as we received we can use Statement.
In (1) and (4) we conclude that Statement query will not be compiled by java
PreparedStatement query will be compiled by java.
Scrollable PreparedStatement
PreparedStatement ps=con.prepareStatement(“
Query”,ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs=ps.executeQuery();
ResultSet rs=ps.executeQuery();
Statement
s=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABL
E);
Statement s=con.createStatement();
TYPE_SCROLL_INSENSITIVE: The cursor can scroll forward and backward and the
database changes will not be reflected in result set and the resultset contains
the records at the time of opening.
TYPE_SCROLL_SENSITIVE: The cursor can scroll forward and backward, and the Result
set reflects the changes made to the underlying data source while the result
set remains open.
TYPE_FORWARD_ONLY: The result set cannot be scrolled; its cursor moves forward
only,
Note:
Not all databases and JDBC drivers support all ResultSet types. The method
DatabaseMetaData.supportsResultSetType returns true if the specified ResultSet
type is supported and false otherwise.
ResultSet Concurrency
Note: Not all JDBC drivers and databases support concurrency. The method
DatabaseMetaData.supportsResultSetConcurrency returns true if the specified
concurrency level is supported by the driver and false otherwise
ResultSet Methods(I)
int getRow()
void afterLast()
void beforeFirst()
boolean isBeforeFirst()
boolean isAfterLast()
boolean isFirst()
boolean isLast()
boolean next()
boolean previous()
void cancelRowUpdates()
void close()
void deleteRow()
Returns column no
Blob getBlob(int i)
void insertRow()
boolean last()
void updateRow()
Below program creates the table using dsnname in access data base.
In above notes, refer to create the DSN.
1. import java.sql.*;
2. class CreateTable
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
9. //mydsn is the dsnname
10. Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");
11. PreparedStatement ps=con.prepareStatement("create table customer(cusname t
ext(30),company text(30),pur_amt number,bal_amt number)");
12. ps.executeUpdate();
13. System.out.pirntln(“Table has been created”);
14. ps.close();
15. con.close();
16. }
17. catch(Exception e)
18. {
19. e.printStackTrace();
20. }
21. }
22. }
23. Output
24. Table has been created
1. import java.sql.*;
2. import java.io.*;
3. class CreateTableFromUser
4. {
5. public static void main(String args[])
6. {
7. DataInputStream dis=new DataInputStream(System.in);
8. String tablename;
9. String str;
10. String cn,type,size;
11. try
12. {
13. int x,more=0,choice=0;
14. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
15. //mydsnorc is the dsnname and scott is the username,tiger is the password
of oracle database
16. Connection con=DriverManager.getConnection("jdbc:odbc:mydsnorc","scott","t
iger");
17. System.out.println("Enter Table Name");
18. tablename=dis.readLine();
19. str="create table "+tablename+"(";
20. do
21. {
22. System.out.println("Enter the Column Name");
23. cn=dis.readLine();
24. System.out.println("Enter the Data Type ");
25. type=dis.readLine();
26. System.out.println("Enter the Size ");
27. size=dis.readLine();
28. System.out.println("Add More Yes - 1 No -0");
29. if (more==1)
30. str=str+","+cn+ " "+type+"("+size+")";
31. else
32. System.out.println("1");
33. str=str+cn+ " "+type+"("+size+")";
34. choice=Integer.parseInt(dis.readLine());
35. }while(choice==1);
36. str=str+")";
37. System.out.println(str);
38. PreparedStatement ps=con.prepareStatement(str,ResultSet.TYPE_SCROLL_SENSIT
IVE,ResultSet.CONCUR_UPDATABLE);
39. ps.executeUpdate();
40. }
41. catch(Exception e)
42. {
43. System.out.println(e);
44. }
45. }
46. }
47. Output
48.
49. Table has been created in oracle
1. import java.sql.*;
2. class Select
3. {
4. public static void main(String args[])
5. {
6. try{
7. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
8. Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");
9. PreparedStatement ps=con.prepareStatement("select * from deptmaster");
10. ResultSet rs=ps.executeQuery();
11. System.out.println("Dno"+"\t\t\t"+"DName"+"\t\t "+"Head");
12. while(rs.next())
13. {
14. System.out.println(rs.getString(1)+"\t\t"+rs.getString(2)+"\t\t"+rs.getStr
ing(3));
15. }
16. ps.close();
17. con.close();
18. }
19. catch(Exception e)
20. {
21. e.printStackTrace();
22. }
23. }
24. }
25.
26. Output
27.
28. Dno DName Head
29. d0001 production ramprasath
30. d0002 purchase sivaramKumar
31. d0003 marketing sathish
32. d0004 accounts ram prasath
1. import java.sql.*;
2. class Insert
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
9. Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");
1. import java.sql.*;
2. class HowValuesInsertedForSelectedColumn
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
9. Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");
10. PreparedStatement ps=con.prepareStatement("insert into marklist(sno,name)
values(?,?)");
11. ps.setInt(1,102);
12. ps.setString(2,"Shiva");
13. System.out.println(ps.executeUpdate());
14. }
15. catch(Exception e)
16. {
17. System.out.println(e);
18. }
19. }
20. }
21.
22. Output
23.
24. 1 //number of affected row
1. import java.sql.*;
2. class Update
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
9. Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");
1. import java.sql.*;
2. class Delete
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
9. Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");
10. PreparedStatement ps=con.prepareStatement("delete from deptmaster where dn
o=?");
11. ps.setString(1,"d0005");
12. ps.executeUpdate();
13. ps=con.prepareStatement("delete from deptmaster where dno=?");
14. ps.setString(1,"d0006");
15. ps.executeUpdate();
16. ps=con.prepareStatement("select * from deptmaster");
17. ResultSet rs=ps.executeQuery();
18. while(rs.next())
19. {
20. System.out.println(rs.getString(1)+"\t"+rs.getString(2)+"\t"+rs.getString(
3));
21. }
22. ps.close();
23. con.close();
24. }
25. catch(Exception e)
26. {
27. e.printStackTrace();
28. }
29. }
30. }
31.
32. Output
33. d0001 production ramprasath
34. d0002 purchase sivaramkumar
35. d0003 marketing sathish
36. d0004 accounts ramprasath
1. import java.sql.*;
2. class DropTable
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
9. Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");
10. PreparedStatement ps=con.prepareStatement("drop table customer");
11. ps.executeUpdate();
12. System.out.println("Table has been Droped");
13. ps.close();
14. con.close();
15. }
16. catch(Exception e)
17. {
18. System.out.println(e);
19. }
20. }
21. }
22.
23. Output
1. import java.sql.*;
2. class StatementMethods
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. ResultSet resultset=null;
9. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
10. Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");
11. Statement st=con.createStatement();
12. boolean flag=st.execute("select * from deptmaster");
13. if (flag==true)
14. {
15. resultset=st.getResultSet();
16. System.out.println(resultset.getType());
17. }//if
18. resultset.first();
19. }//try
20. catch(Exception e)
21. {
22. System.out.println(e);
23. }
24. }//main
25. }//class
26.
27. Output
28. 1003
1. import java.sql.*;
2. class SelectDemo
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
9. Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");
10.
11. Statement st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet
.CONCUR_UPDATABLE);
12. ResultSet rs=st.executeQuery("select * from empmaster where dob=#23-OCT-
1973#");
13. while (rs.next())
14. {
15. System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(
3)+" "+rs.getDate(4)+" "+rs.getDate(5)+" "+rs.getString(6)+" "+rs.getInt(7)
+" "+rs.getString(8)+" "+rs.getString(9));
16. }
17. }
18. catch(Exception e)
19. {
20. System.out.println(e);
21. }
22. }
23. }
24.
25. Output
26. e0005 priya f 1973-10-23 1998-01-12 n 0 dindigul d0004
1. import java.sql.*;
2. class SelectDemoUsingPreparedStatement
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
9. Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");
10. PreparedStatement ps=con.prepareStatement("select * from empmaster where d
no in(?,?,?)");
11. ps.setString(1,"d0001");
12. ps.setString(2,"d0002");
13. ps.setString(3,"d0004");
14. ResultSet rs=ps.executeQuery();
15. while (rs.next())
16. {
17. System.out.println(rs.getString("ename"));
18. }
19. }
20. catch(Exception e)
21. {
22. System.out.println(e);
23. }
24. }
25. }
26.
27. Output
28. surya narayanan
29. dorio solamon
30. sai ram
31. priya
32. ashok kumar
33. vidhya
1. import java.sql.*;
2. class AbsoluteDemo
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
9. Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");
10. PreparedStatement ps=con.prepareStatement("select * from empmaster",Result
Set.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
11. ResultSet rs=ps.executeQuery();
12. rs.absolute(4); //calculates from first record
13. System.out.println("rs.getRow()="+rs.getRow());
14. rs.absolute(-1); // To Go to last record
15. System.out.println("rs.getRow()="+rs.getRow());
16. rs.last();
17. System.out.println("rs.getRow()="+rs.getRow());
18. rs.absolute(4);
19. System.out.println("rs.getRow()="+rs.getRow());
20. rs.absolute(-5); // calculates from last record
21. System.out.println("rs.getRow()="+rs.getRow());
22.
23. }
24. catch(Exception e)
25. {
26. System.out.println(e);
27. }
28. }
29. }
30.
31. Output
32. rs.getRow()=4
33. rs.getRow()=10
34. rs.getRow()=10
35. rs.getRow()=4
36. rs.getRow()=6
1. import java.sql.*;
2. class DataType
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
9. Connection con=DriverManager.getConnection("jdbc:odbc:javadsn");
10. Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,Resul
tSet.CONCUR_UPDATABLE);
11. ResultSet rs=stmt.executeQuery("select * from datatype");
12. rs.first();
13. System.out.println("rs.getString(1)="+rs.getString(1));
14. System.out.println("rs.getInt(2)="+rs.getInt(2));
15. System.out.println("rs.getLong(3)="+rs.getLong(3));
16. System.out.println("rs.getByte(4)="+rs.getByte(4));
17. System.out.println("rs.getFloat(5)="+rs.getFloat(5));
18. System.out.println("rs.getDouble(6)="+rs.getDouble(6));
19. System.out.println("rs.getDate(7)="+rs.getDate(7));
20. System.out.println("rs.getTime(8)="+rs.getTime(8));
21. rs.updateString(1,"Text111");
22. rs.updateInt(2,2);
23. rs.updateLong(3,30);
24. rs.updateByte(4,(byte)100);
25. rs.updateFloat(5,100.1f);
26. rs.updateDouble(6,100.123);
27. rs.updateDate(7,new Date(System.currentTimeMillis()));
28. rs.updateTime(8,new Time(System.currentTimeMillis()));
29. rs.updateRow();
30. System.out.println("rs.getString(1)="+rs.getString(1));
31. System.out.println("rs.getInt(2)="+rs.getInt(2));
32. System.out.println("rs.getLong(3)="+rs.getLong(3));
33. System.out.println("rs.getByte(4)="+rs.getByte(4));
34. System.out.println("rs.getFloat(5)="+rs.getFloat(5));
35. System.out.println("rs.getDouble(6)="+rs.getDouble(6));
36. System.out.println("rs.getDate(7)="+rs.getDate(7));
37. System.out.println("rs.getTime(8)="+rs.getTime(8));
38. rs.moveToInsertRow();
39. rs.updateString(1,"Text111");
40. rs.updateInt(2,2);
41. rs.updateLong(3,30);
42. rs.updateByte(4,(byte)100);
43. rs.updateFloat(5,100.1f);
44. rs.updateDouble(6,100.123);
45. rs.updateDate(7,new Date(System.currentTimeMillis()));
46. rs.updateTime(8,new Time(System.currentTimeMillis()));
47. rs.insertRow();
48. }
49. catch(Exception e)
50. {
51. e.printStackTrace();
52. }
53. }
54. }
55. Output
56. rs.getString(1)=Text111
57. rs.getInt(2)=2
58. rs.getLong(3)=30
59. rs.getByte(4)=100
60. rs.getFloat(5)=100.1
61. rs.getDouble(6)=100.123
62. rs.getDate(7)=2006-10-08
63. rs.getTime(8)=16:48:29
64. rs.getString(1)=Text111
65. rs.getInt(2)=2
66. rs.getLong(3)=30
67. rs.getByte(4)=100
68. rs.getFloat(5)=100.1
69. rs.getDouble(6)=100.123
70. rs.getDate(7)=2006-10-14
71. rs.getTime(8)=19:20:49
1. import java.sql.*;
2. class DeleteRowDemo
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
9. Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");
10. con.setAutoCommit(false);
11. PreparedStatement ps=con.prepareStatement("select * from empmastercopy",Re
sultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
12. ResultSet rs=ps.executeQuery();
13. rs.absolute(2)
14. rs.deleteRow();
15. con.rollback();
16. }
17. catch(Exception e)
18. {
19. e.printStackTrace();
20. }
21. }
22. }
1. import java.sql.*;
2. class RelativeDemo
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
9. Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");
10. PreparedStatement ps=con.prepareStatement("select * from empmaster",Result
Set.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
11. ResultSet rs=ps.executeQuery();
12. rs.first();
13. rs.relative(5);
14. System.out.println("Get Row="+rs.getRow());
15. rs.relative(1);
16. System.out.println("Get Row="+rs.getRow());
17. rs.relative(10);
18. System.out.println(rs.isAfterLast());
19. System.out.println("Get Row="+rs.getRow());
20. rs.first();
21. System.out.println("Get Row="+rs.getRow());
22. rs.relative(10);
23. System.out.println("Get Row="+rs.getRow());
24. rs.relative(-2);
25. }
26. catch(Exception e){
27. e.printStackTrace();
28. }
29. }//main
30. }//class
1. import java.sql.*;
2. import java.io.*;
3. class All
4. {
5. public static void main(String args[])
6. {
7. try
8. {
9. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
10. Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");
20. System.out.println("getColumnLabel(1)="+md.getColumnLabel(1));
21. System.out.println("getColumnName(1)="+md.getColumnName(1));
22. System.out.println("getColumnType(1)="+md.getColumnType(1));
23. System.out.println("getColumnType(5)="+md.getColumnType(5));
24. System.out.println("getColumnType(3)="+md.getColumnType(3));
25. System.out.println("getColumnTypeName(1)="+md.getColumnTypeName(1));
26. System.out.println("getColumnTypeName(3)="+md.getColumnTypeName(3));
27. System.out.println("getPrecision(7)="+md.getPrecision(7));
28. System.out.println("getScale(7)="+md.getScale(7));
29. System.out.println("isAutoIncrement(7)="+md.isAutoIncrement(7));
30. System.out.println("isCaseSensitive(2)="+md.isCaseSensitive(2));
31. System.out.println("isNullable(1)="+md.isNullable(1));
32. System.out.println("isNullable(5)="+md.isNullable(5));
33. }
34. catch(Exception e)
35. {
36. e.printStackTrace();
37. }
38. }
39. }
40.
41. Output
42. 0
43. 1
44. 2
45. getColumnClassName(2)=java.lang.String
46. getColumnCount()=8
47. getColumnDisplaySize(6)=50
48. getColumnLabel(1)=ccode
49. getColumnName(1)=ccode
50. getColumnType(1)=12
51. getColumnType(5)=-6
52. getColumnType(3)=5
53. getColumnTypeName(1)=VARCHAR
54. getColumnTypeName(3)=SMALLINT
55. getPrecision(7)=50
56. getScale(7)=0
57. isAutoIncrement(7)=false
58. isCaseSensitive(2)=false
59. isNullable(1)=1
60. isNullable(5)=1
1. import java.sql.*;
2. import java.io.*;
3. class Methods
4. {
5. public static void main(String args[])
6. {
7. try
8. {
9. int x,choice=0;
10. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
11. Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");
12. DatabaseMetaData meta=con.getMetaData();
13. System.out.println("User Name="+meta.getUserName());
14. System.out.println("Url="+meta.getURL());
15. con=DriverManager.getConnection("jdbc:odbc:mydsnorc","scott","tiger");
16. meta=con.getMetaData();
17. System.out.println("User Name="+meta.getUserName());
18. System.out.println("Url="+meta.getURL());
19. }
20. catch(Exception e)
21. {
22. e.printStackTrace();
23. }
24. }
25. }
1. import java.sql.*;
2. import java.io.*;
3. class CallableStatementDemo2
4. {
5. public static void main(String args[])
6. {
7. try
8. {
9. DataInputStream dis=new DataInputStream(System.in);
10. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
11. Connection con=DriverManager.getConnection("jdbc:odbc:javadsn","scott","ti
ger");
1. import java.sql.*;
2. import java.io.*;
3. class CallableStatementDemo1
4. {
5. public static void main(String args[])
6. {
7. try
8. {
9. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
10. Connection con=DriverManager.getConnection("jdbc:odbc:javadsn","scott","ti
ger");
11. CallableStatement cs=con.prepareCall("{call pro()}");
12. System.out.println(cs.execute());
13. PreparedStatement ps=con.prepareStatement("select * from empcopy");
14. ResultSet rs=ps.executeQuery();
15. while(rs.next())
16. {
17. System.out.println(" sal= "+rs.getString("sal"));
18. }
19. }//try
20. catch(Exception e)
21. {
22. System.out.println(e);
23. }
24. }
25. }
26. Pro1.sql
27. create or replace procedure pro() is
28. begin
29. update emppay set basic=basic+1000 where eno='e0001'
30. end;
Jdbc\CallableStatement\CallableStatementDemo3.java
1. import java.sql.*;
2. import java.io.*;
3. class CallableStatementDemo3
4. {
5. public static void main(String args[])
6. {
7. try
8. {
9. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
10. Connection con=DriverManager.getConnection("jdbc:odbc:javadsn","scott","ti
ger");
11. CallableStatement cs=con.prepareCall("{call pro(?)}");
12. cs.setInt(1,7369);
13. cs.registerOutParameter(1,Types.INTEGER);
14. cs.execute();
15. System.out.println(cs.getInt(1));
16. }//try
17. catch(Exception e)
18. {
19. System.out.println(e);
20. }
21. }
22. }
23. Pro3.sql
1. import java.sql.*;
2. import java.io.*;
3. class LobDemo
4. {
5. public static void main(String args[])
6. {
7. /* -------------------------------------------- Writing ------------------------
-------------------- */
8. try
9. {
10. System.out.println("1");
11. FileInputStream fis=new FileInputStream("resume.doc");
12. System.out.println("2");
13. byte b[]=new byte[fis.available()];
14. System.out.println("3");
15. fis.read(b);
16. System.out.println("4");
17. FileInputStream fis1=new FileInputStream("photo.jpg");
18. System.out.println("5");
19. byte b1[]=new byte[fis1.available()];
20. System.out.println("6");
21. fis1.read(b1);
22. System.out.println("7");
23.
24. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
25. System.out.println("8");
26. Connection con=DriverManager.getConnection("jdbc:odbc:javaoracledsn","scot
t","tiger");
27. System.out.println("9");
28. CallableStatement cs=con.prepareCall("{call proc1(?,?,?)}");
29. System.out.println("9a");
30. Clob clob=cs.getClob(2);
31. System.out.println("10");
32. Blob blob=cs.getBlob(3);
33. System.out.println("11");
34.
35. OutputStream os=clob.setAsciiStream(0);
36. System.out.println("15");
37. os.write(b);
38. System.out.println("16");
39.
40. OutputStream os1=blob.setBinaryStream(0);
41. System.out.println("17");
42. os1.write(b1);
43. System.out.println("18");
44.
45. cs.setString(1,"Ram.s");
46. System.out.println("19");
47. cs.setClob(2,clob);
48. System.out.println("20");
49. cs.setBlob(3,blob);
50. cs.execute();
51. /*------------------ Reading -------------------------*/
52. PreparedStatement ps=con.prepareStatement("select * from blobtable");
53. ResultSet rs=ps.executeQuery();
1. import java.sql.*;
2. class ConnectionMethods
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
9. Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");
10. System.out.println(con.getAutoCommit());
11. System.out.println(con.isClosed());
12. con.close();
13. System.out.println(con.isClosed());
14. con=DriverManager.getConnection("jdbc:odbc:mydsn");
15. System.out.println(con.getAutoCommit());
16. PreparedStatement ps=con.prepareStatement("insert into deptmaster values('
d0005','stores','ram')");
17. System.out.println("No of Records Affected="+ps.executeUpdate());
18. ps=con.prepareStatement("select * from deptmaster");
19. ResultSet rs=ps.executeQuery();
20. while (rs.next())
21. {
22. System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(
3));
23. }
24. }
25. catch(Exception e)
26. {
27. System.out.println(e);
28. }
29. }
30. }
31. Output
32. true
33. false
34. true
35. true
36. No of Records Affected=1
37. d0001 production ram prasath
38. d0005 stores ram
39. d0002 purchase siva ram kumar
40. d0003 marketing sathish
41. d0004 accounts ram prasath
1. import java.sql.*;
2. import java.util.*;
3. class ProcessQuery
4. {
5. int columncount=0;
6. int x=0;
7. String query;
8. Vector datavector=new Vector();;
9. Vector columnvector=new Vector();
10. Object getQuery(String query)
11. {
12. Object o=null;
13. this.query=query;
14. defineType();
15. if (x==1)
16. {
17. processSelect();
18. o=(Object)selectAnswer();
19. }
20. else if(x==2)
21. {
22. o=(Object)new Integer(otherAnswer());
23. }
24. return o;
25. }
26.
27. void defineType()
28. {
29. if (query.startsWith("select"))
30. {
31. x=1;
32. }
33. else
34. {
35. x=2;
36. }
37. }
38. void processSelect()
39. {
40. try
41. {
42. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
43. Connection con=DriverManager.getConnection("jdbc:odbc:javadsn","javauser",
"javauser");
44. PreparedStatement ps=con.prepareStatement(query);
45. ResultSet rs=ps.executeQuery();
46. ResultSetMetaData meta=rs.getMetaData();
47. columncount=meta.getColumnCount();
48. for (int i=1;i<=columncount;i++)
49. {
50. columnvector.addElement(meta.getColumnName(i));
51. }
52.
53. while (rs.next())
54. {
55. Vector rowvector=new Vector();
56. for (int i=1;i<=columncount;i++)
57. {
58. rowvector.addElement(rs.getString(i));
59. }//for
60. datavector.addElement(rowvector);
61. }//while
62. }//try
63. catch(Exception e)
64. {
65. System.out.println("From prcoessSelect ="+e);
66. }
67. }//method
68.
69. Vector selectAnswer()
70. {
71. Vector resultvector=new Vector();
72. resultvector.addElement(columnvector);
73. resultvector.addElement(datavector);
74. return (resultvector);
75. }
76.
77. int otherAnswer()
78. {
79. try
80. {
81. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
82. Connection con=DriverManager.getConnection("jdbc:odbc:javadsn","javauser",
"javauser");
Output
1. import javax.swing.*;
2. import java.awt.event.*;
3. import javax.swing.border.*;
4. import java.awt.*;
5. import java.util.*;
6. class GUI extends JFrame implements ActionListener
7. {
8. JPanel northpanel,centerpanel;
9. JButton submitcmd;
10. JTextField text;
11. JScrollPane scrollpane;
12. JTable table;
13. GUI()
14. {
15. super("Data Table");
16. setExtendedState(JFrame.MAXIMIZED_BOTH);
17. northpanel=new JPanel();
18. centerpanel=new JPanel();
19. text=new JTextField(50);
20. submitcmd=new JButton("Submit");
21. register();
22. effectsProvider();
23. layoutProvider();
24. addControls();
25.
26. }
27. void register()
28. {
29. submitcmd.addActionListener(this);
30. }
31. void effectsProvider()
32. {
33. northpanel.setBorder(new LineBorder(Color.blue,10));
34. centerpanel.setBorder(new LineBorder(Color.blue,10));
35. }
36. void layoutProvider()
37. {
38. northpanel.setLayout(new FlowLayout());
39. centerpanel.setLayout(new BorderLayout());
40. setLayout(new BorderLayout());
41. }
42. void addControls()
43. {
44. northpanel.add(text);
45. northpanel.add(submitcmd);
46. add(northpanel,BorderLayout.NORTH);
47. add(centerpanel,BorderLayout.CENTER);
48. show();
49. }
50. public void actionPerformed(ActionEvent ae)
51. {
52. ProcessQuery pq=new ProcessQuery();
53. Object o=pq.getQuery(text.getText());
54. if (o instanceof Vector)
55. {
56. int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
Below program illustrates executeBatch(). This method can be used to execute the group
of queries.
1. import java.sql.*;
2. class ExecuteBatchDemo
3. {
4. void m1()
5. {
6. Connection con=null;
7. try
8. {
9. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
10. con=DriverManager.getConnection("jdbc:odbc:oracledsn","scott","tiger");
11. con.setAutoCommit(false);
12. Statement stmt=con.createStatement();
13. stmt.addBatch("update t1 set amount=amount+100");
14. stmt.addBatch("update t2 set amount=amount+100");
15. stmt.addBatch("update t3 set amount=amount+100");
16. int res[]=stmt.executeBatch();
17. for (int i=0;i<res.length;i++)
18. {
19. System.out.println(res[i]);
20. }
21. con.close();
22. }
23. catch(Exception e)
24. {
25. try
26. {
27. //con.rollback();
28. con.commit();
29. }catch(Exception e1){}
30. e.printStackTrace();
31. }
32. }
33. void m2()
34. {
35. try
36. {
37. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
38. Connection con=DriverManager.getConnection("jdbc:odbc:oracledsn","scott","
tiger");
39. Statement stmt=con.createStatement();
40. stmt.execute("create table t1(amount number(4))");
41. stmt.execute("create table t2(amount number(4))");
42. stmt.execute("create table t3(aamount number(4))");
Below program illustrates BLOB (Binary Large Object), which requires Type3 or Type4
driver. Add classes111.jar in your classpath.
1. import java.sql.*;
2. import java.io.*;
3. import oracle.jdbc.driver.*;
4. import oracle.sql.*;
5. class BLobDemo
6. {
7. public static void main(String args[])
8. {
9. try
10. {
11. Class.forName("oracle.jdbc.driver.OracleDriver");
12. OracleConnection con=(OracleConnection)DriverManager.getConnection("jdbc:o
racle:thin:@localhost:1521:sbit","scott","tiger");
13. con.setAutoCommit(false);
14. // Empty Lob Insertion
15. OraclePreparedStatement ops0=(OraclePreparedStatement)con.prepareStatement
("Insert into map values(?,?)");
16. ops0.setString(1,"India");
17. ops0.setBLOB(2,BLOB.empty_lob());
18. ops0.executeUpdate();
19. // preparing byte[]
20. FileInputStream fis=new FileInputStream("photo.jpg");
21. byte b[]=new byte[fis.available()];
22. fis.read(b);
23. fis.close();
24. // Writing
25. OraclePreparedStatement ops=(OraclePreparedStatement)con.prepareStatement(
"select photo from map for update of photo");
26. OracleResultSet ors=(OracleResultSet)ops.executeQuery();
27. ors.next();
28. BLOB blob=ors.getBLOB(1);
29. OutputStream os=blob.getBinaryOutputStream();
30. os.write(b);
31. ops=(OraclePreparedStatement)con.prepareStatement("update map set photo=?
where country=?");
32. ops.setBLOB(1,blob);
33. ops.setString(2,"India");
34. ops.executeUpdate();
35. ops.close();
36. con.commit();
37. // Reading
38. OraclePreparedStatement opsr=(OraclePreparedStatement)con.prepareStatement
("select * from map");
39. OracleResultSet orsr=(OracleResultSet)opsr.executeQuery();
40. orsr.next();
41. BLOB blobr=orsr.getBLOB("photo");
42. System.out.println(blobr.length());
43. InputStream in=blobr.getBinaryStream();
44. byte br[]=blobr.getBytes(((long)1),((int)blobr.length()));
45. System.out.println(br.length);
46. FileOutputStream fos=new FileOutputStream("newphoto.jpg");
47. fos.write(br);
48. fos.close();
49. opsr.close();
50. con.commit();
51. con.close();
52. }//try
53. catch(Exception e)
54. {
55. e.printStackTrace();
56. }
57. }
58. }
59.
60. O/P
61. Photo.jpg will be stored in oracle table.
62. newphoto.jpg will be created.
Clobdemo.java
1. import java.sql.*;
2. import java.io.*;
3. import oracle.jdbc.driver.*;
4. import oracle.sql.*;
5. class ClobDemo
6. {
7. public static void main(String args[])
8. {
9. try
10. {
11. Class.forName("oracle.jdbc.driver.OracleDriver");
12. OracleConnection con=(OracleConnection)DriverManager.getConnection("jdbc:o
racle:thin:@localhost:1521:sbit","scott","tiger");
13. con.setAutoCommit(false);
14. // Empty Lob Insertion
15. OraclePreparedStatement ops0=(OraclePreparedStatement)con.prepareStatement
("Insert into resumes values(?,?)");
16. ops0.setString(1,"Rama");
17. ops0.setCLOB(2,CLOB.empty_lob());
18. ops0.executeUpdate();
19. // preparing char[]
20. FileInputStream fis=new FileInputStream("Text.txt");
21. FileDescriptor fd=fis.getFD();
22. FileReader fr=new FileReader(fd);
23. int totallen=fis.available();
24. char ch[]=new char[totallen];
25. fr.read(ch,0,ch.length);
26. fr.close();
27. // Writing
60. catch(Exception e)
61. {
62. e.printStackTrace();
63. }
64. }
65. }
66.
67. Output
68. The data of Text.txt will be written into oracle table.
69. The output will be in NewText.txt file.
Chapter 27 - javax.sql
Oracle Connection
To establish the connection with oracle the connection string can be specified
in two ways.
URL - jdbc:oracle:thin:@//localhost:1521/XE
Here we are using thin driver and localhost system. Port no is 1521. XE is the
service name.
URL - jdbc:oracle:thin:@localhost:1521:XE
DataSourceManager.java
1. import oracle.jdbc.pool.OracleDataSource;
2.
3. import com.mysql.cj.jdbc.*;
4.
5. public class DataSourceManager {
6.
7. public static OracleDataSource getOracleDataSource()
8. {
9. try
10. {
11. OracleDataSource dataSource=new OracleDataSource();
12. dataSource.setURL("jdbc:oracle:thin:@localhost:1521/XE");
13. dataSource.setUser("system");
14. dataSource.setPassword("admin");
15. return dataSource;
16.
17. }
18. catch(Exception e)
19. {
20. e.printStackTrace();
21. return null;
22. }
23. }
24.
1. import java.sql.Connection;
2. import java.sql.PreparedStatement;
3. import java.sql.ResultSet;
4.
5. import javax.sql.DataSource;
6.
7. class DataSourceDemo {
8. void printOracleData() {
9. try {
10. System.out.println("***** ORACLE DATA *****");
11. //javax.sql.DataSource is the interface
12. DataSource dataSource = DataSourceManager.getOracleDataSource(
);
13. Connection con = dataSource.getConnection();
14. PreparedStatement ps = con.prepareStatement("select * from dep
t");
15. ResultSet rs = ps.executeQuery();
16. while (rs.next()) {
17. System.out.println(rs.getString(1) + " " + rs.getString(2
) + " " + rs.getString(3));
18. }
19.
20. } catch (Exception e) {
21. e.printStackTrace();
22. }
23.
24. }
25.
26. void printMysqlData() {
27. try {
28. System.out.println("***** MYSQL DATA *****");
29. DataSource dataSource = DataSourceManager.getMysqlDataSource()
;
30. Connection con = dataSource.getConnection();
31. PreparedStatement ps = con.prepareStatement("select * from wor
ld.city");
32. ResultSet rs = ps.executeQuery();
33. while (rs.next()) {
34. System.out.println(rs.getString(1) + " " + rs.getString(2
) + " " + rs.getString(3));
35. }
36.
37. } catch (Exception e) {
38. e.printStackTrace();
39. }
40.
41. }
42.
43. public static void main(String args[]) {
44.
45. DataSourceDemo dataSourceDemo = new DataSourceDemo();
46. dataSourceDemo.printOracleData();
47. dataSourceDemo.printMysqlData();
48. }
49. }
50.
51. ***** ORACLE DATA *****
52. 10 ACCOUNTING NEW YORK
53. 20 RESEARCH DALLAS
54. 30 SALES CHICAGO
55. 40 OPERATIONS BOSTON
56. ***** MYSQL DATA *****
57. 1 Kabul AFG
58. 2 Qandahar AFG
59. 3 Herat AFG
60. 4 Mazar-e-Sharif AFG
61. 5 Amsterdam NLD
GlassFish server
Let's see the how we create the domain using asadmin command.
Here mydomain1 is a name of domain. After entering this command press enter.
Now it will ask the username. Type admin, and press enter. It may be anything
.. for this example .. just we are following this name.
Now it will ask password as like below. Type admin and press enter.
[CN=Chidambaram-PC,OU=GlassFish,O=Oracle Corporation,L=Santa
Clara,ST=California,C=US]
[CN=Chidambaram-PC-instance,OU=GlassFish,O=Oracle Corporation,L=Santa
Clara,ST=California,C=US]
Go to eclipse
Window -> Show View -> Others -> type servers and click servers and click OK
button
In Servers pane, click the link "No servers are available. Click this link to
create a new server" as in above image to select the server
Enter GlassFish location and Java Location, the path in the system.
Now we will get below dialog and we need to enter the below values.
In Name text box enter the domain name just we created as like below
In Domain Path text box, enter the domain path which is available in dos prompt
when we create the domain.
Admin name : admin - We entered the username when we create the domain
Admin password : admin - We entered the password when we create the domain
If any project is needed to add we can add using Add button. Otherwise click
Finish button and we can add the project later.
Then select the server name in the servers pane and right click and select the
Start option in the popup menu.
Type the username and password.. admin and admin. Click Login button.
Collection
Object based collections - Only objects are stored into the collection
Keyvalue based collections - Key value combination like name="rama"; age=23 like
these type of objects wil be stroed in key value based collection.
Legacy Classes
It was introduced with original java release. All legacy classes are synchronized and
thread safe.
Synchronized and thread safe means, only one thread can access the legacy class object
at a time.
Legacy classes are extended the new collections framework to use the new
functionalites with legacy classes.
In below we can see Vector implements List - Vector is the legacy classe and List is
the new collection interface.
Dictionary implements Map - Dictionary is the legacy class and Map is the new
collection interface.
In Legacy classes there are object based classes and Key value based classes as below.
It was released since java 1.2. This is modern framework and high performance
also non synchronized. In Collections Framework, there are Object based
collection interfaces, Object based collection classes, Key value based collection
interfaces and Key value based collection classes
java.util.SortedMap
java.util.NavigableMap
java.util.concurrent.ConcurrentMap
java.util.concurrent.ConcurrentNavigableMap
java.util.SortedMap
java.util.NavigableMap
java.util.concurrent.ConcurrentMap
java.util.concurrent.ConcurrentNavigableMap
We will discuss about each of them to understand more better and based on real
time usage.
We need to take care about this and we will discuss about this in separate
topic.
ArrayList
It is the dynamic Array. Array is the fixed length. ArrayList is a variable length
collection. ArrayList can dynamically increase or decrease in size based on objects
added and removed.
It allows duplicates
Constructors
ArrayList()
1. import java.util.ArrayList;
2. class ArrayListDemo
3. {
4. public static void main(String args[])
5. {
6. //ArrayList object created with a generic way to store String only
7. ArrayList<String> arrayList1=new ArrayList<>();
8. arrayList1.add("One");
9. arrayList1.add("Two");
10. arrayList1.add("Four");
11. //arrayList2 is created and it has all the elements of arrayList1
12. ArrayList<String> arrayList2=new ArrayList<>(arrayList1);
13. System.out.println("arrayList1="+arrayList1);
14. System.out.println("arrayList2="+arrayList2);
15. System.out.println("arrayList1.size()="+arrayList1.size());
16. System.out.println("arrayList2.size()="+arrayList2.size());
17.
18. arrayList1.remove("Two");
19. System.out.println("After Removal from arrayList1");
20. System.out.println("arrayList1.size()="+arrayList1.size());
21. System.out.println("arrayList2.size()="+arrayList2.size());
22. }
23. }
24.
25. Output
26.
27. arrayList1=[One, Two, Four]
28. arrayList2=[One, Two, Four]
29. arrayList1.size()=3
30. arrayList2.size()=3
31. After Removal from arrayList1
32. arrayList1.size()=2
33. arrayList2.size()=3
ListIterator
ListIterator listIterator()
Iterator
Iterator iterator().
Iterator methods
void remove() - remove the element of collection where the iterator cursor is
currently positioned.
Program 1
1. import java.util.ArrayList;
2. import java.util.ListIterator;
3. class ListIteratorDemo
4. {
5. public static void main(String args[])
6. {
7. //ArrayList object created with a generic way to store string only
8. ArrayList<String> arrayList1=new ArrayList<>();
9. arrayList1.add("One");
10. arrayList1.add("Two");
11. arrayList1.add("Four");
12. ListIterator<String> listIterator= arrayList1.listIterator();
13. //add() adds "Five" in 0th index. Because ListIterator cursor now points i
n 0th index
14. listIterator.add("Five");
15. System.out.println("arrayList1="+arrayList1);
16. System.out.println("List Iterator hasNext iteration results");
17. while (listIterator.hasNext())
18. System.out.println(listIterator.next().toString());
19. //add() adds "Six" in last position. Because ListIterator cursor now point
s in last position
20. listIterator.add("Six");
21. System.out.println("arrayList1="+arrayList1);
22. System.out.println("List Iterator hasPrevious iteration results");
23. while (listIterator.hasPrevious())
24. System.out.println(listIterator.previous().toString());
25. }
26. }
Program 2
1. import java.util.*;
2. class ListIteratorDemo
3. {
4. public static void main(String args[])
5. {ArrayList al=new ArrayList();
6. al.add("A");
7. al.add("B"); // duplicate allowed
8. al.add("C");
9. System.out.println(al.add("D"));
10. System.out.println(al.add("D"));
11. System.out.println(al);
12. ListIterator li=al.listIterator();
13. while (li.hasNext())
14. {
15. if (li.nextIndex()==2)
16. {
17. /*
18. set() overwrites the existing data where the iterator cursor is poistioned
19. */
20. li.set("z"); }
21. //next() - returns the element where the cursor is positioned
22. System.out.println("Next ="+li.next());
23. //nextIndex() - returns the index number where the cursor is positioned
24. System.out.println("Next index ="+li.nextIndex());
25. }
26. System.out.println(al);
27. }
28. }
29.
30. Output
31.
32. [A, B, C, D]
33. Next =A
34. Next =1
35. Next =B
36. Next =2
37. Next =C
38. Next =3
39. Next =D
40. Next index =4
41. [A, z, C, D]
LinkedList
LinkedList uses doubly linked list data structure to store the elements. It contains
the nodes where it stores data along with reference link of next node and previous
node.
LinkedList Constructor
public LinkedList()
public LinkedList(Collection c)
1. class LinkedListDemo
2. {
3. public static void main(String args[])
4. {
5. LinkedList ll=new LinkedList();
6. ll.add(5);
7. ll.add(50);
8. System.out.println(ll.add(75));
9. System.out.println(ll.add(75));
10. System.out.println(ll);
11. ll.addFirst(1);
12. System.out.println(ll);
13. ll.addLast(1);
14. System.out.println(ll);
15. System.out.println("Remove First Content of ll ="+ll.removeFirst().toStrin
g());
16. System.out.println("After Removing First ="+ll);
17. ll.removeLast();
18. System.out.println("After Removing Last ="+ll);
19. }//main
20. }//class
LinkedList vs ArrayList
Each one element links with previous and next element. So adding, removing
elements are not working index based.
When you remove or add the element it will change internal structure of
LinkedList.
ArrayList is working index based. Index starts from 0. The size will be growing
or shrinking based on add or remove operations. In below table you can see the
log value of search, delete and add performance between two.
As you see, the search and add functions of ArrayList are good performance than
LinkedList. Search of LinkedList is good performance than ArrayList. Both
allow duplicate and nulls.
Allow
Class Search Delete Add Allow Nulls
Duplicates
LinkedHashSet
LinkedHashSet constructors
LinkedHashSet()
Constructs a linked hash set with the default initial capacity (16) and load
factor (0.75).
LinkedHashSet(Collection c)
Constructs a new linked hash set with the same elements as the specified
collection.
LinkedHashSet(int initialCapacity)
Constructs a new linked hash set with the specified initial capacity and the
default load factor (0.75).
Constructs a linked hash set with the specified initial capacity and load
factor.
1. import java.util.*;
2. class LinkedHashSetDemo
3. {
4. public static void main(String args[])
5. {
6. LinkedHashSet linkedHashSet=new LinkedHashSet();
7. linkedHashSet.add("a");
8. linkedHashSet.add("b");
9. linkedHashSet.add("e");
10. linkedHashSet.add("d");
11. //LinkedHashSet doen't allow duplicates
12. System.out.println("linkedHashSet.add(\"c\") added c first time ="+linkedH
ashSet.add("c"));
13. System.out.println("linkedHashSet.add(\"c\") added c second time ="+linked
HashSet.add("c"));
14. System.out.println("***** linkedHashSet *****");
15. System.out.println(linkedHashSet);
16. //HashSet object created with the initial elements of linkedHashSet
17. HashSet hashSet1=new HashSet(linkedHashSet);
18. /*
19. * HashSet object created with assigning linkedHashSet
Hashtable
This class implements a hash table, which maps keys to values. Any non-
null object can be used as a key or as a value.
Hashtable Constructors
Hashtable()
Constructs a new, empty hashtable with a default initial capacity (11) and load factor
(0.75).
Hashtable(int initialCapacity)
Constructs a new, empty hashtable with the specified initial capacity and default load
factor (0.75).
Constructs a new, empty hashtable with the specified initial capacity and the
specified load factor.
Constructs a new hashtable with the same mappings as the given Map.
HashSet
HashSet extends AbstractSet and implements the Set interface. It creates a collection
that uses a hash table for storage.
HashSet(int capacity, float fillRatio) - creates HashSet with specified capacity and
fillRatio.
The fill ratio must be between 0.0 and 1.0. Default value 0.75. It determines the new
capacity when Hashtable reaches its capacity
HashSet does not have any methods and it can use the methods from its super classes
and interfaces
PriorityQueue
PriorityQueue extends AbstractQueue
AbstractQueue implements Queue and Collection. So we can use Queue and Collection and
AbstractQueue methods here.
If we prints or lists the elements it will not print the order as we inserted.
Instead we can use peek() or poll() to get the head of the queue.
Let's see the below program and inline comments to understand each method.
1. import java.util.Arrays;
2. import java.util.PriorityQueue;
3.
4. class PriorityQueueDemo
5. {
6. public static void main(String args[])
7. {
8. PriorityQueue<Integer> pq=new PriorityQueue<>();
TreeSet
TreeSet implements NavigableSet and stores the objects in ascening order. Its
performance of storage and retrieval are quite fast.
By using Comparator we can define the order. Let's see the examples and constructors.
TreeSet Constructors
TreeSet()
TreeSet(Collection c)
TreeSet(SortedSet s)
Constructs a new tree set containing the same elements and using the same ordering as
the specified sorted set.
TreeSet(Comparator comparator)
Constructs a new, empty tree set. By default TreeSet makes ascedning order. By using
this constructor, we can change the logic like descending by using Comparator.
Wheneven the objects are stored in TreeSet, the compare method will be called by
runtime by passing the two objects.
1. import java.util.*;
2. class ComparatorDemo implements Comparator
3. {
4. int val=0;
5. //runtime calls this method automatically.
6. public int compare(Object ob1,Object ob2)
7. {
8. String str1=(String)ob1;
9. String str2=(String)ob2;
10. /*
11. compareTo() is String class method returns ascii different between str1 an
d str2
12. str1.compareTo(str2) - To make ascending
13. str2.compareTo(str1) - To make descending
14. Nothing else we need to do; returning value is enough and runtime takes ca
re to make the order in TreeSet.
15. */
16. val=str1.compareTo(str2);
17. return val;
18. }
19. }
20. class TreeSetDemo
21. {
22. public static void main(String args[])
23. {
24. ComparatorDemo cd=new ComparatorDemo();
25. /*
HashSet No Yes
LinkedHashSet No Yes
TreeSet No No
PriorityQueue Yes No
HashMap
HashMap extends AbstractMap implement Map
Constructors
HashMap()
Constructs an empty HashMap with the default initial capacity (16) and the default
load factor (0.75).
HashMap(int initialCapacity)
Constructs an empty HashMap with the specified initial capacity and the default load
factor (0.75).
Constructs an empty HashMap with the specified initial capacity and load factor.
When the number of entries in the hash table exceeds the product of the load factor
and the current capacity will be the measure to increase the size
HashMap is used to store and retrieve key value pairs. Allows null key and null value.
Internally it uses hashtable based on hashing principle to store elements. HashMap
stores internally key value pair as a Map.Entry object. Entry is the sub class of Map.
Each Map.Entry object is considered as a Node.
When put(key,value) is called to store key value pair in HashMap, the int hashCode()
method is called for key.
HashMap stores key values in hash table as like below and the default capacity is 16,
ranges 0 to 15. In the hash table each one storage can be known as bucket.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
When put(key,value) is called to store key value pair in HashMap, the Map.Entry will
be mapped with Key's hashcode. Hashcode is the unique identifer for each one object
created by runtime.
Here we need to understand that to minmize the storage of lengthy hash code, HashMap
finds the hash. Hash is nothing but it is also the integer and it will be act as the
identity for each node.
Now HashMap puts the node object in hashtable. So it means one bucket will have one
node. Each one node, LinkedList is used to store the elements and each one element is
the Map.Entry object.
In continuous put() call, the same flow is working to store the nodes.
If sometimes hash value is duplicated the same bucket will be used to store the nodes
and the next of node points to the next node.
The get() will be used retrieve the value of key. get(key) returns corresponding
value.
get() finds the hash for key and based on the hash value it checks the bucket. If
node's hash and the key's hash are matched then the value will be returned.
In some cases if one bucket has more than one nodes then the equals() will be called
to find out the correct key.
In Java 8, HashMap replaces linked list with a binary tree when the number of elements
in a bucket reaches certain threshold to ensure a performance. Based on this change
the below benfit we will have.
Typically binary tree has the branches left and right side , where hashcode is
used as a branching variable. If there are two different hash in the same
bucket, one is considered bigger and goes to the right of the tree and other
one to the left. Above changes ensure search performance of O(1) instead the
O(log(n)) in worst case scenarios.
1. import java.util.HashMap;
2. import java.util.Iterator;
3. import java.util.Map;
4.
5. public class HashMapDemo {
6. public static void main(String args[])
7. {
8. HashMap<String,String> hashMap = new HashMap<>();
9. hashMap.put("name","Rama");
10. hashMap.put("age","27");
11. hashMap.put("salary","35000");
12. /*
13. *Way 1 to list the HashMap
14. *hashMap.keySet() -
returns Set interface object (keys of HashMap) the iterator() of Set class retu
rns Iterator object
15. */
16. Iterator<String> iterator=hashMap.keySet().iterator();
17. //iterator.hasNext() - returns true if next element can be read
49.
50. key=name value=Rama
51. key=salary value=35000
52. key=age value=27
53. key=name value=Rama
54. key=salary value=35000
55. key=age value=27
TreeMap
TreeMap extends AbstractMap implements NavigableMap
TreeMap provides the result in sorted order in asceding by using keys. We can change
the order using Comparator.
1. import java.util.Comparator;
2. import java.util.TreeMap;
3.
4. class CompareDemo implements Comparator
5. {
6. public int compare(Object ob1,Object ob2)
7. {
8. String st1=(String)ob1;
9. String st2=(String)ob2;
10. // For Ascending
11. //return (st1.compareTo(st2));
12. //// For Descending
13. return (st1.compareTo(st2));
14. }
15. }
16. class TreeMapDemo
17. {
18. public static void main(String args[])
19. {
20. TreeMap<String,Double> treeMap=new TreeMap<>(new CompareDemo());
21. treeMap.put("Ragav",new Double(1000.00));
22. treeMap.put("Rajesh",new Double(1000.00));
23. treeMap.put("Amir",new Double(1000.00));
24. treeMap.put("Yashota",new Double(1000.00));
25. treeMap.put("Sankar",new Double(1000.00));
26. treeMap.put("Balu",new Double(1000.00));
27. System.out.println(treeMap);
28. }
29. }
30.
31. Output
32.
33. {Amir=1000.0, Balu=1000.0, Ragav=1000.0, Rajesh=1000.0, Sankar=1000.0, Yas
hota=1000.0}
LinkedHashMap
LinkedHashMap()
Constructs an empty instance with the default initial capacity (16) and load factor
(0.75).
LinkedHashMap(int initialCapacity)
Constructs an empty instance with the specified initial capacity and a default load
factor (0.75).
LinkedHashMap(Map m)
1. import java.util.*;
2. class LinkedHashMapDemo
3. {
4. public static void main(String args[])
5. {
6. LinkedHashMap<String,Double> linkedHashMap=new LinkedHashMap<String,Double>();
7. linkedHashMap.put("Ragav",new Double(1000.00));
8. linkedHashMap.put("Rajesh",new Double(1000.00));
9. linkedHashMap.put("Amir",new Double(1000.00));
10. linkedHashMap.put("Yashota",new Double(1000.00));
11. linkedHashMap.put("Sankar",new Double(1000.00));
12. linkedHashMap.put("Balu",new Double(1000.00));
13.
14. Iterator it=linkedHashMap.keySet().iterator();
15. while (it.hasNext())
16. {
17. Object o=it.next();
18. System.out.println(o.toString()+" : "+linkedHashMap.get(o));
19. }
20.
21. }
22. }
23.
24.
25. Output :
26.
27. Ragav : 1000.0
28. Rajesh : 1000.0
29. Amir : 1000.0
30. Yashota : 1000.0
31. Sankar : 1000.0
32. Balu : 1000.0
IdentityHashMap
The HashMap equals method checks value comparision between two objects. In
contrary IdentityHashMap checks the reference equality between object not the
values.
IdentityHashMap constructors
IdentityHashMap()
Constructs a new, empty identity hash map with a default expected maximum size (21).
IdentityHashMap(int expectedMaxSize)
Constructs a new, empty map with the specified expected maximum size.
IdentityHashMap(Map m)
Constructs a new identity hash map with the initial values from m.
1. import java.util.IdentityHashMap;
2. class IdentityHashMapDemo
3. {
SortedMap
SortedMap is the interface it comes with some interesting useful methods such
as below
SortedMapMethodsDemo
1. /*
2. SortedMap headMap(Object key)
3. Returns values lessthan (backwards) of key
4. SortedMap tailMap(Object key)
5. Returns values greater than or equal to (backwards) of key
Now we will discuss about legacy classes in java.util. We also discussed like that
legacy classes were introduced in initial java release and modern java collection
frame work were introduced in java 1.2. So far we discussed modern java collection
framework.
Following classes are legacy clasess. Hope you remember the below points we discussed
early in below chapters.
Legacy classes are synchronized and thread safe also implements modern collections
framework.
Vector
Stack
Hashtable
Properties
Vector
The Vector class is a legacy class available since java 1.0. It is synchronized
class. It maintains internal data array to manage objects and it can grow or
shrink as per added / removed elements in vector. Since java 1.2 Vector
implements List. So we can use the List methods in Vector also.
Constructs an empty vector with the specified initial capacity and capacity
increment. Capcity increment defines how much size needs to be resized when its
size reached the capacity
1. import java.util.Vector;
2. public class VectorDemo1 {
3. public static void main(String ar[]) {
4. /*
5. * In below you can see Vector<Object> correct... in <> diamond operator
.
6. * It means we can add any object in Vector
7. */
8. Vector<Object> v = new Vector<>();
9. /*
10. * Vector's default capacity is zero.
11. * To define the capacity at the time of startup
12. */
13. v.ensureCapacity(20);
14. System.out.println(v.capacity());
15. System.out.println(v.isEmpty());
16. System.out.println(v.size());
17. v.addElement("india");
18. v.addElement("welcome");
19. // add(Object obj) - method of List
20. v.add(100);
21. // elementAt(int index) - retrieve the element at given index
22. System.out.println(v.elementAt(1));
23. // contains() - searches given element and returns true if found
24. System.out.println(v.contains("welcome"));
25. Object ob[] = new Object[v.size()];
26. // copy the entire content into ob
27. v.copyInto(ob);
28. for (int i = 0; i < ob.length; i++) {
29. System.out.println(ob[i]);
30. }
31. // setSize() -
truncates only keeps given size of the elements and remove remaining items
32. // remaining items
33. v.setSize(2);
34. System.out.println("***************** vector after resizing ******
******** ");
35. System.out.println(v);
36. }
37. }
38.
39. Output
40.
41. 20
42. true
43. 0
44. welcome
45. true
46. india
47. welcome
48. 100
49. ***************** vector after resizing **************
50. [india, welcome]
Stack
Stack Constructors
boolean empty()
Object peek()
Looks at the object at the top of this stack without removing it from the
stack.
Object pop()
Removes the object at the top of this stack and returns that object as the
value of this function.
Object search(Object o)
1. import java.util.Stack;
2.
3. class StackDemo
4. {
5. public static void main(String args[])
6. {
7. //Stack object created to add any type of elements
8. Stack<Object> st1=new Stack<>();
9. //push() - push the item on top of the stack
10. st1.push("1");
11. st1.push("2");
12. st1.push("3");
13. st1.push("4");
14. st1.push("5");
15. //duplicate allowed in stack
16. st1.push("5");
17. st1.push("java");
18. //search() - returns 1 based position
19. System.out.println("st1.search(\"3\")="+st1.search("3"));
20. //Returns top of the stack without removing
21. System.out.println("Peek:"+(String)st1.peek());
22. //Returns top of the stack with removing
23. System.out.println("Pop:"+(String)st1.pop());
24. //null allowed in stack
25. st1.push(null);
26.
27. /* Vector class method can be used with Stack
28. * insertElementAt(Object,indexPos)
29. */
30. st1.insertElementAt("java 9",3);
31. System.out.println("***** stack after insertion *****");
32. System.out.println(st1);
33.
34. }//main
35. }//class
36.
37. Output
38.
39. st1.search("3")=5
40. Peek:java
41. Pop:java
42. ***** stack after insertion *****
43. [1, 2, 3, java 9, 4, 5, 5, null]
44.
Hashtable
Hashtable is a legacy class since Java 1.0 and it doesn't allow null key and
null value. Since Java 1.2 it implements Map interface to add the functionality
of new collection frame work.
Constructors
Hashtable()
Constructs a new, empty hashtable with a default initial capacity (11) and load
factor (0.75).
Hashtable(int initialCapacity)
Constructs a new, empty hashtable with the specified initial capacity and
default load factor (0.75).
Constructs a new, empty hashtable with the specified initial capacity and the
specified load factor.
Hashtable(Map t)
1. import java.util.*;
2. import java.io.*;
3. class HashtableDemo
4. {
5. String name;
6. Double salary;
7. String choice;
8. Hashtable ht=new Hashtable();
9. void getValue()
10. {
11. String key;
12. double value=0;
13. try
14. {
15. DataInputStream dis=new DataInputStream(System.in);
16. do
17. {
18. System.out.println("Enter the Name");
19. name=dis.readLine();
20. System.out.println("Enter the Salary");
21. salary=new Double(dis.readLine());
22. ht.put(name,salary);
23. System.out.println("Add More");
24. choice=dis.readLine();
25. }while(choice.equalsIgnoreCase("yes"));
26. Set set=ht.keySet();
27. Iterator it=set.iterator();
28. System.out.println("Key \t\t Value");
29. while (it.hasNext())
30. {
31. key=(String)it.next();
32. System.out.print(key);
33. System.out.println(((Double)ht.get(key)).doubleValue());
34. }
35. Enumeration e=ht.keys();
36. System.out.println("Key \t\t Value");
37. while (e.hasMoreElements())
38. {
39. key=(String)e.nextElement();
40. System.out.print(key);
41. System.out.println(((Double)ht.get(key)).doubleValue());
42. }
43. System.out.println("All values in hash table");
44. System.out.println(ht.toString());
45. double basic=((Double)ht.get("one")).doubleValue();
46. System.out.println("basic of one is="+basic);
47. }//try
48. catch(Exception e){}
49. }//method
50. void removeValue(String name)
51. {
52. System.out.println("Removed Object ="+ht.remove(name));
53. System.out.println("Size of Collection ="+ht.size());
54. }
55. public static void main(String args[])
56. {
57. try
58. {
59. String tname="";
60. String choice;
61. DataInputStream dis=new DataInputStream(System.in);
62. HashtableDemo htd=new HashtableDemo();
63. htd.getValue();
64. do
65. {
66. System.out.println("Enter The Name to Remove");
67. tname=dis.readLine();
68. htd.removeValue(tname);
69. System.out.println("Enter Choice to remove");
70. choice=dis.readLine();
71. }while(choice.equalsIgnoreCase("yes"));
72. }//try
73. catch(Exception e){}
74. }//main
75. }//class
76.
77. Output
78.
79. H:\Util\Hashtable>java HashtableDemo
80. Enter the Name
81. one
82. Enter the Salary
83. 10000
84. Add More
85. yes
86. Enter the Name
87. two
88. Enter the Salary
89. 20000
90. Add More
91. yes
92. Enter the Name
93. three
94. Enter the Salary
95. 30000
96. Add More
97. no
98. Key Value
99. two20000.0
100. one10000.0
101. three30000.0
102. Key Value
103. two20000.0
104. one10000.0
105. three30000.0
106. All values in hash table
107. {two=20000.0, one=10000.0, three=30000.
108. basic of one is=10000.0
109. Enter The Name to Remove
110. two
111. Removed Object =20000.0
112. Size of Collection =2
113. Enter Choice to remove
114. yes
115. Enter The Name to Remove
116. one
117. Removed Object =10000.0
118. Size of Collection =1
119. Enter Choice to remove
120. no
Properties
In addition it supports io stream to get the properties from file and store
properties in file.
Constructors
Properties()
Properties(Properties defaults)
1. import java.io.FileInputStream;
2. import java.io.FileOutputStream;
3. import java.util.*;
4. class PropertyDemo1
5. {
6. public static void main(String args[])
7. {
8. try
9. {
10. Properties p=new Properties();
11. //Add key value in property object
12. p.setProperty("username", "user1");
13. p.setProperty("password", "pass1PASS@9143");
14.
15.
16. System.out.println("p.getProperty(\"username\")="+p.getProperty("username"
));
17.
18. /* To store properties(from object p) in file and
19. * retrieve the same from file and store in property object (to p1 object)
20. */
21. FileOutputStream fos=new FileOutputStream("properties1.txt");
22. p.store(fos,"Company");
23. FileInputStream fis=new FileInputStream("properties1.txt");
24. Properties p1=new Properties();
25. p1.load(fis);
26. System.out.println("*** p1 *****");
27. System.out.println(p1);
28.
29. /*
30. * Store to xml file from properties object and
64.
65. p.getProperty("username")=user1
66. *** p1 *****
67. {password=pass1PASS@9143, username=user1}
68. *** p2 *****
69. {password=pass1PASS@9143, username=user1}
70. *** p3 *****
71. {datasource=oracle}
72. p3.getProperty("username")=user1
73.
java.util.Date class
Example
System.out.println(date);
Output
java.text.SimpleDateFormat class
Example
sdf.format(date);
Output
29-DEC-07
1. import java.util.*;
2. import java.text.*;
3. class DateDemo
4. {
5. public static void main(String args[])
6. {
7. Date date=new Date();
8. System.out.println("Un Formatted Date="+date);
9. SimpleDateFormat sdf; // Reference
10. sdf=new SimpleDateFormat("dd/MMMM/yyyy");
11. System.out.println("dd/MMMM/yyyy==>"+sdf.format(date));
12. sdf=new SimpleDateFormat("dd/MMM/yyyy");
13. System.out.println("dd/MMM/yyyy==>"+sdf.format(date));
14. sdf=new SimpleDateFormat("dd/MM/yyyy");
15. System.out.println("dd/MM/yyyy==>"+sdf.format(date));
16. sdf=new SimpleDateFormat("dd/MM/yy");
17. System.out.println("dd/MM/yy==>"+sdf.format(date));
18. sdf=new SimpleDateFormat("d/MM/yy");
19. System.out.println("d/MM/yy==>"+sdf.format(date));
20. sdf=new SimpleDateFormat("d-MM-yy");
21. System.out.println("d-MM-yy==>"+sdf.format(date));
22. sdf=new SimpleDateFormat("hh:mm:ss");
23. System.out.println("hh:mm:ss==>"+sdf.format(date));
24. sdf=new SimpleDateFormat("dd");
25. System.out.println("dd==>"+sdf.format(date));
26. sdf=new SimpleDateFormat("MMMM");
27. System.out.println("MMMM==>"+sdf.format(date));
28. sdf=new SimpleDateFormat("yyyy");
29. System.out.println("yyyy==>"+sdf.format(date));
30. sdf=new SimpleDateFormat("hh");
31. System.out.println("hh==>"+sdf.format(date));
32. sdf=new SimpleDateFormat("mm");
33. System.out.println("mm==>"+sdf.format(date));
java.util.Arrays
This class comes with various methods to work with array such as sorting, searching.
1. import java.util.*;
2. class ArraysDemo
3. {
4. public static void main(String args[])
5. {
6. int a[]={1,2,3,4,5,6,7,8,9,10};
7. /*
8. binarySearch() is the static method. First argument is the array and second argu
ment is the element to be searched.
9. Returns index position of second argument.*/
10. System.out.println("Arrays.binarySearch(a,3)="+Arrays.binarySearch(a,3));
28. Arrays.sort(str,1,4);
29. System.out.println("================ After Sort ======================");
Formatter
Formatter class provides format method to format the string as like C language printf.
Let's see with example program and inline comments to understand more better.
1. import java.util.*;
2. class FormatterDemo
3. {
4. public static void main(String args[])
5. {
6. //Formatter object creation
7. Formatter fmt=new Formatter();
8. /*
9. As per the number of format specified in the first argument, the remaining argum
ent should be given.
10. For example In below example
11. %s -> "The Number Integer is"
12. %d -> 10
13. %S -> " and Float is " -
%S is capital S, the output in below S.o.p prints AND FLOAT IS.. correct
14. %f->6.7
15. */
16. fmt.format("%s %d %S %f","The Number Integer is",10," and Float is ",6.7);
17. System.out.println(fmt);
18. //o.p -> The Number Integer is 10 AND FLOAT IS 6.700000
19.
20.
21. /* Dispaly Current Time */
22. Formatter fmt1=new Formatter();
23. fmt1.format("%tr",cal);
24. System.out.println("Time is ="+fmt1);
25. //o.p -> Time is =08:36:26 PM
26.
27.
62.
63. Formatter fmt6=new Formatter();
64. fmt6.format("%,.2f",1234255234.676575);
65. System.out.println(fmt6);
66. //o.p -> 1,234,255,234.68
67.
68. }
69. }
1. import java.util.*;
2. class FormatterDemo1
3. {
4. public static void main(String args[])
5. {
6. //Calendar object creation.
7. Calendar cal=Calendar.getInstance();
8. Formatter fmt;
9. fmt=new Formatter();
10. fmt.format("%s %ta","Abbreviated WeekDay Name ",cal);
11. System.out.println(fmt);
12. fmt=new Formatter();
13. fmt.format("%s %tA","Full Week Day Name ",cal);
14. System.out.println(fmt);
15. fmt=new Formatter();
16. fmt.format("%s %tb","Abbreviated Month Name ",cal);
17. System.out.println(fmt);
18. fmt=new Formatter();
19. fmt.format("%s %tB","Full Month Name ",cal);
20. System.out.println(fmt);
21. fmt=new Formatter();
22. fmt.format("%s %tc","Date and Time with time zone ",cal);
23. System.out.println(fmt);
24. fmt=new Formatter();
60.
61. fmt.format("%s %tk","Hour in Railway Time",cal);
62. System.out.println(fmt);
63. fmt=new Formatter();
64.
65. fmt.format("%s %tL","Millisecond",cal);
66. System.out.println(fmt);
67. fmt=new Formatter();
68.
69. fmt.format("%s %tM","Minute",cal);
70. System.out.println(fmt);
71. fmt=new Formatter();
72.
73. fmt.format("%s %tN","NanoSecond",cal);
74. System.out.println(fmt);
75. fmt=new Formatter();
76.
77. fmt.format("%s %tP","AM or PM",cal);
78. System.out.println(fmt);
79. fmt=new Formatter();
80.
81. fmt.format("%s %tp","am or pm",cal);
82. System.out.println(fmt);
83. fmt=new Formatter();
84.
85. fmt.format("%s %tr","hour:minute 12 hour",cal);
86. System.out.println(fmt);
87. fmt=new Formatter();
88.
89. fmt.format("%s %tR","hour:minute 24 hour format",cal);
90. System.out.println(fmt);
91. fmt=new Formatter();
92.
93. fmt.format("%s %tS","Seconds",cal);
94. System.out.println(fmt);
Observer
Observable
Observable is the class, and to notify the state changes of observable object we can
use this concept.
/*
*/
setChanged();
notfiyObservers(Object ob);
// add the code. The code will be invoked by run time when you call readFile().
Observable.addObserver(Observer);
Watcher is user defined class and it will act as Observer, because it implements
Observer interface and overrides update().
We register Observer for Observable using the addObserver().. hope you got the point.
student.print() invokes print(). In print() we added below two lines to invoke the
observer
setChanged();
notifyObservers(new Integer(count));
1. import java.util.Observable;
2. import java.util.Observer;
3.
4. class Watcher implements Observer
5. {
6. /*
7. * update() will be called whenever print() Student class is invoked
8. * parameter ob would be the Student object and we can cast
9. * ex: Student student = (Student)ob;
10. * paramter o would be the value we passed in notifyObservers()
11. */
12. public void update(Observable ob,Object o)
13. {
14. System.out.println("I am Update:"+(((Integer)o).intValue()));
15. }
16. }
17.
18. class ObserverDemo
19. {
20. public static void main(String args[])
21. {
22. //Observer
23. Watcher watcher=new Watcher();
24. //Observable
25. Student student=new Student();
26. //observer and observable registration using addObserver()
27. student.addObserver(watcher);
28. //print() invoked, which automatically triggers update() of observer.
29. student.print();
30. }
31. }
32.
33.
34. class Student extends Observable
35. {
36. int count=10;
37. void print()
38. {
39. /*
40. * Below two method setChanged() and
41. * notifyObservers() must be called to trigger observer whenever obser
vable is invoked
42. * count will be parameter to update() of observer
43. */
44. setChanged();
45. notifyObservers(new Integer(count));
46. System.out.println("I am Student Class");
47. count++;
48. }
49. }
50.
51. Output :
52.
53. I am Update:10
54. I am Student Class
Random
Random is the java.util package class to generate the random numbers. The below
example program creates Random class object and prints random number using Random
class methods.
Let's see the below sample program, which prints random number within for loop to
understand Random object generates different output for each call.
1. import java.util.Random;
2.
3. class RandomDemo extends Random
4. {
5.
6. public static void main(String args[])
7. {
8. Random r1=new Random();
9. //nextInt() returns any one integer number.
10. System.out.println("***** r1.nextInt() *****");
11. for (int i=0;i<3;i++)
12. System.out.println(r1.nextInt());
13.
14. //nextInt() returns any one integer number within 100
15. System.out.println(" ***** r1.nextInt(100) *****");
16. for (int i=0;i<3;i++)
17. System.out.println(r1.nextInt(100));
18.
19. //nextDouble() returns any one Double number within double range
20. System.out.println("**** r1.nextDouble() *****");
21. for (int i=0;i<3;i++)
22. System.out.println(r1.nextDouble());
23.
24. //nextBoolean() returns any one boolean value
25. System.out.println("***** r1.nextBoolean() *****");
26. for (int i=0;i<3;i++)
27. System.out.println(r1.nextBoolean());
28.
29. //nextBytes() fills byte[] with any of the byte range
30. System.out.println("***** r1.nextBytes(byte[]) *****");
31. byte b[]=new byte[20];
32. r1.nextBytes(b);
33. for (int i=0;i<3;i++)
34. System.out.println(b[i]);
35.
36. }
37. }
38.
39. Output
40.
41.
42. ***** r1.nextInt() *****
43. 1500743010
44. 1048473621
45. 1863031333
46. ***** r1.nextInt(100) *****
47. 66
48. 59
49. 92
50. **** r1.nextDouble() *****
51. 0.30520999537245574
52. 0.2494990569479918
53. 0.9582452668807597
54. ***** r1.nextBoolean() *****
55. true
56. false
57. true
58. ***** r1.nextBytes(byte[]) *****
59. 1
60. -26
61. -17
62.
Scanner
Scanner parses from the given source using delimiters. It breaks its input into
tokens using a delimiters, default delimiter is whitespace.
Constructor
Scanner(java.io.File source)
By using this constructor we can create Scanner object with connecting one
file.
Example:
Scanner(java.io.InputStream source)
Example #1
Example #2
Example #3
Scanner(java.lang.Readable source)
Readable is the interface, so we can give the sub class of Readbale for exampole
FileReader
CharArrayReader
Scanner(java.lang.String source)
Here string is the source of Scanner. It means reading from scanner really reads from
any String source.
Methods
boolean hasNext()
This method reads next token from source(tokens are identified by using space or
enter) and returns true if next token is available.
boolean hasNextXxx()
To check the data type of token. Here Xxx is the data type like int, float, etc..
xxx nextXxx()
String next()
1. import java.io.FileReader;
2. import java.util.Scanner;
3.
4. /* Parse one file into token with its data type */
5.
6. class FileReaderDemo
7. {
8. public static void main(String args[])
9. {
10. try
11. {
12. FileReader fr=new FileReader("file.txt");
13. Scanner in=new Scanner(fr);
14. in.useDelimiter("-"); // default delimiter is space
15. while (in.hasNext()) // If token found returns true
16. {
17. if (in.hasNextInt())
18. {
19. System.out.println("Integer :"+in.nextInt());
20. }
56. file.txt
57.
58. 12-true-23-35.5-false-56.78-done-afterdone-12-a
StringTokenizer
The string tokenizer class is used to break a string into tokens using
delimiters.
StringTokenizer constructors
StringTokenizer(String str)
A token is returned by taking a substring of the string that was used to create
the StringTokenizer object.
The following is one example of the use of the tokenizer. The code:
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
this
is
test
The following example illustrates how the String.split method can be used to
break up a string into its basic tokens:
System.out.println(result[x]);
this
is
test
1. import java.util.StringTokenizer;
2.
3. class StringTokenizerDemo
4. {
5. public static void main(String args[])
6. {
7. String str="Name:Rama:Age:60:Salary:7500";
8. StringTokenizer st=new StringTokenizer(str,":");
9. System.out.println("No of Tokens in str="+st.countTokens());
10. while (st.hasMoreElements())
11. {
12. System.out.println(st.nextElement());
13. }
14. }
15. }
16.
17.
18. Output
19.
20. No of Tokens in str=6
21. Name
22. Rama
23. Age
24. 60
25. Salary
26. 7500
1. import java.util.StringTokenizer;
2.
3. class StringTokenizerDemo1
4. {
5. public static void main(String args[])
6. {
7. String str="Name:Rama:seetha;Age:60:70;Salary:7500:354656";
8. StringTokenizer st=new StringTokenizer(str,";");
9. System.out.println(st.toString());
10. System.out.println("No of Tokens in str="+st.countTokens());
11. while (st.hasMoreTokens())
12. {
13. String inner=st.nextToken();
14. StringTokenizer st1=new StringTokenizer(inner,":");
15. System.out.print(st1.nextToken()+" ");
16. System.out.println(st1.nextToken());
17. System.out.println(st1.nextToken());
18. }
19. }
20. }
1. import java.util.StringTokenizer;
2. class StringTokenizerDemo2
3. {
4. public static void main(String args[])
5. {
6. String str="Hello Java Guys - Welcome";
7. /*
8. The below constructor has thre arguments
9. str -> source string
10. - -> delimiter
11. true -> true delim returns as the token. default is false.
12. StringTokenizer st=new StringTokenizer(str,"-",true);
13. while(st.hasMoreTokens())
14. System.out.println(st.nextToken());
15. }//method
16. }//class
17.
18. Output
19.
20. Hello Java Guys
21. -
22. Welcome
The package is used to accomplish the fundamental needs of the Java programming
language.
java.lang.Object is the implicit super class for all the java classes
The wrapper classes Boolean, Character, Integer, Long, Float, and Double serve
the functionality for data of our application.
Throwable is the super class of Exception and Error and these are useful to
manipulate exception handling mechanisms.
java.lang is the default package. It means we need not to import this package in our
program to use the classes of this package.
java.lang.Number
Below program illustrates Number class methods, which just returns the requried
data type primitive value.
1. class MethodsOfNumberClass
2. {
3. public static void main(String args[])
4. {
5. System.out.println("Integer");
6. Integer i=new Integer(200);
7. System.out.println("int "+i.intValue());
8. System.out.println("float "+i.floatValue());
9. System.out.println("byte "+i.byteValue());
10. System.out.println("long "+i.longValue());
11. System.out.println("double "+i.doubleValue());
12. System.out.println("short "+i.shortValue());
13. System.out.println("-------------------------------");
14. System.out.println("Long");
15. Long l=new Long(4566);
16. System.out.println("int "+l.intValue());
17. System.out.println("float "+l.floatValue());
18. System.out.println("byte "+l.byteValue());
19. System.out.println("long "+l.longValue());
20. System.out.println("double "+l.doubleValue());
21. System.out.println("short "+l.shortValue());
22. System.out.println("-------------------------------");
23. System.out.println("Byte");
24. Byte b=new Byte((byte)67);
25. System.out.println("int "+b.intValue());
26. System.out.println("float "+b.floatValue());
27. System.out.println("byte "+b.byteValue());
28. System.out.println("long "+b.longValue());
29. System.out.println("double "+b.doubleValue());
30. System.out.println("short "+b.shortValue());
31. System.out.println("-------------------------------");
32. System.out.println("Short");
33. Short s=new Short((short)457);
34. System.out.println("int "+s.intValue());
35. System.out.println("float "+s.floatValue());
36. System.out.println("byte "+s.byteValue());
37. System.out.println("long "+s.longValue());
38. System.out.println("double "+s.doubleValue());
Double class
Double Constructors
Double(double)
1. class DoubleConstructorsDemo
2. {
3. public static void main(String args[])
4. {
5. Double d1=new Double(6);
6. Double d2=new Double("6.4");
7. System.out.println("d1="+d1);
8. System.out.println("d2="+d2);
9. }
10. }
11.
12. Output
13.
14. d1=6.0
15. d2=6.4
1. class DoubleFieldsDemo
2. {
3. public static void main(String args[])
4. {
5. System.out.println("Double.MAX_VALUE="+Double.MAX_VALUE);
6. System.out.println("Double.MIN_VALUE="+Double.MIN_VALUE);
7. System.out.println("Double.SIZE="+Double.SIZE);
8. System.out.println("Double.TYPE="+Double.TYPE);
9. System.out.println("Double.POSITIVE_INFINITY="+Double.POSITIVE_INFINITY);
10. System.out.println("Double.NEGATIVE_INFINITY="+Double.NEGATIVE_INFINITY);
11. System.out.println("Double.NaN="+Double.NaN);
12. Double f=new Double(5.0f/0.0f);
13. System.out.println(f);
14. Double f1=new Double(-5.0f/0.0f);
15. System.out.println(f1);
16. }
17. }
18.
19. Output
20.
21. Double.MAX_VALUE=1.7976931348623157E308
22. Double.MIN_VALUE=4.9E-324
23. Double.SIZE=64
24. Double.TYPE=double
25. Double.POSITIVE_INFINITY=Infinity
26. Double.NEGATIVE_INFINITY=-Infinity
27. Infinity
28. -Infinity
1. class FloatIsInfiniteDemo
2. {
1. class IntegerHexBinOct
2. {
3. public static void main(String args[])
4. {
5. System.out.println("Binary of 25 is ="+Integer.toBinaryString(25));
1. import java.io.*;
2. class LongMethodsDemo
3. {
4. public static void main(String args[])
5. {
6. System.out.println(Long.toBinaryString(100));
7. System.out.println(Long.toOctalString(100));
8. System.out.println(Long.toHexString(100));
9. }
10. }
11.
12. Output
13.
14. 1100100
15. 144
16. 64
Byte(byte b)
Byte(String s)
1. class ByteConstructors
2. {
3. public static void main(String args[])
4. {
5. Byte b1=new Byte((byte)100);
6. Byte b2=new Byte("100");
7. System.out.println("b1="+b1);
8. System.out.println("b2="+b2);
9. }
10. }
11.
12. Output
13.
14. b1=100
15. b2=100
1. class ByteFields
2. {
3. public static void main(String args[])
4. {
5. System.out.println("Max="+Byte.MAX_VALUE);
6. System.out.println("Min="+Byte.MIN_VALUE);
7. System.out.println("Type="+Byte.TYPE);
8. System.out.println("Size="+Byte.SIZE); // returns size in bits
9. }
10. }
11.
12. Output
13.
14. Max=127
15. Min=-128
16. Type=byte
17. Size=8
This program aims to get the user input and convert to primitive using AutoBox
and Autounbox. This is the mechanism introduced in java 5. The wrapper object
type values can be stored to primitive wrapper type and vice versa. Prior in
java 5, it will throw exception
1. import java.io.DataInputStream;
2. public class ObjectToPrimitiveWithAutoBox
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. DataInputStream dis=new DataInputStream(System.in);
9. System.out.println("Enter Integer");
10. int num1=new Integer(dis.readLine());
11. System.out.println("Enter float");
12. float num2=new Float(dis.readLine());
13. System.out.println("Enter Double");
14. double num3=new Double(dis.readLine());
15. System.out.println("Enter byte value");
16. byte num4=new Byte(dis.readLine());
17. System.out.println("Enter long value");
18. long num5=new Long(dis.readLine());
19. System.out.println("Enter Short value");
ConvertObjectToPrimitiveDifferentType
1. import java.io.*;
2. class ConvertObjectToPrimitiveDifferentType
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. DataInputStream dis=new DataInputStream(System.in);
9. System.out.println("Enter Double to Integer");
10. int num1=new Double(dis.readLine()).intValue();
11. System.out.println("Enter Float to double");
12. double num2=new Float(dis.readLine()).doubleValue();
13. System.out.println("integer num1 ="+num1);
14. System.out.println("double num2 ="+num2);
15. }
16. catch(Exception e){}
17. }
18. }
19.
20. Output
21.
22. Enter Double to Integer
23. 23.43
24. Enter Float to double
25. 54.67
26. integer num1 =23
27. double num2 =54.66999816894531
1. class MaxAndMinValues
2. {
3. public static void main(String args[])
4. {
5. System.out.println("Integer.MAX_VALUE="+Integer.MAX_VALUE);
6. System.out.println("Integer.MIN_VALUE="+Integer.MIN_VALUE);
7.
8. System.out.println("Long.MAX_VALUE="+Long.MAX_VALUE);
9. System.out.println("Long.MIN_VALUE="+Long.MIN_VALUE);
10.
11. System.out.println("Double.MAX_VALUE="+Double.MAX_VALUE);
12. System.out.println("Double.MIN_VALUE="+Double.MIN_VALUE);
13.
14. System.out.println("Float.MAX_VALUE="+Float.MAX_VALUE);
15. System.out.println("Float.MIN_VALUE="+Float.MIN_VALUE);
16.
17. System.out.println("Byte.MAX_VALUE="+Byte.MAX_VALUE);
18. System.out.println("Byte.MIN_VALUE="+Byte.MIN_VALUE);
19. System.out.println("Short.MAX_VALUE="+Short.MAX_VALUE);
20. System.out.println("Short.MIN_VALUE="+Short.MIN_VALUE);
21. }
22. }
23.
24. Output
25.
26. Integer.MAX_VALUE=2147483647
27. Integer.MIN_VALUE=-2147483648
28. Long.MAX_VALUE=9223372036854775807
29. Long.MIN_VALUE=-9223372036854775808
30. Double.MAX_VALUE=1.7976931348623157E308
31. Double.MIN_VALUE=4.9E-324
32. Float.MAX_VALUE=3.4028235E38
33. Float.MIN_VALUE=1.4E-45
34. Byte.MAX_VALUE=127
35. Byte.MIN_VALUE=-128
36. Short.MAX_VALUE=32767
37. Short.MIN_VALUE=-32768
Boolean class
1. class BooleanCompareToDemo
2. {
3. public static void main(String args[])
4. {
5. Boolean b1=new Boolean("true");
6. Boolean b2=new Boolean(false);
7. Boolean b3=new Boolean(true);
8. System.out.println("b1.compareTo(b2)="+b1.compareTo(b2));
9. System.out.println("b1.compareTo(b3)="+b1.compareTo(b3));
10. System.out.println("b2.compareTo(b3)="+b2.compareTo(b3));
11. }
12. }
13.
14. Output
15.
16. b1.compareTo(b2)=1
17. b1.compareTo(b2)=1 // true and false comparision returns positive integer
Boolean(String)
Boolean(boolean)
1. class BooleanConstructor
2. {
3. public static void main(String args[])
4. {
5. Boolean b1=new Boolean("true");
6. Boolean b2=new Boolean(false);
7. Boolean b3=new Boolean(true);
8. System.out.println("b1="+b1);
9. System.out.println("b2="+b2);
10. System.out.println("b3="+b3);
11. }
12. }
13.
14. Output
15.
16. b1=true
17. b2=false
18. b3=true
1. class BooleanEqualsDemo
2. {
3. public static void main(String args[])
4. {
5. Boolean b1=new Boolean("true");
6. Boolean b2=new Boolean(false);
1. class BooleanParseBooleanDemo
2. {
3. public static void main(String args[])
4. {
5. Boolean b1=new Boolean("true");
6. Boolean b2=new Boolean(false);
7. Boolean b3=new Boolean(true);
8. String b4="false";
9. boolean bool1=Boolean.parseBoolean(b4);
10. System.out.println("bool1="+bool1);
11. }
12. }
13.
14. Output
15.
16. bool1=false
Character class
1. class CharacterCharValueDemo
2. {
3. public static void main(String args[])
4. {
5. Character c1=new Character('A');
6. Character c2=new Character('Z');
7. char char1=c1.charValue();
8. System.out.println("c1.charValue()="+char1);
9. }
10. }
11.
12. Output
13.
14. c1.charValue()=A
1. class CharacterCompareToDemo
2. {
3. public static void main(String args[])
4. {
5. Character c1=new Character('A');
6. Character c2=new Character('Z');
7. System.out.println("c1.compareTo('D')="+c1.compareTo('D'));
8. System.out.println("c1.compareTo('a')="+c1.compareTo('a'));
9. System.out.println("c1.compareTo('I')="+c1.compareTo('I'));
10. }
11. }
12.
13. Output
14.
15. c1.compareTo('D')=-3
16. c1.compareTo('a')=-32
17. c1.compareTo('I')=-8
Character(char value)
1. class CharacterConstructorDemo
2. {
3. public static void main(String args[])
4. {
5. Character c1=new Character('A');
6. Character c2=new Character('Z');
7. System.out.println(c1);
8. System.out.println(c2);
9. }
10. }
11.
12. Output
13.
14. A
15. Z
1. class CharacterEqualsDemo
2.
3. {
4. public static void main(String args[])
5. {
6. Character c1=new Character('A');
7. Character c2=new Character('Z');
8. System.out.println("c1.equals(c2)="+c1.equals(c2));
9. }
10. }
11.
12. Output
13.
14. c1.equals(c2)=false
1. class PrintAscii
2. {
3. public static void main(String args[])
4. {
5. for(int i=0;i<=255;i++)
6. System.out.println(i+"="+(char)i);
7. }
8. }
9.
10. Output
11.
12. Here we can see all ascii characters and its values.
java.lang.System class
System.getProperties()
1. import java.util.*;
2. class SystemProperties
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. Properties p=System.getProperties();
9. // Enumeration is an interface to retrieve the key stored in Collection(class) *
/
10. Enumeration e=p.propertyNames();
11. while (e.hasMoreElements())
12. {
13. String key=e.nextElement().toString();
14. String value=System.getProperty(key);
15. System.out.println(key+":\"answers:\""+value);
16. }//while
17. }//try
18. catch(Exception e)
19. {
20. System.out.println(e);
21. }
22. }//main
23. }//class
24.
25. Output
26.
27. java.runtime.name:"answers:"Java(TM) 2 Runtime Environment, Standard Editi
on
28. sun.boot.library.path:"answers:"D:\Program Files\Java\jdk1.5.0\jre\bin
29. java.vm.version:"answers:"1.5.0-beta2-b51
30. java.vm.vendor:"answers:"Sun Microsystems Inc.
31. java.vendor.url:"answers:"http://java.sun.com/
32. path.separator:"answers:";
33. java.vm.name:"answers:"Java HotSpot(TM) Client VM
34. file.encoding.pkg:"answers:"sun.io
35. user.country:"answers:"US
36. sun.os.patch.level:"answers:"
37. java.vm.specification.name:"answers:"Java Virtual Machine Specification
38. user.dir:"answers:"G:\KalaiPrintingWork\lang\System\properties
39. java.runtime.version:"answers:"1.5.0-beta2-b51
40. java.awt.graphicsenv:"answers:"sun.awt.Win32GraphicsEnvironment
41. java.endorsed.dirs:"answers:"D:\Program Files\Java\jdk1.5.0\jre\lib\endors
ed
42. os.arch:"answers:"x86
43. java.io.tmpdir:"answers:"D:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\
44. line.separator:"answers:"
45. java.vm.specification.vendor:"answers:"Sun Microsystems Inc.
46. user.variant:"answers:"
47. os.name:"answers:"Windows XP
48. sun.jnu.encoding:"answers:"Cp1252
49. java.library.path:"answers:"D:\Program Files\Java\jdk1.5.0\bin;.;D:\WINDOW
S\System32;D:\WINDOWS;D:\WINDOWS\system32;D:\WINDOWS;D:\WINDOWS\System32\Wbem;C:
\jdk1.5.0\bin;g:\ORAWIN95\BIN;F:\Program Files\Java\jdk1.5.0\bin
50. java.specification.name:"answers:"Java Platform API Specification
51. java.class.version:"answers:"49.0
52. sun.management.compiler:"answers:"HotSpot Client Compiler
53. java.util.prefs.PreferencesFactory:"answers:"java.util.prefs.WindowsPrefer
encesFactory
54. os.version:"answers:"5.1
55. user.home:"answers:"D:\Documents and Settings\Administrator
56. user.timezone:"answers:"
57. java.awt.printerjob:"answers:"sun.awt.windows.WPrinterJob
58. file.encoding:"answers:"Cp1252
59. java.specification.version:"answers:"1.5
60. user.name:"answers:"Administrator
61. java.class.path:"answers:".;D:\Program Files\Java\jdk1.5.0\lib\classes.zip
;F:\Program Files\Apache Group\Tomcat 4.1\common\lib\servlet.jar;F:\Program File
s\Apache Software Foundation\Tomcat 5.5\common\lib\jsp-
api.jar;F:\Program Files\Apache Software Foundation\Tomcat 5.5\common\lib\servle
t-api.jar;
62. java.vm.specification.version:"answers:"1.0
63. sun.arch.data.model:"answers:"32
64. java.home:"answers:"D:\Program Files\Java\jdk1.5.0\jre
65. java.specification.vendor:"answers:"Sun Microsystems Inc.
66. user.language:"answers:"en
67. awt.toolkit:"answers:"sun.awt.windows.WToolkit
68. java.vm.info:"answers:"mixed mode, sharing
69. java.version:"answers:"1.5.0-beta2
70. java.ext.dirs:"answers:"D:\Program Files\Java\jdk1.5.0\jre\lib\ext
71. sun.boot.class.path:"answers:"D:\Program Files\Java\jdk1.5.0\jre\lib\rt.ja
r;D:\Program Files\Java\jdk1.5.0\jre\lib\i18n.jar;D:\Program Files\Java\jdk1.5.0
\jre\lib\sunrsasign.jar;D:\Program Files\Java\jdk1.5.0\jre\lib\jsse.jar;D:\Progr
am Files\Java\jdk1.5.0\jre\lib\jce.jar;D:\Program Files\Java\jdk1.5.0\jre\lib\ch
arsets.jar;D:\Program Files\Java\jdk1.5.0\jre\classes
To terminate the program using exit() of System class. The int arguments serves as the
status code.
The call System.exit(n) is effectively equivalent to the call and exit() calls below
method.
Runtime.getRuntime().exit(n)
1. class ExitDemo
2. {
3. public static void main(String args[])
4. {
5. System.out.println("I am before Exit");
6. System.exit(100);
7. System.out.println("I am after exit");
8. }
9. }
10.
11. Output
12.
13. I am before Exit
CurrentTimeMillisDemo.java
Page 361 of 660
Java Book - Chidambaram.S
Methods of java.lang.Class
1. class ProviderSuper
2. {
3. ProviderSuper()
4. {
5. System.out.println("I am ProviderSuper");
6. }
7. }
8. class Provider extends ProviderSuper
9. {
10. Provider()
11. {
12. System.out.println("I am Provider");
13. }
14. }
15. class ClassCall
16. {
17. public static void main(String args[])
18. {
19. try
20. {
21. Class c1=Class.forName("Provider");
22. System.out.println(c1.getName());
23. Class c2=c1.getSuperclass();
24. System.out.println(c1.getSuperclass().getName());
25. System.out.println(c2.getSuperclass());
26. System.out.println(c2);
27. }
28. catch(Exception e)
29. {
30. System.out.println(e);
31. }
32. }
33. }
34.
35. Output
36.
37. Provider
38. ProviderSuper
39. class java.lang.Object
40. class ProviderSuper
Reflection
Using java.lang.Class below programs retrieve and invoke the members of the
Provider.class. This mechanism is known as reflection.
1. Provider.java -
It is the source class and in output you can see the list of members of this cl
ass
2. public class Provider
3. {
4. public final int x=100;
5. public String y="Ragav";
6. public int m1=10;
7. public int m2=100;
8. public Provider(){}
9. public Provider(String name){}
77. catch(Exception e)
78. {
79. e.printStackTrace();
80. }
81. /* To Display all Construcors defined in Given Class */
82. System.out.println("List of Constructors");
83. try
84. {
85. Constructor co[]=c.getDeclaredConstructors();
86. for (int i=0;i<co.length;i++)
87. {
88. int modifier=co[i].getModifiers();
89. switch (modifier)
90. {
91. case 1:
92. System.out.print("public ");
93. case 0:
94. System.out.print("default ");
95. }
96. System.out.print(co[i].getName()+"(");
97. Class pmtype[]=co[i].getParameterTypes();
98. for (int j=0;j<pmtype.length;j++)
99. {
100. System.out.print(pmtype[j].getName());
101. if ((j+1)!=pmtype.length)
102. System.out.print(",");
103. }
104. System.out.println(")");
105. }
106. }
107. catch(Exception e)
108. {
109. e.printStackTrace();
110. }
111. /* To Display all Variables defined in Given Class */
147. }//try
148. catch(Exception e)
149. {
150. e.printStackTrace();
151. }
152. }
153. public static void main(String args[])
154. {
155. new ClassDemo();
156. }
157. }
158.
159. command to run the program - java ClassDemo
160.
161. Output
162.
163. The name of class is =Provider
164. void main([Ljava.lang.String;)
165. void protected_subtract()
166. void private_sum(double,double)
167. void public_mul(java.lang.String)
168. void default_div()
169. List of Constructors
170. default Provider(float)
171. public default Provider(double,double)
172. public default Provider(java.lang.String)
173. public default Provider()
174. List of Variables
175. public final int x=100
176. public java.lang.String y=Ragav
177. public int m1=10
178. public int m2=100
1. import java.lang.reflect.*;
2. class MethodsViewDemo
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. Class c=Class.forName("A");
9. //A ob1=new A();
10. //Class c=ob1.getClass();
11. Object ob1=c.newInstance();
12. Method m[]=c.getDeclaredMethods();
13. for (int i=0;i<m.length;i++)
14. {
15. int x=m[i].getModifiers();
16. System.out.println("x="+x);
17. if (x==1)
18. System.out.print("public ");
19. else if(x==0)
20. System.out.print("default ");
21. else if(x==9)
22. System.out.print("public static ");
23. else if(x==8)
24. System.out.print("default static ");
25.
26. System.out.print(m[i].getReturnType().getName()+" ");
27. System.out.print(m[i].getName()+"(");
28. Class ptypes[]=m[i].getParameterTypes();
29. for (int j=0;j<ptypes.length;j++)
30. {
31. System.out.print(ptypes[j].getName());
32. if (j!=ptypes.length-1)
33. System.out.print(",");
34. }//for
35. System.out.println(")");
36. }//outerfor
37. Object ob=m[0].invoke(ob1,5,5,"Rama");
38. System.out.println(ob.toString());
39. Constructor con[]=c.getDeclaredConstructors();
40. for(int j=0;j<con.length;j++)
41. {
42. int mod=con[j].getModifiers();
43. if(mod==0)
44. System.out.print("default ");
45. else if(mod==1)
46. System.out.print("public ");
47. else if(mod==2)
48. System.out.print("private ");
49. System.out.print(con[j].getName()+"(");
50. Class pratypes[]=con[j].getParameterTypes();
51. for(int k=0;k<pratypes.length;k++)
52. {
53. System.out.print(pratypes[k].getName());
54. if(k!=pratypes.length-1)
55. System.out.print(",");
56. }
57. System.out.print(")");
58. System.out.println();
59. }
60. Object obj= con[1].newInstance(5,"java");
61. //Object obj1= con[0].newInstance(5.0f);
62. Field f[]=c.getDeclaredFields();
63. for(int l=0;l<f.length;l++)
64. {
65. int md=f[l].getModifiers();
66. if (md==1)
67. System.out.print("public ");
68. else if(md==0)
69. System.out.print("default ");
70. else if(md==9)
71. System.out.print("public static ");
72. else if(md==8)
108. {
109. public int age=23;
110. public static String s="java";
111. float f;
112. public A()
113. {
114. System.out.println("I am A");
115. }
116. A(int i,String s)
117. {
118. System.out.println("I am A with i and s");
119. }
120. private A(float f)
121. {
122. }
123. public static String pubmethod(int x,int y,String s)
124. {
125. System.out.println("I am pubmethod ");
126. return ("Hello");
127. }
128. static void defmethod(double d1,double d2)
129. {
130. System.out.println("I am defmethod ");
131. }
132. }
Cloning
Cloning is the way to get the copy of the object.
ob1=ob2; using this, now ob1 refers the memory of ob2. All the changes in ob2 or ob1
affects both the objects.
By creating the object using clone method creates new copy with the new memory.
To do the clone for an object the class must implement Cloneable interface. Otherwise
we will get CloneNotSupportedException.
Clone Example 1
26. ob2.x=500;
27. System.out.println("ob1.x="+ob1.x);
28. System.out.println("ob2.x="+ob2.x);
29. }
30. }
31.
32. Output
33.
34. ob1.x=100
35. ob2.x=100
36. ob1.x=500
37. ob2.x=500
Clone Example 2
21. {
22. public static void main(String args[])
23. {
24. A ob1=new A();
25. ob1.x=100;
26.
27. A ob2=ob1.objectFactory(ob1);
28. System.out.println("ob1.x="+ob1.x);
29. System.out.println("ob2.x="+ob2.x);
30. ob1.x=300;
31. System.out.println("ob1.x="+ob1.x);
32. System.out.println("ob2.x="+ob2.x);
33. }
34. }
35.
36. Output
37.
38. ob1.x=100
39. ob2.x=100
40. ob1.x=300
41. ob2.x=100
1. class MathMethodsDemo1
2. {
3. public static void main(String args[])
4. {
5. System.out.println("Math.ceil(5.1) = " + Math.ceil(5.1));
6. System.out.println("Math.ceil(5.9) = " + Math.ceil(5.9));
7. System.out.println("Math.floor(5.1) = " + Math.floor(5.1));
8. System.out.println("Math.floor(5.9) = " + Math.floor(5.9));
43.
44. acos(12.2345) = NaN
45. asin(0.2345) = 1.206851824742245
46. atan(12.2345) = 0.09216971189683117
47. atan2(12.2345,11.22) = 0.09216971189683117
48. cbrt(27) = 3.0
49. 5,2)=1.0
1. class MathMethodsDemo4
2. {
3. public static void main(String args[])
4. {
5. System.out.println("\t Math.log(2) = " + Math.log(2));
6. System.out.println("\t Math.log10(2) = " + Math.log10(2));
7. System.out.println("\t Math.log1p(2) = " + Math.log1p(2));
8. }
9. }
10.
11. Output
12.
13. Math.log(2) = 0.6931471805599453
14. Math.log10(2) = 0.3010299956639812
15. Math.log1p(2) = 1.0986122886681096
1. class MathMethodsDemo5
2. {
3. public static void main(String args[])
4. {
5. System.out.println("\t Math.max(12,34) = " + Math.max(12,34));
6. System.out.println("\t Math.min(12,34) = " + Math.min(12,34));
7. System.out.println("\t Math.round(2.2)="+Math.round(2.2));
8. System.out.println("\t Math.round(2.5)="+Math.round(2.5f));
9. System.out.println("\t Math.round(2.9)="+Math.round(2.9));
10. System.out.println("\t Math.rint(2.5)="+Math.rint(2.5));
Garbage Collection
1. class GarbageDemo
2. {
3. Runtime rt=rt=Runtime.getRuntime(); // Runtime class object creation
4. void m1()
5. {
6. int a[]=new int[3000];
7. System.out.println("Total Memory ="+rt.totalMemory());
8. System.out.println("Free Memory 1 ="+rt.freeMemory());
9. System.out.println("Max Memory="+rt.maxMemory());
10. // call the finalize(); but it is not guarantee to call the finalize meth
od even we override the method here
11. rt.runFinalization();
12. rt.gc();//To start the garbage collection explicitly
Using Runtime class we can invoke the applications stored in our machine using
exec() which returns Process object to control the executed application.
1. import java.io.*;
2. class StartFile
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. int x;
9. Runtime rt=Runtime.getRuntime();
10. // str[0] - path of the application; str[1] -
the file which opens with the application
11. String str[]={"F:\\Program Files\\Microsoft Office\\Office10\\winword.exe"
,"H:\\java5.30\\lang\\RunTime\\Methods.doc"};
12. Process p=rt.exec(str);
13. p.waitFor(); // This enables JRE to wait until the opened application is c
losed.
14. }catch(Exception e){e.printStackTrace();}
15. }
16. }
17.
18. Output
19.
20. currentTimeMillis() returns current date as long number -
the difference, measured in milliseconds, between the current time and midnight
, January 1, 1970
java.lang.Object class
It is the super class of all predefined and user defined classes. So we can use
the members of Object class in our classes without creating object.
Methods of java.lang.Object
To create shallow copy of an object we can use this method. It means object
assignment will not create object with new memory. The LHS object refers the
memory of RHS. By using this method we can create new object based on existing
object with new memory. In java.lang we will discuss about it.
To check memory equality of objects, we can use this method. If two objects are
having same memory reference, it returns true.
Creates java.lang.Class object for any one class. In java.lang we will discuss
about it.
For each one object run time provides the hash code. The hash codes are same for
same memory references objects. equals() does the same job. If you override
equals() in your class, you can use this method to check the memory equality for
the objects.
ServerSockets and Sockets are the two classes to create the client server
application. Lets see the program example below to understand clearly.
ServerSocket(int port)
Creates a server socket, bound to the specified port. A port number of 0 means that
the port number is automatically allocated, typically from an ephemeral port range.
This port number can then be retrieved by calling getLocalPort()
Socket
This class implements client sockets
Simple Chat
Server.java
1. import java.net.*;
2. import java.io.*;
3.
4. class Server {
5. public static void main(String args[]) {
6. try {
7. /*
8. * ServerSocket is created @ localhost @ 2000 port number. It means
9. * the ServerSocket waits in 2000 port number and listens to accept
10. * Socket
11. */
12. ServerSocket ss = new ServerSocket(2000);
13. System.out.println("1");
14. // If socket is connected this server then server accepts and
return
15. // the Socket to our application
16. Socket socket = ss.accept();
17. System.out.println("2");
18. // To get the data from Socket as InputStream
19. InputStream is = socket.getInputStream();
20. System.out.println("3");
21. //
22. byte b[] = new byte[20];
23. System.out.println("4");
24. // Reads data from socket and store in b
25. is.read(b);
26. System.out.println("5");
27. // b[] is converted to String
28. String str = new String(b);
29.
30. System.out.println(str);
31. } catch (Exception e) {
32. e.printStackTrace();
33. }
34. }
35. }
Client.java
1. import java.io.*;
2. import java.net.*;
3.
4. class Client {
5. public static void main(String args[]) {
6. try {
7. // Socket object is created. The first argument is the computer name
Note : you can use single machine with two command prompts to demonstrate the
program.
Output
InetAddress
Lets see the program example below for InetAddress. Below program uses
InetAddress object to retrieve the request details.
1. import java.net.*;
2.
3. class InetAddressDemo {
4. public static void main(String args[])
5. {
6. try
7. {
8. /*
9. InetAddress has below static methods to create InetAddress object
10. We created the object inet1,inet2,inet3 and inet4 */
11. InetAddress inet1=InetAddress.getLocalHost();
12. InetAddress inet2=InetAddress.getByName("Chidambaram-
PC");
13. System.out.println("inet1="+inet1);
14. System.out.println("Details of inet1");
15. System.out.println("GetCanonicalHostName="+inet1.getCanonicalH
ostName());
16. System.out.println("GetHostName="+inet1.getHostName());
17. System.out.println("GetHostAddress="+inet1.getHostAddress());
18. System.out.println("inet2="+inet2);
19. System.out.println("Details of inet2");
20. System.out.println("GetCanonicalHostName="+inet2.getCanonicalH
ostName());
21. System.out.println("GetHostName="+inet2.getHostName());
22. System.out.println("GetHostAddress="+inet2.getHostAddress());
23.
24. }//try
25. catch(Exception e){
26. e.printStackTrace();
27. }
28. }// main
29. }// class
30.
31. Output
32.
33. inet1=Chidambaram-PC/192.168.43.33
34. Details of inet1
35. GetCanonicalHostName=Chidambaram-PC
36. GetHostName=Chidambaram-PC
37. GetHostAddress=192.168.43.33
38. inet2=Chidambaram-PC/192.168.43.33
39. Details of inet2
40. GetCanonicalHostName=Chidambaram-PC
41. GetHostName=Chidambaram-PC
42. GetHostAddress=192.168.43.33
Server Program
It is similar to first program. Except here we accept the socket in while(true) loop.
So it works indefinitely until we quit the command prompt
1. import java.net.*;
2. import java.io.*;
3. import java.util.Date;
4. import java.text.SimpleDateFormat;
5.
6. class Server {
7. public static void main(String args[]) {
8. try {
9. // server socket creation @ localhost @ 2000 port
10. ServerSocket ss = new ServerSocket(2000);
11. while (true) {
12. /*
13. * server waits here; the below line will be executed when
the
14. * socket is arrived to the server and server accepts the
socket
15. * and returns to the application
16. */
17. Socket socket = ss.accept();
18. // InetAddress object created to resolve the client machin
e to
19. // know who is connected the server
20. InetAddress inet = socket.getInetAddress();
21. String clientcomputername = inet.getHostName();
22. // date object created to print when is the client reached
the
23. // server
Client Program
It is similar to first program in this book. but in below client program we get the
input and send to server in while(true) loop. So it works indefinitely until we quit
the command prompt or we can close the socket using some condition. I just commented
out the socket.close() in below program.
1. import java.io.*;
2. import java.net.*;
3. class Client
4. {
5. public static void main(String args[])
6. {
7. try
8. {
9. while (true)
10. {
11. /*
12. scoket is created to connect SeverSocket in com5 computer @ 2000 port
13. In your machine, you can change to localhost if you run server and client
in two console.
14. ex: Socket socket=new Socket(“localhost”,2000); */
15.
16. Socket socket=new Socket(“com5”,2000);
17. DataInputStream dis=new DataInputStream(System.in);
18. System.out.println(“Enter Msg to send server”);
19. String str=dis.readLine();
20. OutputStream os=socket.getOutputStream();
21. byte b[]=str.getBytes();
22. os.write(b);
23. InputStream is=socket.getInputStream();
24. byte b1[]=new byte[20];
25. is.read(b1);
26. System.out.println(“Server:”+new String(b1));
27. //socket.close();
28. }
29. }
30. catch(Exception e)
31. {
32. e.printStackTrace();
33. }
34. }
35. }
Socket Methods
The same socket class methods are printed in client side and server side.
Server.java
1. import java.net.*;
2. import java.io.*;
3. import java.util.Date;
4. import java.text.SimpleDateFormat;
5. class Server
6. {
7. public static void main(String args[])
8. {
9. String str=””;
10. try
11. {
12. ServerSocket ss=new ServerSocket(2000);
13. while(true)
14. {
15. Socket socket=ss.accept();
16. // To know the client computer name of the machine which socket is
created
17. System.out.println(“Client Name=”+socket.getInetAddress().
getHostName());
18. // To know the server name to the machine socket is connected
19. System.out.println(“Server Name=”+socket.getLocalAddress()
.getHostName());
20. //The port number socket is created at client machine.
21. System.out.println(“Client Port=”+socket.getPort());
22. //The port number socket is connected in server machine
23. System.out.println(“Server Port=”+socket.getLocalPort());
24. /*
25. Returns the binding state of the socket. Even closing a socket doesn't cle
ar its binding state. It means this method will return true until it is bound @
server machine */
26. System.out.println(“Is socket Available=”+socket.isBound()
);
27.
28. String date=new SimpleDateFormat(“dd/MMM/yyyy hh:mm:ss”).f
ormat(new Date());
29. InputStream is=socket.getInputStream();
30. byte b[]=new byte[20] ;
31. System.out.println(“Client:”+clientname+”Date:”+date+”Msg:
”+str);
32. socket.close();
33. System.out.println(“After Closing Socket”);
34. System.out.println(“Is socket Available=”+socket.isBound()
);
35. System.out.println(“Is socket Closed=”+socket.isClosed());
36. /*
37. Returns the connection state of the socket. Closing a socket doesn't clea
r its connection state, which means this method will return true until it connec
ts the server */
38. System.out.println(“Is socket Connected=”+socket.isConnect
ed());
39. System.out.println(“Is string information of socket=”+sock
et.toString());
40. }
41. }
42.
43. catch(Exception e)
44. {
45. System.out.println(e);
46. }
47. }
48. }
Client.java
1. import java.io.*;
2. import java.net.*;
3. class Client
4. {
5. public static void main(String args[])
6. {
7. Socket socket=null;
8. try
9. {
10. socket=new Socket("com5",2000);
11. socket.getOutputStream().write("Hello ".getBytes());
12. Thread.sleep(5000);
13. }
14. catch(Exception e)
15. {
16. System.out.println(e);
17. }
18. try
19. {
20. InetAddress serverinet=InetAddress.getByName("com5");
21. InetAddress clientinet=InetAddress.getByName("com5");
22. System.out.println("Server Name="+socket.getInetAddress().getH
ostName());
23. System.out.println("Client Name="+socket.getLocalAddress().get
HostName());
24. System.out.println("Socket getPort()="+socket.getPort());
25. System.out.println("Socket getLocalPort()="+socket.getLocalPor
t());
26. System.out.println("Socket isConnected()="+socket.isConnected(
));
27. System.out.println("Is socket Available="+socket.isBound());
28. System.out.println("Socket isClosed()="+socket.isClosed());
29. System.out.println("Socket toString()="+socket.toString());
30. }
31. catch(Exception e)
32. {
33. System.out.println(e);
34. }
35. }
36. }
Output
Need
Develop Chat Application. The below program accepts many sockets and enable the
Client
ClientPrg
ReadThread
It is the thread. For each one client the new thread is started.
SendThread
It is one more thread. For each one client the new thread is started
sendMessage() gets the input from client and sends to other client
So one reading / sending is completed again the methods are reading / sending
message indefinitely.
Server
ServerPrg
1. import java.net.*;
2. import java.io.*;
3. class ClientPrg
4. {
5. DataInputStream dis=new DataInputStream(System.in);
6. Socket s;
7. String str;
8. OutputStream os;
9. String systemname;
10. InputStream is;
11. void init()
12. {
13. try
14. {
15. s=new Socket("com8",2000);
16. systemname=InetAddress.getLocalHost().getHostName();
17. os=s.getOutputStream();
18. os.write(systemname.getBytes());
19. }
20. catch(Exception e)
21. {
22. System.out.println("init ="+e);
23. }
24.
25. }
26. void readMessage()
27. {
28. try
29. {
30. System.out.println("read 1");
31. byte b[]=new byte[100];
32. System.out.println("read 2");
33. is=s.getInputStream();
34. System.out.println("read 3");
35. is.read(b);
36. System.out.println("read 4");
37. System.out.println(new String(b));
38. }
39. catch(Exception e)
40. {
41. System.out.println("From read="+e);
42. }
43. }//method
44.
45. void sendMessage()
46. {
47. try
48. {
49. System.out.println("Enter the String -
Friend name to send the server");
50. str=dis.readLine();
51. os=s.getOutputStream();
52. os.write(str.getBytes());
53. }
54. catch(Exception e){}
55. }
56. }
1. class Client
2. {
3. public static void main(String args[])throws Exception
4. {
5. ClientPrg cp=new ClientPrg();
6. cp.init();
7. ReadThread rt=new ReadThread(cp);
8. SendThread st=new SendThread(cp);
9. }
10. }
1. import java.net.*;
2. import java.io.*;
3. class ServerPrg implements Runnable
4. {
5. static int clientcount;
6. Socket s;
7. Thread t;
8. InputStream is;
9. OutputStream os;
10. String clientname;
11. String message,msg,targetname;
12. static ServerPrg sp[]=new ServerPrg[10];
13. void createClientThread(Socket s)
14. {
15. clientcount=clientcount+1;
16. this.s=s;
17. t=new Thread(this);
18. t.start();
19. }
20. public void run()
21. {
22. try
23. {
24. while(true)
25. {
26. System.out.println("1");
27. byte b[]=new byte[100];
28. System.out.println("2");
29. is=s.getInputStream();
30. System.out.println("3");
31. is.read(b);
32. System.out.println("4");
33. message=new String(b);
34. System.out.println("5");
35. msg=message.substring(0,message.indexOf('-'));
36. System.out.println("6");
37. targetname=message.substring(message.indexOf('-
')+1,message.length());
38. System.out.println("7");
39. System.out.println("client Name : "+clientname +": Message
" +msg+"Target Name : "+targetname);
40. // source - clientname
41. // target - targetname
42. //message - msg
43. msg=clientname + ":" +msg;
44. for (int i=0;i<clientcount;i++)
45. {
46. System.out.println("client List");
47. System.out.println("-------------------------");
48. System.out.println(i+"]"+sp[i].clientname);
49.
50. }
51. System.out.println("-------------------------");
52. for (int i=0;i<clientcount;i++)
53. {
54. System.out.println("server for 1");
55. System.out.println("sp[i].clientname:"+sp[i].clientnam
e);
56. System.out.println("this.targetname:"+this.targetname)
;
57. if (((sp[i].clientname).trim()).equalsIgnoreCase((this
.targetname).trim()))
58. {
59. System.out.println("server for 2");
60. os=sp[i].s.getOutputStream();
61. System.out.println("server for 3");
62. os.write(msg.getBytes());
63. System.out.println("server for 4");
64. break;
65. }
66. }
67. }//while
68. }
69. catch(Exception e)
70. {
71. e.printStackTrace(); }
72. }//run
73.
74. public static void main(String args[])
75. {
76. int i=-1;
77. InputStream is;
78. byte b[]=new byte[5];
79. String clientname;
80. String clientname1;
81. try
82. {
83. ServerSocket ss=new ServerSocket(2000);
84. while(true)
85. {
86. Socket s=ss.accept();
87. i=i+1;
88. sp[i]=new ServerPrg();
89. s.getInputStream().read(b);
90. sp[i].clientname=new String(b);
91. System.out.println(sp[i].clientname+" Connected");
92. sp[i].createClientThread(s);
93.
94. }//while
95. }//try
96. catch(Exception e)
97. {
98. System.out.println("From main ="+e);
99. }//catch
100. }//main
101. }//class
Output
1) Open dos console (click start button in windows and type cmd and click
cmd.exe)
command : cd..
command : cd\
to come to drive
command : drivename:
once the drive is changed in prompt go to your folder using below command
now the prompt would show the folder where you store the program.
java ServerPrg
java ClientPrg
now you have three prompts one for server and another two for client. correct.
in one client dos prompt type client1 and another client window type client2
these names should be unique and server identifies you using this name only
msg part you can any message and second part must be the target client name.
you can run these programs in LAN (Local Area Network) also.
Datagram
The Socket uses TCP(Transmission Control Protocol), whereas Datagram uses UDP
(User Datagram Protocol).
Ok.. now lets look at the program and it is similar flow of above one program
but here we start client and server datagram sockets only.
Place this files in two different locations and change port no to different one if you
run in single machine. I here mention 20000 for one file correct. you can change it to
10000 in another file.
Start two MyDatagrams in two different console that's it. Now you are ready to start
the chat. OK Fine. Now let's see how this program is working.
In this method DatagramSocket is created in portno 20000, and another one is 10000.
correct. It means the DatagramSocket is started @ 20000 port number of localhost and @
10000 port number of localhost in different console.
SendMsg, RecMsg constructors start the threads and invoke sendMsg() and recMsg().
sendMsg() accepts the string with the format of computername-message and parses it.
DatagramPacket is created with the argument of byte array, lenght of byte array,
InetAddress object, portnumber
What we need to understand here that DatagramPacket holds the target computer name,
target computer portnumber along with message.
In recMsg() we create DatagramPacket with the byte array and its size 25.
1. import java.net.*;
2. import java.io.*;
3. class MyDatagram
4. {
5. DatagramSocket ds;
6. DataInputStream dis=new DataInputStream(System.in);
7. void serverStart()
8. {
9. try
10. {
11. ds=new DatagramSocket(20000);
12. }
13. catch(Exception e)
14. {
15. e.printStackTrace();
16. }
17. }
18. void sendMsg()
19. {
20. try
21. {
22. String message="";
23. while (true)
24. {
57. {
58. e.printStackTrace();
59. }
60. }//meth rec
61. }//class
12. {
13. try
14. {
15. md.recMsg();
16. }
17. catch(Exception e)
18. {
19. e.printStackTrace();
20. }
21. }//meth
22. }//class
1. class DatagramDemo
2. {
3. static MyDatagram md=new MyDatagram();
4. public static void main(String args[])throws Exception
5. {
6. MyDatagram md=new MyDatagram();
7. md.serverStart();
8. SendMsg sm=new SendMsg(md);
9. RecMsg rm=new RecMsg(md);
10. }
11. }
URLConnection class can be used to open the network location specified by URL
and here I give the local computer file URL using file protocol path format.
You can use any valid http /https URL also to open.
Need
Receive the Content from Server by Using URL Class
1. import java.net.URL;
2. import java.net.URLConnection;
3. import java.io.*;
4.
5. public class URLConnectionDemo {
6. public static void main(String ar[]) {
7.
8. try {
9. URL url = new URL("file:/e:/demo.txt");
10. URLConnection urlcon = url.openConnection();
11. InputStream stream = urlcon.getInputStream();
12. int i;
13. while ((i = stream.read()) != -1) {
14. System.out.print((char) i);
15. }
16. } catch (Exception e) {
17. System.out.println(e);
18. }
19.
20. }// main
21. }// class
If client is console just it prints the data. Here the client is brower. So
browser executes HTML code and shows the result.
1. import java.net.*;
2. import java.io.*;
3. class Server
4. {
5. public static void main(String args[])
6. {
7. try
8. {
9. ServerSocket ss=new ServerSocket(2000);
10. Socket socket=ss.accept();
11. InputStream is=socket.getInputStream();
12. byte b[]=new byte[300];
13. is.read(b);
14. System.out.println("Request String From IE");
15. System.out.println("------------------------");
16. System.out.println(new String(b));
17. System.out.println("------------------------");
18. OutputStream os=socket.getOutputStream();
19. String str="<h1> MY Server Response <table border=5> <th> Name
</th><th> Age </th> <tr><td> Ram </td><td>21</td></tr></table>";
20. os.write(str.getBytes());
21. socket.close();
22. }
23. catch(Exception e)
24. {
25. e.printStackTrace();
26. }
27. }
Output
RMI
JVM Communication
In java there are three ways to pass message between two JVM(Two Process). Lets
see the three ways below.
Sockets
Datagram
RMI
Reliable
Fastless
Fast
Unreliable
RMI
Page 415 of 660
Java Book - Chidambaram.S
Http based
Object can be passed between JVMs but socket allows only primitive type data.
RMI Layers
Application Layer
Proxy Layer
Transport Layer
Responsibilities of Stub
Responsibilities of Skeleton
Registry
Registry is the memory created and developed by runtime to hold remote objects.
Server Application
Example Programs
Need
Files - Client
Client.java,Student.java,ServerInterface.class,Server_Stub.class.
Files - Server
Server.java,ServerInterface.java,Student.class,Server_Stub.class.
Client/Client.java
1. import java.rmi.*;
2. import java.io.*;
3.
4. class Client {
5. public static void main(String args[]) {
6. try {
7. Student s = new Student();
8. /*
9. * this is the way to access server from client. lookup methods
10. * looks the server object in specified computer as args[0] ar
gs[0]
11. * is the argument can be passed when run the program in conso
le.
12. */
13. ServerInterface si = (ServerInterface) Naming.lookup("rmi://"
+ args[0] + "/Server");
14. Student result = si.processResult(s);
15. System.out.println(" Tamil Mark is =" + result.tamil);
16. System.out.println(" English Mark is =" + result.english);
17. System.out.println(" Maths Mark is =" + result.maths);
18. System.out.println(" Total Mark is =" + result.total);
19. System.out.println(" Average is =" + result.avg);
20. } catch (Exception e) {
21. e.printStackTrace();
22. }
23. }
24. }
Client/Student.java
1. import java.io.*;
2. /*
3. Student object will be passed to server from client and
4. server returns the same. The object passed in wire should be the sub class of
5. Serializable to do encryption and decrytpion by runtime. Otherwise we will have
MarshallException at runtime */
6. class Student implements Serializable
7. {
8. int tamil,english,maths,total;
9. double avg;
10. Student()
11. {
12. try
13. {
14. DataInputStream dis=new DataInputStream(System.in);
15. System.out.println("Enter The Tamil ");
16. tamil=Integer.parseInt(dis.readLine());
17. System.out.println("Enter The English ");
18. english=Integer.parseInt(dis.readLine());
19. System.out.println("Enter The Maths ");
20. maths=Integer.parseInt(dis.readLine());
21. }
22. catch(Exception e)
23. {
24. e.printStackTrace();
25. }
26. }
27. }
Server/Server.java
1. import java.rmi.*;
2. import java.rmi.server.*;
3. /*
4. Server must be the sub class of java.rmi.server.UnicastRemoteObject and java.rmi
.Remote interface
5. Server is our own class and it extends UnicastRemoteObject and implements Server
Interface (sub interface of Remote)
6. /*
7. class Server extends UnicastRemoteObject implements ServerInterface
8. {
9. // we must add emptry constructor
10. public Server() throws Exception
11. {
12. System.out.println("Server Started");
13. }
14.
15. /*
16. business function that done by server
17. it accesspts Student object and returns same object after
18. applying total in that object
19. */
20. public Student processResult(Student s)
21. {
22. s.total=s.tamil+s.english+s.maths;
23. s.avg=s.total/3;
24. return s;
25. }
26.
Server/ServerInterface.java
1. import java.rmi.*;
2. /*
3. sub interface of Remote must have all business functions
4. needed for client
5. ServerInterface.class must be placed in client folder.
6. */
7. public interface ServerInterface extends Remote
8. {
9. public Student processResult(Student s) throws Exception;
10. }
java Client
89
98
99
Average is =95.0
java Server
Server Started
Need
By default client can invoke the server’s method, how can we invoke client’s
method from server like Queue Applications. This program is the answer.
Files
Client
Client.class,Client.java,Client_Stub.class,ClientInterface.class,ClientInterface.java,
Server
Server.class,Server.java,ServerInterface.class,ServerInterface.java,
ClientInterface.class
Server.java
1. import java.rmi.*;
2. import java.rmi.server.*;
3. import java.util.*;
4. import java.text.*;
5. import java.rmi.registry.*;
6. public class Server extends UnicastRemoteObject implements ServerInterface
7. {
8. int count=0;
9. ClientInterface ci;
10. Vector vector=new Vector();
11. public Server() throws Exception
12. {
13. System.out.println("Server Started");
14. }
15. /* The String sent by client received here */
16. public void receiveMessage(String str)
17. {
18. try
19. {
20. /*
21. Each str sent by client is stored in vector object
22. if more than 5 str means server invokes client method to
23. share the error message
24. */
25. vector.addElement(str);
26. if (vector.size()>=5)
27. /* Now Server Calls Client method getErrorMessage */
28. ci.getErrorMessage("Limit Over, Request Prohibited",vector);
29. }
30. catch(Exception e)
31. {
32. e.printStackTrace();
33. }
34. }
Client.java
1. import java.awt.*;
2. import javax.swing.*;
3. import java.awt.event.*;
4. import java.rmi.*;
5. import java.rmi.registry.*;
6. import java.rmi.server.*;
7. import java.util.*;
8. import javax.swing.border.*;
9. /*
10. In previous program Server only sub class of Remote.
11. This program Client also sub class of Remote
12. So client can call client and server can call client.
13. */
14. /*
15. Client qualifies Remote(to invoke by server), JFrame ( to act as frame (sc
reen)) and
16. ActionListener (to listen events such button click and invoke listener met
hods)
17. */
18. class Client extends JFrame implements ActionListener,ClientInterface
19. {
20. //Swing GUI components to create the screen
21. JPanel centerpanel=new JPanel();
22. JPanel centerpanel1=new JPanel();
92. UnicastRemoteObject.exportObject(this);
93. //This methods passes client object to server.
94. si.registerServer(this);
95. }
96. public static void main(String args[])
97. {
98. try
99. {
100. Client client=new Client();
101. //To start GUI screen in client
102. client.objectCreator();
103. //invokes registerClient()
104. client.registerClient();
105. }
106. catch(Exception e)
107. {
108. e.printStackTrace();
109. }
110. }
111. }
Output – Client
Output – Server
java Server
Server Started
In prior java.awt (Abstract window Toolkit) was introduced in java 1.0 to build
the GUI pages. Swing comes with lot more components more than awt and swing extends
awt to incorporate awt functionalitis in swing.
Awt Swing
Before deep dive, Lets discuss about component hierarchy to understand how
classes are arranged in awt and swing.
java.awt.Component
java.awt.Container
java.awt.Window
java.awt.Frame java.awt.Dialog
javax.swing.JFrame javax.swing.JDialog
Using above image, lets understand the flow of awt and swing hierarchy as
below and how swing extends awt.
To create screen, we need to understand the below screen model. The below
imageillustrates Frame contains window, windows contains container and
container contains the component. Just It is better to remember this one as of
now. In below sections we will understand more better.
Frame
Window
Container
Component
Below statement is the way to create the JFrame object and displaying JFrame.
frame.show();
okcmd=new JButton("Ok");
frame.add(okcmd);
Now the following program, interestingly displays frame in top left corner with
minimized state; when you maximize the frame we can see the command button displays
full in frame.
frame.setLayout(JFrame.BORDER_LAYOUT);
The following line displays JFrame in full window with maximized manner.
frame.setSize(JFRAME.MAXIMIZED_BOTH);
Why? here we need to understand about layout concepts and frame's display methods.
so the complete code would be as follows. Just add this code in one main method and
run it, that's it.
frame.setLayout(JFrame.BORDER_LAYOUT);
frame.setSize(JFRAME.MAXIMIZED_BOTH);
okcmd=new JButton("Ok");
frame.add(okcmd);
frame.show();
Layouts
What is layout
Layout is the technique to apply the design to the screen that instructs how
the components should be arranged.
Layout interfaces
Layout Classes
BorderLayout
BoxLayout
CardLayout
FlowLayout
GridBagLayout
GridLayout
GroupLayout
SpringLayout
BorderLayout
Tool bars that are created using JToolBar must be created within
a BorderLayout container.
frame.setLayout(JFrame.BORDER_LAYOUT);
Event handling
Event handling is the process to handle the events such as mouse click, key press.
1) Listeners
2) Event handlers
Listeneres
Listeners are the sub classes of any one of Listener interface and it overrides
listener methods, which will be invoked by runtime based on the events raised by user
against components.
At the time of listener invocation, the event class will be passed by runtime
automatically. The methods of event class will be useful to handle the events. We will
see the example programs with these concepts.
Adapter classes
The below table lists the Adapter classes for each one listener except those listener
has only one method.
In below class, we must override all the methods in MouseListener. Even we don't need
all the methods, we must override with atleast empty implementation.
For example, we want to do something when mouse clicked against button. In this case,
we can add the code in mouseClicked() but we should add empty implementation as like
below.
// code to do something
//code to do something
void mouseExited(MouseEvent e)
void mousePressed(MouseEvent e)
void mouseReleased(MouseEvent
e)
AdjustmentListe
Scrollb AdjustmentEv Void No
ner
ar ent adjustmentValueChanged(Adjustmen
movemen tEvent e)
ts
FoucsListener
Keyboar FocusEvent void focusGained(FocusEvent e) FocusAdapte
d focus r
void focusLost(FocusEvent e)
events
ItemListener
Checkbo ItemEvent void itemStateChanged(ItemEvent No
x, e)
Radio
button
events
KeyListener
Textbox KeyEvent void keyPressed(KeyEvent e) KeyAdapter
pressed.
void keyReleased(KeyEvent e)
void keyTyped(KeyEvent e)
MouseWheelListe
MouseWheelEv void
ner
ent mouseWheelMoved(MouseWheel
Event e)
FocusListener
FocusEvent void focusGained(FocusEvent e) FocusAdapte
r
void focusLost(FocusEvent e)
WindowListener
Window WindowEvent void WindowAdapt
windowActivated(WindowEven er
t e)
void windowClosed(WindowEvent
e)
void windowClosing(WindowEvent
e)
void
windowDeactivated(WindowEv
ent e)
void
windowDeiconified(WindowEv
ent e)
void
windowIconified(WindowEven
t e)
void windowOpened(WindowEvent
e)
Lets see the examples in swing package and somne example applets.
1. import javax.swing.*;
2. import java.awt.event.*;
3. import java.awt.*;
4. import javax.swing.border.*;
5. class ActionEventDemo implements ActionListener,KeyListener
6. {
7. JButton okcmd,cancelcmd;
8. JTextField displaytxt;
9. JFrame jf;
10. ActionEventDemo()
11. {
12. objectCreator();
13. layoutProvider();
14. register();
15. effectsProvider();
16. addControlsToJFrame();
17. jframeShow();
18. }
19. void addControlsToJFrame()
20. {
21. jf.getContentPane().add(displaytxt);
22. jf.getContentPane().add(okcmd);
23. jf.getContentPane().add(cancelcmd);
24. }
25. void objectCreator()
26. {
27. jf=new JFrame("Events Prg");
28. okcmd=new JButton("Ok");
29. cancelcmd=new JButton("Cancel");
30. displaytxt=new JTextField(15);
31. }
32.
33. void layoutProvider()
34. {
35. jf.getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
36. }
37.
38. void effectsProvider()
39. {
40. jf.setSize(250,250);
41. }
42. void register()
43. {
44. //okcmd.addListSelectionListener(this);
45. cancelcmd.addActionListener(this);
46. displaytxt.addKeyListener(this);
47. displaytxt.requestFocus();
48. }
49. void jframeShow()
50. {
51. jf.show();
52. }
53. public void actionPerformed(ActionEvent ae)
54. {
55. String str=ae.getActionCommand();
56. displaytxt.setText(str);
57. }
Output
/* if ok is pressed*/
j -74
a -65
v -86
a -65
1. import java.util.*;
2. import javax.swing.*;
3. import java.awt.event.*;
4. import javax.swing.border.*;
5. import java.awt.*;
6. import java.text.*;
7. public class JEventDemo implements Runnable,ActionListener,TextListener,FocusLis
tener,WindowListener
8. {
9. Date timedate;
10. JPanel panel1,panel2,panel3,panel21,panel22;
11. JFrame jf;
12. JLabel dateLbl,timeLbl,titleLbl;
13. Thread t1;
14. JTextField jtf;
15. JEventDemo()
16. {
17. objectCreator();
18. effectsProvider();
19. layoutProvider();
20. addControlsToPanels();
21. addPanelsToJFrame();
22. jf.setSize(700,500);
23. jf.show();
24. t1.start();
25. }
26. public void run()
27. {
28. while(true)
29. {
30. try
31. {
32. Thread.sleep(1000);
33. timedate=new Date();
34. }//try
35. catch(Exception e){}
36. setTime();
37. }//while
38. }//run
39. void setTime()
40. {
41. timeLbl.setText(new SimpleDateFormat("hh:mm:ss").format(timedate));
42. }
43. void layoutProvider()
44. {
45. panel1.setLayout(new BorderLayout());
46. jf.getContentPane().setLayout(new BorderLayout());
47. panel2.setLayout(new BorderLayout());
48. jtf.addActionListener(this);
49.
50. jf.addWindowListener(this);
51. }
52. void objectCreator()
53. {
54. jf=new JFrame("Book Store");
55. panel1=new JPanel();
56. panel2=new JPanel();
57. panel3=new JPanel();
58. panel21=new JPanel();
59. panel22=new JPanel();
60. dateLbl=new JLabel();
61. timeLbl=new JLabel();
62. titleLbl=new JLabel("Mark List for 2005 - 2006",SwingConstants.CENTER);
63. t1=new Thread(this);
64. jtf=new JTextField("Hello JAVa",5);
65. }
101. }
102. public void focusGained(FocusEvent fe)
103. {
104.
105. }
106. public void focusLost(FocusEvent fe)
107. {
108. }
109. public void actionPerformed(ActionEvent ae)
110. {
111. System.out.println("ae.getActionCommand()="+ae.getActionCommand());
112. }
113. public void windowClosing(WindowEvent we)
114. {
115. System.out.println("Window Closing");
116. }
117. public void windowClosed(WindowEvent we)
118. {
119. System.out.println("Window Closed");
120. }
121. public void windowIconified(WindowEvent we)
122. {
123. System.out.println("Window Iconified");
124. }
125. public void windowDeiconified(WindowEvent we)
126. {
127. System.out.println("Window DeIconified");
128. }
129. public void windowActivated(WindowEvent we)
130. {
131. System.out.println("Window Activated");
132. }
133. public void windowDeactivated(WindowEvent we)
134. {
135. System.out.println("Window DeActivated");
136. }
137. public void windowOpened(WindowEvent we)
138. {
139. }
140.
141. public static void main(String args[])
142. {
143. new JEventDemo();
144. }
145. }
/* WindowConstants
DO_NOTHING_ON_CLOSE
HIDE_ON_CLOSE
DISPOSE_ON_CLOSE
EXIT_ON_CLOSE
*/
Output
Window DeIconified
Window Activated
Window Closing
Window DeActivated
Window Closed
1. import java.awt.*;
2. import java.awt.event.*;
3. import javax.swing.*;
4. public class Listener extends MouseAdapter
5. {
6. Source s;
7. public Listener(Source s)
8. {
9. this.s=s;
10. }
11. public void mouseClicked(MouseEvent me)
12. {
13. JOptionPane.showConfirmDialog(s.frame,"My Frame","My Frame Message",JOptio
nPane.DEFAULT_OPTION);
14. }
15. }
1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. class Source
5. {
6. JFrame frame;
7. JButton cmd1;
8. Source()
9. {
10. frame=new JFrame("My Frame");
11. cmd1=new JButton("Click");
12. frame.setLayout(new FlowLayout());
13. frame.add(cmd1);
14. frame.setSize(300,300);
15. frame.show();
16. cmd1.addMouseListener(new Listener(this));
17. }
18. public static void main(String args[])
19. {
20. Source s=new Source();
21. }
22. }
Output
/*If ok is clicked*/
1. import java.awt.*;
2. import javax.swing.*;
3. import java.awt.event.*;
4. class AdapterDemo extends MouseAdapter
5. {
6. JFrame frame;
7. JButton addcmd,exitcmd,savecmd;
8. AdapterDemo()
9. {
10. frame=new JFrame("Frame");
11. addcmd=new JButton("Add");
12. exitcmd=new JButton("Exit");
13. savecmd=new JButton("Save");
14. frame.setExtendedState(Frame.MAXIMIZED_BOTH);
15. addcmd.addMouseListener(this);
16. frame.setLayout(new FlowLayout(FlowLayout.LEFT,50,50));
17. frame.addMouseListener(this);
18. frame.add(addcmd);
19. frame.add(savecmd);
20. frame.add(exitcmd);
21. frame.show();
22. }
23. public static void main(String s[])
24. {
25. new AdapterDemo();
26. }
27. public void mouseClicked(MouseEvent me)
28. {
29. System.out.println("x="+me.getX());
30. System.out.println("y="+me.getY());
31. }
32. }
33.
34. Output
35. /* if add is clicked*/
36. x=29
37. y=10
BoxLayout demonstration
1.
2. import javax.swing.*;
3. import java.awt.event.*;
4. import javax.swing.border.*;
5. import java.awt.*;
6. public class BoxLayoutDemo
7. {
8. JPanel panel1,panel2,panel3;
9. JFrame jf;
10. BoxLayoutDemo()
11. {
12. objectCreator();
13. effectsProvider();
14. layoutProvider();
15. addControlsToPanels();
16. addPanelsToJFrame();
17. jf.setSize(700,500);
18. jf.show();
19. }
20. void layoutProvider()
21. {
22. jf.getContentPane().setLayout(new BoxLayout(jf.getContentPane(),BoxLayout.
Y_AXIS));
23. }
24. void objectCreator()
25. {
26. jf=new JFrame("Book Store");
27. panel1=new JPanel();
28. panel2=new JPanel();
29. panel3=new JPanel();
30. }
31. void effectsProvider()
32. {
Output
setIcon(Icon)
setPressedIcon(Icon)
setRolloverIcon(Icon)
setFont(Font)
setForeground(Color)
setBorder(Border)
setTooltipText(String str)
setMnemonic(int num)
1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. import javax.swing.border.*;
5. class HundredButton implements ActionListener
6. {
7. int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
8. int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
9. JButton button[]=new JButton[100];
10. JPanel panel1;
11. JFrame frame;
12. JScrollPane scrollpane;
13.
14. HundredButton()
15. {
16. objectCreator();
17. layoutProvider();
18. addControlsToPanels();
19. effectsProvider();
20. register();
21. frame.show();
22. }
23. void objectCreator()
24. {
25. panel1=new JPanel();
26. frame=new JFrame("My Frame");
27. for (int i=0;i<100;i++)
28. {
29. button[i]=new JButton(String.valueOf(i+1));
30. button[i].setMnemonic(i+49);
31. button[i].setBorder(new LineBorder(Color.blue));
32. }//for
33. }//method
34. void layoutProvider()
35. {
36. frame.setLayout(new BorderLayout());
37. panel1.setLayout(new GridLayout(10,10,20,20));
38. }
39. void addControlsToPanels()
40. {
41. for (int i=0;i<100;i++)
42. panel1.add(button[i]);
43. scrollpane=new JScrollPane(panel1,v,h);
44. frame.add(scrollpane,BorderLayout.CENTER);
45. }
46. void effectsProvider()
47. {
48. for (int i=0;i<100;i++)
49. {
50. button[i].setIcon(new ImageIcon("pressed.jpg"));
51. button[i].setPressedIcon(new ImageIcon("press.jpg"));
52. //button[i].setReleasedIcon(new ImageIcon("release.jpg"));
53. button[i].setRolloverIcon(new ImageIcon("rollover.jpg"));
54. panel1.setBorder(new LineBorder(Color.red,10));
1. import java.awt.*;
2. import javax.swing.*;
3. import javax.swing.border.*;
4. class ButtonMethods
5. {
6. JButton cmd1,cmd2,cmd3;
7. JFrame frame;
8. ButtonMethods()
9. {
10. objectCreator();
11. effectsProvider();
12. layoutProvider();
13. addControlsToFrame();
14. jframeShow();
15. }
16. void objectCreator()
17. {
18. cmd1=new JButton("First");
19. cmd2=new JButton("Second");
20. cmd3=new JButton("Third");
21. frame=new JFrame("JButton Methods");
22. }
23. void effectsProvider()
24. {
25. cmd1.setToolTipText("Click To view File1");// JComponent
26. cmd2.setToolTipText("Click To view File2");
27. cmd3.setToolTipText("Click To view File3");
28. cmd1.setMnemonic('F');
29. cmd2.setMnemonic('S');
30. cmd3.setMnemonic('T');
31.
32. cmd1.setCursor(new Cursor(Cursor.HAND_CURSOR));
33. cmd2.setCursor(new Cursor(Cursor.HAND_CURSOR));
Output
1. import javax.swing.*;
2. import java.awt.event.*;
3. import javax.swing.border.*;
4. import java.awt.*;
5. public class CardLayoutDemo implements MouseListener,ActionListener
6. {
7. JPanel panel1,panel2,panel3;
8. JFrame jf;
9. JPanel main1;
10. JButton cb1,cb2;
11. CardLayout clo;
12. CardLayoutDemo()
13. {
14. objectCreator();
15. layoutProvider();
16. effectsProvider();
17. addListeners();
18. addControlsToPanels();
19. addPanelsToJFrame();
20. jf.setSize(300,300);
21. jf.show();
22. }
23. void layoutProvider()
24. {
25. jf.getContentPane().setLayout(new BoxLayout(jf.getContentPane(),BoxLayout.
Y_AXIS));
26. main1.setLayout(new CardLayout());
27. }
28. void objectCreator()
29. {
30. jf=new JFrame("Book Store");
31. panel1=new JPanel();
32. panel2=new JPanel();
33. panel3=new JPanel();
34. main1=new JPanel();
Output
Checkbox Demonstration
1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. import javax.swing.border.*;
5. class CheckBox1 implements ItemListener
6. {
7. String selectedtext="";
8. JFrame jf;
9. JPanel p1,p2,p3,p4;
10. JCheckBox win98,win2000,winxp,IP,AMD,celeron;
11. ButtonGroup bg1,bg2;
12. JLabel displaylbl,titlelbl;
13. CheckBox1()
14. {
15. objectCreator();
16. effectsProvider();
17. layoutProvider();
18. register();
19. addControlsToPanels();
20. addPanelsToJFrame();
21. jframeShow();
22. }
23. void objectCreator()
24. {
25. bg1=new ButtonGroup();
26. bg2=new ButtonGroup();
27. win98=new JCheckBox("win98");
28. win2000=new JCheckBox("win2000");
29. winxp=new JCheckBox("winxp");
30. IP=new JCheckBox("IP");
66. celeron.setBackground(Color.red);
67.
68. displaylbl.setBackground(Color.red);
69. displaylbl.setForeground(Color.green);
70. displaylbl.setFont(new Font("Arial",Font.BOLD,18));
71. }
72. void addControlsToPanels()
73. {
74. p1.add(titlelbl);
75. p2.add(win98);
76. p2.add(win2000);
77. p2.add(winxp);
78. p3.add(IP);
79. p3.add(AMD);
80. p3.add(celeron);
81. p4.add(displaylbl);
82.
83. bg1.add(win98);
84. bg1.add(win2000);
85. bg1.add(winxp);
86.
87. bg2.add(IP);
88. bg2.add(AMD);
89. bg2.add(celeron);
90.
91. }
92. void addPanelsToJFrame()
93. {
94. jf.getContentPane().add(p1);
95. jf.getContentPane().add(p2);
96. jf.getContentPane().add(p3);
97. jf.getContentPane().add(p4);
98. }
99. void register()
100. {
101. win98.addItemListener(this);
102. win2000.addItemListener(this);
103. winxp.addItemListener(this);
104. IP.addItemListener(this);
105. AMD.addItemListener(this);
106. celeron.addItemListener(this);
107.
108. }
109. void jframeShow()
110. {
111. jf.setExtendedState(Frame.MAXIMIZED_BOTH);
112. jf.show();
113. }
114. void layoutProvider()
115. {
116. p1.setLayout(new FlowLayout(FlowLayout.CENTER,20,50));
117. p2.setLayout(new FlowLayout(FlowLayout.CENTER,50,50));
118. p3.setLayout(new FlowLayout(FlowLayout.CENTER,50,50));
119. p4.setLayout(new FlowLayout(FlowLayout.CENTER,50,50));
120. jf.getContentPane().setLayout(new BoxLayout(jf.getContentPane(),BoxLayout.
Y_AXIS));
121. }
122. public void itemStateChanged(ItemEvent ie)
123. {
124. if (win98.isSelected())
125. displaylbl.setText("win98");
126. if (win2000.isSelected())
127. displaylbl.setText("win2000");
128. else if(winxp.isSelected())
129. displaylbl.setText("winxp");
130. if (IP.isSelected())
131. displaylbl.setText("IP");
132. if (AMD.isSelected())
133. displaylbl.setText("AMD");
134. else if(celeron.isSelected())
135. displaylbl.setText("celeron");
136. }//method
137.
138. public static void main(String args[])
139. {
140. CheckBox1 cb=new CheckBox1();
141. }
142. }
Output
/* if win98 is clicked*/
1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. import javax.swing.border.*;
5. class Checkbox implements ActionListener,ItemListener
6. {
7. ImageIcon normal;
8. ImageIcon rollover;
9. ImageIcon selected;
10. String selectedtext="";
115. jf.getContentPane().add(p2);
116. jf.getContentPane().add(p3);
117. jf.getContentPane().add(p4);
118. }
119. void register()
120. {
121. result1cmd.addActionListener(this);
122. result2cmd.addActionListener(this);
123. choicerdo1.addItemListener(this);
124. choicerdo2.addItemListener(this);
125. choicerdo3.addItemListener(this);
126. choicerdo4.addItemListener(this);
127. choice1rdo1.addItemListener(this);
128. choice1rdo2.addItemListener(this);
129. choice1rdo3.addItemListener(this);
130. choice1rdo4.addItemListener(this);
131. result1cmd.addActionListener(this);
132. result2cmd.addActionListener(this);
133. }
134. void jframeShow()
135. {
136. jf.setExtendedState(Frame.MAXIMIZED_BOTH);
137. jf.show();
138. }
139. void layoutProvider()
140. {
141. p1.setLayout(new FlowLayout(FlowLayout.CENTER,20,50));
142. p2.setLayout(new FlowLayout(FlowLayout.CENTER,50,50));
143. p3.setLayout(new FlowLayout(FlowLayout.CENTER,50,50));
144. p4.setLayout(new FlowLayout(FlowLayout.CENTER,50,50));
145. jf.getContentPane().setLayout(new BoxLayout(jf.getContentPane(),BoxLayout.
Y_AXIS));
146. }
147. public void itemStateChanged(ItemEvent ie)
148. {
149. if (choicerdo1.isSelected())
150. correct1lbl.setText("Good, You had 10 Marks");
151. else
152. correct1lbl.setText("Badd, You had 0 Marks");
153. if (choice1rdo3.isSelected())
154. correct2lbl.setText("Good, You had 10 Marks");
155. else
156. correct2lbl.setText("Badd, You had 0 Marks");
157. }//method
158.
159. public void actionPerformed(ActionEvent ae)
160. {
161. if (ae.getSource()==result1cmd)
162. {
163. if (selectedtext.equalsIgnoreCase("JDK"))
164. correct1lbl.setText("Good, You had 10 Marks");
165. else
166. correct1lbl.setText("bad, You had 0 Marks");
167. }
168. if (ae.getSource()==result2cmd)
169. {
170. if (selectedtext.equalsIgnoreCase("Core Java"))
171. correct2lbl.setText("Good, You had 10 Marks");
172. else
173. correct2lbl.setText("bad, You had 0 Marks");
174. }
175. }//method
176. public static void main(String args[])
177. {
178. new Checkbox();
179. }
180. }
Output
Colorchooser Demonstration
1. import javax.swing.*;
2. import javax.swing.event.*;
3. import java.awt.*;
4. import java.awt.event.*;
5. import javax.swing.border.*;
6. class ColorChooser1
7. {
8. JFrame frame;
9. JColorChooser jcc;
10. JPanel panel;
11. ColorChooser1()
12. {
Output
Dialog Demonstration
1. import java.io.*;
2. import javax.swing.*;
3. import java.awt.*;
4. import java.awt.event.*;
5. public class Dialog implements ActionListener
6. {
7. JDialog jd;
8. JLabel jl;
9. JButton jb;
10. JFrame jf;
11. public void showDialog()
12. {
13. jf=new JFrame("Dialog Box");
14. jd=new JDialog(jf,true);
15. jd.setTitle("Password Success");
16. jd.getContentPane().setLayout(null);
17. jl=new JLabel("Click Ok to go to Server");
18. jb=new JButton("OK");
19. jb.addActionListener(this);
20. jl.setBounds(10,40,300,25);
21. jb.setBounds(70,80,100,25);
22. jd.getContentPane().add(jl);
23. jd.getContentPane().add(jb);
24. jd.setBounds(160,70,400,150);
25. jf.setExtendedState(Frame.MAXIMIZED_BOTH);
26. jf.show();
27. jd.show();
28. }
29. public void actionPerformed(ActionEvent ae)
30. {
31. if ((ae.getActionCommand()).equals("OK"))
32. {
33. jd.setVisible(false);
34. jd=null;
35. }//if
36. }//method
37.
38. public static void main(String args[])
39. {
40. Dialog d=new Dialog();
41. d.showDialog();
42. }
43. }//class
Output
GraphicsEnvironment Usage
import java.awt.*;
class LocalScreenDemo
GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
Rectangle r=ge.getMaximumWindowBounds();
System.out.println(r.width);
System.out.println(r.height);
Point p=ge.getCenterPoint();
System.out.println(p.x);
System.out.println(p.y);
Output
800
566
400
283
FileChooser Demonstration
1. import javax.swing.*;
2. import javax.swing.event.*;
3. import java.awt.event.*;
4. import java.awt.*;
5. import java.io.*;
6. import javax.swing.filechooser.*;
7. class ExampleFileFilter extends javax.swing.filechooser.FileFilter
8. {
9. String filename;
10. String extension;
11. public boolean accept(File f)
12. {
13. if (f.isDirectory())
14. {
15. return true;
16. }
17. else
18. {
19. filename=f.getName();
20. extension=filename.substring(filename.lastIndexOf("."),filename.length());
21. if (extension.equalsIgnoreCase(".jpg"))
22. return true;
23. else
24. return false;
25. }
26. }
27. public String getDescription() {
28. return null;
29. }
30. }
31.
32. public class FileChooser implements ActionListener
33. {
34. //JLabel lbl=new JLabel();
35. JFileChooser jfc=new JFileChooser();
36. JFrame frame=new JFrame("My Frame");
37. JButton opencmd=new JButton("Open");
38. JButton savecmd=new JButton("Save");
39. JButton clearcmd=new JButton("Clear");
40. JTextField text =new JTextField(20);
41. JPanel panel=new JPanel();
42. JPanel panel1=new JPanel();
43. FileChooser()
44. {
45. try
46. {
47. panel.add(opencmd);
48. panel.add(savecmd);
49. panel.add(clearcmd);
50. panel1.add(text);
51. //panel1.add(lbl);
52. frame.setLayout(new BorderLayout());
53. frame.add(panel,BorderLayout.SOUTH);
54. frame.add(panel1,BorderLayout.CENTER);
55. jfc.setFileFilter(new ExampleFileFilter());
56. jfc.setCurrentDirectory(new File("h:/javapsna/swing"));
57. //setExtendedState(Frame.MAXIMIZED_BOTH);
58. frame.setSize(500,500);
59. //setVisible(true);
60. opencmd.addActionListener(this);
61. savecmd.addActionListener(this);
62. clearcmd.addActionListener(this);
63. frame.show();
64. }
65. catch(Exception e)
66. {}
67. }
103. }//try
104. catch(Exception e)
105. { }
106. }
107. public static void main(String args[])
108. {
109. FileChooser fc=new FileChooser();
110. }
111. }
Output
FoucsEvent Demonstration
1. import java.util.*;
2. import javax.swing.*;
3. import java.awt.event.*;
4. import javax.swing.border.*;
5. import java.awt.*;
6. import java.text.*;
7. public class JFocusEventDemo implements TextListener,FocusListener
8. {
9. Date timedate;
10. JFrame jf;
11. JTextField text1,text2,text3;
12. JLabel label1,label2;
13. JPanel panel1;
14. JFocusEventDemo()
15. {
16. objectCreator();
17. effectsProvider();
18. addControlsToPanels();
19. addPanelsToJFrame();
20. register();
21. jf.setSize(300,300);
22. jf.show();
23. }
24. void objectCreator()
25. {
26. f=new JFrame("Book Store");
27. text1=new JTextField(20);
28. text2=new JTextField(20);
29. text3=new JTextField(20);
30. panel1=new JPanel();
31. label1=new JLabel("Focus Gained=");
32. label2=new JLabel("Focus Lost =");
33. }
34. void effectsProvider()
35. {
36. text1.setName("Text1");
37. text2.setName("Text2");
38. text3.setName("Text3");
39. jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
40. }
41. void addControlsToPanels()
42. {
43. panel1.add(text1);
44. panel1.add(text2);
45. panel1.add(text3);
46. panel1.add(label1);
47. panel1.add(label2);
48. }
49.
50. void addPanelsToJFrame()
51. {
52. jf.getContentPane().add(panel1,BorderLayout.CENTER);
53. }
54. void register()
55. {
56. text1.addFocusListener(this);
57. text2.addFocusListener(this);
58. text3.addFocusListener(this);
59. //text1.addTextListener(this);
60. }
61. public void textValueChanged(TextEvent te)
62. {
63. JTextField jtf=(JTextField)(te.getSource());
64. System.out.println(jtf.getText());
65. }
66. public void focusGained(FocusEvent fe)
67. {
68. label2.setText("Focus Lost=");
69. System.out.println("Oppoiste="+fe.getOppositeComponent());
70. if (fe.getOppositeComponent()!=null)
71. {
72. label2.setText(label2.getText()+fe.getOppositeComponent().getName());
73. }
74. }
75. public void focusLost(FocusEvent fe)
76. {
77. label1.setText("Focus Gained=");
78. if (fe.getOppositeComponent()!=null)
79. {
80. label1.setText(label1.getText()+fe.getOppositeComponent().getName());
81. System.out.println(label1.getText()+fe.getOppositeComponent().getName());
82. }
83. }
84.
85. public static void main(String args[])
86. {
87. new JFocusEventDemo();
88. }
89. }
/* WindowConstants
DO_NOTHING_ON_CLOSE
HIDE_ON_CLOSE
DISPOSE_ON_CLOSE
EXIT_ON_CLOSE
*/
Output
Focus Gained=Text3Text3
Oppoiste=javax.swing.JTextField[Text2,34,30,224x20,layout=javax.swing.plaf.basic.Basic
TextUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,border=javax.swing.plaf.BorderUIRes
ource$CompoundBorderUIResource@14a9972,flags=296,maximumSize=,minimumSize=,preferredSi
ze=,caretColor=javax.swing.plaf.ColorUIResource[r=51,g=51,b=51],disabledTextColor=java
x.swing.plaf.ColorUIResource[r=184,g=207,b=229],editable=true,margin=javax.swing.plaf.
InsetsUIResource[top=0,left=0,bottom=0,right=0],selectedTextColor=javax.swing.plaf.Col
orUIResource[r=51,g=51,b=51],selectionColor=javax.swing.plaf.ColorUIResource[r=184,g=2
07,b=229],columns=20,columnWidth=11,command=,horizontalAlignment=LEADING]
Process terminated
Label Demonstration
1. import java.awt.*;
2. import java.awt.event.*;
3. class LabelTextDemo implements ActionListener,TextListener,FocusListener,WindowL
istener
4. {
5. Frame frame;
6. Panel panel1,panel2,panel3,panelfirst;
7. Label namelbl,agelbl,passwordlbl;
8. TextField nametxt,agetxt,passwordtxt;
9. Button okcmd,clearcmd,quitcmd;
10. Label namedisplaylbl,agedisplaylbl,passworddisplaylbl;
11. LabelTextDemo()
12. {
13. objectCreator();
14. effectsProvider();
15. layoutProvider();
16. register();
17. addControlsToFrame();
18. }
19. void layoutProvider()
20. {
21. frame.setLayout(new BorderLayout());
22. panelfirst.setLayout(new BorderLayout());
23. panel1.setLayout(new GridLayout(3,2,400,50));
24. panel2.setLayout(new GridLayout(1,3,200,300));
25. panel3.setLayout(new GridLayout(2,2));
26. }
27. void objectCreator()
28. {
29. frame=new Frame("Label Text Demo");
30. panel1=new Panel();
31. panel2=new Panel();
32. panel3=new Panel();
33. panelfirst=new Panel();
34. namelbl=new Label("Enter The Name",Label.RIGHT);
35. agelbl=new Label("Enter The Age",Label.RIGHT);
36. passwordlbl=new Label("Enter The Password",Label.RIGHT);
37. nametxt=new TextField(10);
38. nametxt.setName("name");
39. agetxt=new TextField();
40. agetxt.setName("age");
41. passwordtxt=new TextField(10);
42. passwordtxt.setName("Password");
43. okcmd=new Button("Ok");
44. clearcmd=new Button("Clear");
45. quitcmd=new Button("Quit");
46. namedisplaylbl=new Label("Display Name");
47. agedisplaylbl=new Label("Display Age");
48. passworddisplaylbl=new Label("Display PassWord");
49. }
50. void effectsProvider()
51. {
52. //frame.setBackground(Color.yellow);
53. namedisplaylbl.setBackground(new Color(100,0,0));
54. passwordtxt.setEchoChar('*');
55. //jf.SetDefaultCloseOperation(jf.
56. }
57. void register()
58. {
59. okcmd.addActionListener(this);
60. clearcmd.addActionListener(this);
61. quitcmd.addActionListener(this);
62. //nametxt.addTextListener(this);
63. nametxt.addFocusListener(this);
64. agetxt.addFocusListener(this);
65. passwordtxt.addFocusListener(this);
66. frame.addWindowListener(this);
67. }
68. void addControlsToFrame()
69. {
70. panel1.add(namelbl);
71. panel1.add(nametxt);
72. panel1.add(agelbl);
73. panel1.add(agetxt);
74. panel1.add(passwordlbl);
75. panel1.add(passwordtxt);
76. panel2.add(okcmd);
77. panel2.add(clearcmd);
78. panel2.add(quitcmd);
79. frame.add(panel1,BorderLayout.NORTH);
80. panel3.add(namedisplaylbl);
81. panel3.add(agedisplaylbl);
82. panel3.add(passworddisplaylbl);
83. panelfirst.add(panel1,BorderLayout.NORTH);
84. panelfirst.add(panel2,BorderLayout.SOUTH);
85. frame.add(panelfirst,BorderLayout.NORTH);
86. frame.add(panel3,BorderLayout.SOUTH);
87. frame.setSize(300,300);
88. frame.show();
89. }
90. public void textValueChanged(TextEvent te)
91. {
92. System.out.println(((TextField)te.getSource()).getText());
93. System.out.println("TextListener="+nametxt.getText());
94. }
95. public void actionPerformed(ActionEvent ae)
96. {
97. System.out.println(ae.getActionCommand());
98. Button b=(Button)ae.getSource();
99. String str=b.getLabel();
100. if (str.equals("Ok"))
101. {
102. System.out.println(nametxt.getText());
103. System.out.println(agetxt.getText());
104. System.out.println(passwordtxt.getText());
105. nametxt.select(1,5);
106. nametxt.requestFocus();
107. System.out.println(nametxt.getSelectedText());
108. namedisplaylbl.setText("The Name is ="+nametxt.getText());
109. agedisplaylbl.setText("The age is ="+agetxt.getText());
110. passworddisplaylbl.setText("The password is ="+passwordtxt.getText());
111. agetxt.setEnabled(false);
112. agetxt.setEchoChar('?');
113. System.out.println(agetxt.echoCharIsSet());
114. System.out.println(agetxt.getEchoChar());
115. }
116. else if (str.equals("Clear"))
117. {
118. nametxt.setText("");
119. agetxt.setText("");
120. passwordtxt.setText("");
121. }
122. else if(str.equals("Quit"))
123. {
124. System.out.println("quit");
125. frame.remove(panelfirst);
126. frame.remove(panel3);
127. frame=null;
128. frame.setVisible(false);
129. }
130. }
166. }
167. public void windowOpened(WindowEvent we)
168. {
169. }
170. public static void main(String args[])
171. {
172. new LabelTextDemo();
173. }
174. }//class
Output
Window Activated
Window Iconified
Window DeActivated
Window DeIconified
Window Activated
Window Closing
JList Demonstration
1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. import javax.swing.event.*;
5. import javax.swing.border.*;
6. class AddRemoveDemo implements ActionListener,ListSelectionListener
7. {
8. JFrame jf;
9. JScrollPane scrollpane1,scrollpane2;
10. String str[]={"Dindigul","Madurai","Coimbatore","Trichy","Chennai","Natham
","Pudukottai"};
11. JList citylist;
12. JList citylistcopy;
13. JPanel panel1,panel2,panel3;
14. int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
15. int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
16. AddRemoveDemo()
17. {
18. objectCreator();
19. effectsProvider();
20. layoutProvider();
21. register();
22. addControlsToJFrame();
23. showJFrame();
24. }
25. void objectCreator()
26. {
27. citylist=new JList(str);
28. jf=new JFrame("Action Event Demo");
29. citylistcopy=new JList();
30. panel1=new JPanel();
31. panel2=new JPanel();
32. panel3=new JPanel();
56. citylist.setSelectionForeground(Color.red);
57. panel1.setBorder(new CompoundBorder(new LineBorder(Color.red,3,true),new T
itledBorder("ListEventListener")));
58. panel2.setBorder(new CompoundBorder(new LineBorder(Color.green,3,true),new
TitledBorder("AdjustmentEvent")));
59. panel3.setBorder(new CompoundBorder(new LineBorder(Color.yellow,3,true),ne
w TitledBorder("ListEventListener")));
60. citylist.setVisibleRowCount(5);
61. citylistcopy.setVisibleRowCount(5);
62. scrollpane1.getViewport().setView(citylist);
63. scrollpane2.getViewport().setView(citylistcopy);
64. }
65. void register()
66. {
67. citylist.addListSelectionListener(this);
68. }
69. public void actionPerformed(ActionEvent ae)
70. {
71. System.out.println(ae.getActionCommand());
72. }
73. public void valueChanged(ListSelectionEvent e)
74. {
75. JList list=(JList)e.getSource();
76. //int item[]=list.selectedIndices();
77. Object ob[]=list.getSelectedValues();
78. citylistcopy.setListData(ob);
79. }
80.
81. public static void main(String args[])
82. {
83. new AddRemoveDemo();
84. }
85. }
Output :
Menu Demonstration
1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. import javax.swing.border.*;
5. import java.applet.*;
6. import javax.swing.event.*;
7. public class MenuDemo1 implements ActionListener,MenuKeyListener
8. {
9. JFrame frame;
10. JMenuBar menubar;
11. JMenu coursemenu;
12. JMenu feesmenu;
13. JMenuItem mcomitem;
14. JMenuItem mscitem;
15. JMenuItem mbaitem;
16. JMenuItem mcomfeesitem;
17. JMenuItem mscfeesitem;
18. JMenuItem mbafeesitem;
19. MenuDemo1()
20. {
21. objectCreator();
22. effectsProvider();
23. layoutProvider();
24. register();
25. addControlsToPanels();
26. addPanelsToJFrame();
27. jframeShow();
28. }
29. void objectCreator()
30. {
31. frame=new JFrame("Menu");
32. menubar=new JMenuBar();
33. coursemenu=new JMenu("Course");
34. feesmenu=new JMenu("Fees");
35. mcomitem=new JMenuItem("M.Com.,");
36. mbaitem=new JMenuItem("MBA",65);
37. mscitem=new JMenuItem("M.Sc.,");
38. mcomfeesitem=new JMenuItem("M.Com Fees.,");
39. mbafeesitem=new JMenuItem("MBA Fees");
40. mscfeesitem=new JMenuItem("M.Sc., Fees");
41. }
42. void effectsProvider()
43. {
44. coursemenu.add(mcomitem);
45. coursemenu.add(mscitem);
46. coursemenu.add(mbaitem);
47. feesmenu.add(mcomfeesitem);
48. feesmenu.add(mbafeesitem);
49. feesmenu.add(mscfeesitem);
50. menubar.add(coursemenu);
51. menubar.add(feesmenu);
52. }
53. void addControlsToPanels()
54. {
55. }
56. void addPanelsToJFrame()
57. {
58. frame.setJMenuBar(menubar);
59. }
60. void register()
61. {
62. mcomitem.addMenuKeyListener(this);
63. mscitem.addMenuKeyListener(this);
64. mbaitem.addMenuKeyListener(this);
65. mcomfeesitem.addMenuKeyListener(this);
66. mscfeesitem.addMenuKeyListener(this);
67. mbafeesitem.addMenuKeyListener(this);
68. mbafeesitem.addActionListener(this);
69. }
70.
71. void jframeShow()
72. {
73. //frame.setExtendedState(Frame.MAXIMIZED_BOTH);
74. frame.setSize(300,300);
75. frame.show();
76. }
77. void layoutProvider()
78. {
79. }
80. public void menuKeyTyped(MenuKeyEvent e){
81. System.out.println("Menu Key Typed");
82. }
83. public void menuKeyPressed(MenuKeyEvent e){
84. System.out.println("Menu Key Pressed");
85. }
86. public void menuKeyReleased(MenuKeyEvent e){
87. System.out.println("Menu Key Released");
88. }
Output :
1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. import javax.swing.border.*;
5. class MenuDemo implements ActionListener
6. {
7. int x,y;
8. JPanel panel;
9. Timer timer=new Timer(1000,this);
10. JFrame frame;
11. JMenuBar menubar;
12. JMenu coursemenu;
13. JMenu feesmenu;
14. JMenuItem mcomitem;
15. JMenuItem mscitem;
16. JMenuItem mbaitem;
17. JCheckBoxMenuItem mcomfeesitem;
18. JMenuItem mscfeesitem;
19. JMenuItem mbafeesitem;
20. Graphics g;
21. MenuDemo()
22. {
23. //timer.addActionListener(this);
24. timer.start();
25. objectCreator();
26. effectsProvider();
27. layoutProvider();
28. register();
29. addControlsToPanels();
30. addPanelsToJFrame();
31. jframeShow();
32. }
33. void objectCreator()
34. {
35. panel=new JPanel();
36. frame=new JFrame("Menu");
37. //g=frame.getGraphics();
38. menubar=new JMenuBar();
39. coursemenu=new JMenu("Course");
40. feesmenu=new JMenu("Fees");
41. mcomitem=new JMenuItem("M.Com.,",65);
42. mbaitem=new JMenuItem("MBA");
43. mscitem=new JMenuItem("M.Sc.,");
44. mcomfeesitem=new JCheckBoxMenuItem("M.Com Fees.,",new ImageIcon("Ms.jpg"),
true);
45. mbafeesitem=new JMenuItem("MBA Fees");
46. mscfeesitem=new JMenuItem("M.Sc., Fees");
47. }
48. void effectsProvider()
49. {
50. coursemenu.add(mcomitem);
51. coursemenu.addSeparator();
52. coursemenu.add(mscitem);
53. coursemenu.addSeparator();
54. coursemenu.add(mbaitem);
55. coursemenu.addSeparator();
56. coursemenu.add(new JButton("Button"));
57. feesmenu.add(mcomfeesitem);
58. feesmenu.addSeparator();
59. feesmenu.add(mbafeesitem);
60. feesmenu.addSeparator();
61. feesmenu.add(mscfeesitem);
62. menubar.add(coursemenu);
63. feesmenu.addSeparator();
64. menubar.add(feesmenu);
65. }
66.
67. void addControlsToPanels()
68. {
69. }
70. void addPanelsToJFrame()
71. {
72. frame.getContentPane().add(panel);
73. frame.setJMenuBar(menubar);
74. }
75. void register()
76. {
77. mbaitem.addActionListener(this);
78. mcomitem.addActionListener(this);
79. mscitem.addActionListener(this);
80. mcomfeesitem.addActionListener(this);
81. }
82.
83. public void actionPerformed(ActionEvent ae)
84. {
85. if (ae.getSource()==mcomitem)
86. System.out.println("Mcom is selected");
87.
88. if (ae.getSource()==mcomfeesitem)
89. {
90. if (mcomfeesitem.getState()==true)
91. System.out.println("Mcom Fees Item is selected");
92. else
93. System.out.println("Mcom Fees Item is deselected");
94. }
95. }
96.
97. void jframeShow()
98. {
99. //frame.setExtendedState(Frame.MAXIMIZED_BOTH);
100. frame.setSize(300,300);
101. frame.show();
102. }
1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. import javax.swing.border.*;
5. class MenuDemo implements ActionListener
6. {
7. int x,y;
8. JPanel panel;
9. Timer timer=new Timer(1000,this);
10. JFrame frame;
11. JMenuBar menubar;
12. JMenu coursemenu;
13. JMenu feesmenu;
14. JMenuItem mcomitem;
15. JMenuItem mscitem;
16. JMenuItem mbaitem;
17. JCheckBoxMenuItem mcomfeesitem;
18. JMenuItem mscfeesitem;
19. JMenuItem mbafeesitem;
20. Graphics g;
21. MenuDemo()
22. {
23. //timer.addActionListener(this);
24. timer.start();
25. objectCreator();
26. effectsProvider();
27. layoutProvider();
28. register();
29. addControlsToPanels();
30. addPanelsToJFrame();
31. jframeShow();
32. }
33. void objectCreator()
34. {
35. panel=new JPanel();
36. frame=new JFrame("Menu");
37. //g=frame.getGraphics();
38. menubar=new JMenuBar();
39. coursemenu=new JMenu("Course");
40. feesmenu=new JMenu("Fees");
41. mcomitem=new JMenuItem("M.Com.,",65);
42. mbaitem=new JMenuItem("MBA");
43. mscitem=new JMenuItem("M.Sc.,");
44. mcomfeesitem=new JCheckBoxMenuItem("M.Com Fees.,",new ImageIcon("Ms.jpg"),
true);
45. mbafeesitem=new JMenuItem("MBA Fees");
46. mscfeesitem=new JMenuItem("M.Sc., Fees");
47. }
48. void effectsProvider()
49. {
50. coursemenu.add(mcomitem);
51. coursemenu.addSeparator();
52. coursemenu.add(mscitem);
53. coursemenu.addSeparator();
54. coursemenu.add(mbaitem);
55. coursemenu.addSeparator();
56. coursemenu.add(new JButton("Button"));
57. feesmenu.add(mcomfeesitem);
58. feesmenu.addSeparator();
59. feesmenu.add(mbafeesitem);
60. feesmenu.addSeparator();
61. feesmenu.add(mscfeesitem);
62. menubar.add(coursemenu);
63. feesmenu.addSeparator();
64. menubar.add(feesmenu);
65. }
66.
67. void addControlsToPanels()
68. {
69. }
70. void addPanelsToJFrame()
71. {
72. frame.getContentPane().add(panel);
73. frame.setJMenuBar(menubar);
74. }
75. void register()
76. {
77. mbaitem.addActionListener(this);
78. mcomitem.addActionListener(this);
79. mscitem.addActionListener(this);
80. mcomfeesitem.addActionListener(this);
81. }
82.
83. public void actionPerformed(ActionEvent ae)
84. {
85. if (ae.getSource()==mcomitem)
86. System.out.println("Mcom is selected");
87.
88. if (ae.getSource()==mcomfeesitem)
89. {
90. if (mcomfeesitem.getState()==true)
91. System.out.println("Mcom Fees Item is selected");
92. else
93. System.out.println("Mcom Fees Item is deselected");
94. }
95. }
96.
97. void jframeShow()
98. {
99. //frame.setExtendedState(Frame.MAXIMIZED_BOTH);
100. frame.setSize(300,300);
101. frame.show();
102. }
1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. import javax.swing.event.*;
5. class MenuDemo implements ActionListener,PopupMenuListener,MenuListener
6. {
7. JFrame frame;
8. JMenuBar menubar;
9. JMenu imagemenu,fontmenu;
10. JMenuItem loaditem,exititem;
45. imagemenu.addSeparator();
46. imagemenu.add(combobox);
47. imagemenu.addSeparator();
48. imagemenu.add(exititem);
49. imagemenu.addSeparator();
50.
51. fontmenu.add(fontcmb);
52. fontmenu.addSeparator();
53. fontmenu.add(sizecmb);
54. fontmenu.addSeparator();
55. fontmenu.add(checkbolditem);
56.
57. combobox.addActionListener(this);
58. fontcmb.addActionListener(this);
59. sizecmb.addActionListener(this);
60. clearcmd.addActionListener(this);
61. combobox.addPopupMenuListener(this);
62. fontcmb.addPopupMenuListener(this);
63. sizecmb.addPopupMenuListener(this);
64. imagemenu.addMenuListener(this);
65. fontmenu.addMenuListener(this);
66.
67. addmenutxt.addKeyListener(new KeyAdapter()
68. {
69. public void keyPressed(KeyEvent ke)
70. {
71. if (ke.getKeyCode()==ke.VK_ENTER)
72. {
73. fontmenu.add(new JMenuItem(addmenutxt.getText(),new ImageIcon("MS.jpg")));
74. addmenutxt.setText("");
75. }
76. }
77. });
78.
114. {
115. System.out.println("2");
116. fontmenu.setPopupMenuVisible(false);
117. }
118. if ((ae.getSource()==combobox))
119. {
120. System.out.println("3");
121. imagemenu.setPopupMenuVisible(false);
122. }
123. }
124.
125. public void menuCanceled(MenuEvent e){
126. Component c=((JMenu)e.getSource()).getComponent();
127. c.setForeground(Color.blue);
128. }
129. public void menuDeselected(MenuEvent e){
130. Component c=((JMenu)e.getSource()).getComponent();
131. c.setForeground(Color.yellow);
132. }
133. public void menuSelected(MenuEvent e){
134. Component c=((JMenu)e.getSource()).getComponent();
135. c.setForeground(Color.red);
136. }
137.
138. public void popupMenuWillBecomeInvisible(PopupMenuEvent e){}
139. public void popupMenuCanceled(PopupMenuEvent e){}
140. public void popupMenuWillBecomeVisible(PopupMenuEvent ae)
141. {
142. System.out.println("popup 1");
143. if ((ae.getSource()==fontcmb) || (ae.getSource()==sizecmb))
144. {
145. System.out.println("popup 2");
146. fontmenu.setPopupMenuVisible(true);
147. }
148. if ((ae.getSource()==combobox))
149. {
150. System.out.println("popup 3");
151. imagemenu.setPopupMenuVisible(true);
152. }
153. }
154. }
Output
1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. import javax.swing.border.*;
5. class MenuDemo implements ActionListener
6. {
7. int x,y;
8. JPanel panel;
9. Timer timer=new Timer(1000,this);
10. JFrame frame;
11. JMenuBar menubar;
12. JMenu coursemenu,feessubmenu;
13. JMenu feesmenu;
14. JMenuItem mcomitem;
15. JMenuItem mscitem;
16. JMenuItem mbaitem;
17. JCheckBoxMenuItem mcomfeesitem;
18. JMenuItem mscfeesitem;
19. JMenuItem mbafeesitem;
20. JMenuItem a,b,c,d;
21. Graphics g;
22. MenuDemo()
23. {
24. //timer.addActionListener(this);
25. timer.start();
26. objectCreator();
27. effectsProvider();
28. layoutProvider();
29. register();
30. addControlsToPanels();
31. addPanelsToJFrame();
32. jframeShow();
33. }
34. void objectCreator()
35. {
36. panel=new JPanel();
37. frame=new JFrame("Menu");
38. //g=frame.getGraphics();
39. menubar=new JMenuBar();
40. coursemenu=new JMenu("Course");
41. feesmenu=new JMenu("Fees");
42. feessubmenu=new JMenu("feessub");
77.
78. void addControlsToPanels()
79. {
80. }
81. void addPanelsToJFrame()
82. {
83. frame.getContentPane().add(panel);
84. frame.setJMenuBar(menubar);
85. }
86. void register()
87. {
88. mbaitem.addActionListener(this);
89. mcomitem.addActionListener(this);
90. mscitem.addActionListener(this);
91. mcomfeesitem.addActionListener(this);
92. }
93.
94. public void actionPerformed(ActionEvent ae)
95. {
96. if (ae.getSource()==mcomitem)
97. System.out.println("Mcom is selected");
98.
99. if (ae.getSource()==mcomfeesitem)
100. {
101. if (mcomfeesitem.getState()==true)
102. System.out.println("Mcom Fees Item is selected");
103. else
104. System.out.println("Mcom Fees Item is deselected");
105. }
106. }
107.
108. void jframeShow()
109. {
110. //frame.setExtendedState(Frame.MAXIMIZED_BOTH);
111. frame.setSize(400,400);
112. frame.show();
113. }
114. void layoutProvider()
115. {
116. }
117.
118. public static void main(String args[])
119. {
120. new MenuDemo();
121. }
122. }
Output
1. import java.awt.*;
2. import java.awt.event.*;
3. import javax.swing.*;
4. class MouseEventDemo implements MouseListener,MouseMotionListener
5. {
6. JFrame frame=new JFrame("My Frame");
7. JButton okcmd=new JButton("Ok");
8. JButton cancelcmd=new JButton("Cancle");
9. MouseEventDemo()
10. {
11. frame.setLayout(new FlowLayout());
12. frame.add(okcmd);
13. frame.add(cancelcmd);
14. //frame.setExtendedState(Frame.MAXIMIZED_BOTH);
15. frame.setSize(300,300);
16. frame.show();
17. okcmd.addMouseListener(this);
18. cancelcmd.addMouseListener(this);
19. frame.addMouseMotionListener(this);
20. }
21. public void mouseExited(MouseEvent me)
22. {
23. Object obj=me.getSource();
24. JButton jb=(JButton)obj;
25. if (jb==okcmd)
26. jb.setBackground(Color.blue);
27. else
28. jb.setBackground(Color.yellow);
29. }
30. public void mousePressed(MouseEvent me)
31. {
32.
33. }
34. public void mouseClicked(MouseEvent me)
35. {
36. }
37. public void mouseReleased(MouseEvent me)
38. {
39. }
40. public void mouseEntered(MouseEvent me)
41. {
42. Object obj=me.getSource();
43. JButton jb=(JButton)obj;
44. jb.setBackground(Color.red);
45. }
46. public void mouseDragged(MouseEvent me)
47. {
48. System.out.println("Dragged x="+me.getX());
49. System.out.println("Dragged y="+me.getY());
50. }
51. public void mouseMoved(MouseEvent me)
52. {
53. System.out.println("Moved x="+me.getX());
54. System.out.println("Moved y="+me.getY());
55. }
56. public static void main(String args[])
57. {
58. new MouseEventDemo();
59. }
60. }
Output
Moved x=23
Moved y=93
Moved x=32
Moved y=96
Moved x=43
Moved y=96
Msgbox Demonstration
1. import javax.swing.*;
2. import javax.swing.event.*;
3. import java.awt.*;
4. import java.awt.event.*;
5. class MsgBox
6. {
7. JFrame frame=new JFrame("Message");
8. JOptionPane pane;
9. MsgBox()
10. {
11. frame.setExtendedState(Frame.MAXIMIZED_BOTH);
12. frame.show();
13. /*pane=new JOptionPane("Are You Sure");
14. int result=pane.showConfirmDialog(frame,"Are We Sure","Confirm Dialog",JOp
tionPane.YES_NO_CANCEL_OPTION,JOptionPane.ERROR_MESSAGE);
15. System.out.println(result);
16. if (result==JOptionPane.YES_OPTION)
17. {
18. System.out.println("Yes is Pressed");
19. }
20. else if (result==JOptionPane.NO_OPTION)
21. {
22. System.out.println("NO is Pressed");
23. }
24. else if (result==JOptionPane.CANCEL_OPTION)
25. {
26. System.out.println("CANCEL is Pressed");
27. }
28.
29. result=pane.showConfirmDialog(frame,"Are We Sure","Confirm Dialog",JOption
Pane.YES_NO_OPTION);
30. System.out.println(result);
31. result=pane.showConfirmDialog(frame,"Are We Sure","Confirm Dialog",JOption
Pane.YES_NO_OPTION,JOptionPane.ERROR_MESSAGE);
32. System.out.println(result);
33. result=pane.showConfirmDialog(frame,"Are We Sure","Confirm Dialog",JOption
Pane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE);
34. System.out.println(result);
35. result=pane.showConfirmDialog(frame,"Are We Sure","Confirm Dialog",JOption
Pane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE);
36. System.out.println(result);
the icon from the pluggable Look and Feel: ERROR_MESSAGE, INFORMATION_MESSAGE,
WARNING_MESSAGE, QUESTION_MESSAGE, or PLAIN_MESSAGE
67. */
Output
1. import javax.swing.*;
2. import javax.swing.event.*;
3. import java.awt.event.*;
4. import java.awt.*;
5. import java.io.*;
6.
7. class PasswordField extends JFrame implements ActionListener
8. {
9. Container con;
Output
1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. import javax.swing.border.*;
5. import java.applet.*;
6. import javax.swing.event.*;
7. class JPopupMenuDemo implements ActionListener
8. {
9. JPanel panel;
10. JTextArea jta;
11. JPopupMenu pop;
12. JFrame frame;
13. JMenu menu;
14. JMenuItem red=new JMenuItem("Red");
15. JMenuItem green=new JMenuItem("Green");
16. JMenuItem blue=new JMenuItem("Blue");
17. JPopupMenuDemo()
18. {
19. frame=new JFrame();
20. //pop=new JPopupMenu();
21. menu=new JMenu();
22. red.setName("red");
23. green.setName("green");
24. blue.setName("blue");
25. menu.add(green);
26. menu.addSeparator();
27. menu.add(red);
28. menu.addSeparator();
29. menu.add(blue);
30. pop=menu.getPopupMenu();
31. red.addActionListener(this);
32. green.addActionListener(this);
33. blue.addActionListener(this);
34. frame.getContentPane().setLayout(new BorderLayout());
35. jta=new JTextArea();
36. panel=new JPanel();
37. panel.setLayout(new BorderLayout());
38. JScrollPane jsp=new JScrollPane(jta,ScrollPaneConstants.VERTICAL_SCROLLBAR
_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
39. //panel.add(jsp,BorderLayout.CENTER);
40. frame.add(panel,BorderLayout.CENTER);
41. panel.addMouseListener(new MouseAdapter()
42. {
43. public void mouseClicked(MouseEvent me)
44. {
45. // To check right click
46. if (me.getModifiers()==InputEvent.BUTTON3_MASK)
47. {
48. pop.show(panel,me.getX(),me.getY());
49. }//if
50. }//method
51. }//inner class
52. );
53. frame.setExtendedState(Frame.MAXIMIZED_BOTH);
54. frame.show();
55. }
56. public void actionPerformed(ActionEvent ae)
57. {
58. String color=ae.getActionCommand();
59. System.out.println(color);
60. if (color.equals("Red"))
61. {
62. panel.setBackground(Color.blue);
63. }
64. else if (color.equals("Green"))
65. {
66. panel.setBackground(Color.green);
67. }
68. else if (color.equals("Blue"))
69. {
70. panel.setBackground(Color.blue);
71. }
72. }
73. public void popupMenuWillBecomeVisible(PopupMenuEvent pe)
74. {
75. }
76. public void popupMenuCanceled(PopupMenuEvent e)
77. {
78. }
79. public static void main(String args[])
80. {
81. new JPopupMenuDemo();
82. }
83. }
Output
ProgressBar Demonstration
1. import javax.swing.border.*;
2. import javax.swing.*;
3. import java.awt.*;
4. import java.awt.event.*;
5. import java.util.concurrent.*;
6. class ProgressBarDemo implements Runnable
7. {
8. JFrame frame;
9. JProgressBar progressbar;
10. Thread t;
11. JPanel panel1;
12. ProgressBarDemo()
13. {
14. objectCreator();
15. effectsProvider();
16. layoutProvider();
17. addControlsToPanels();
18. addPanelsToJFrame();
19. jframeShow();
20. t.start();
21. }
22. void effectsProvider()
23. {
24. panel1.setBorder(new TitledBorder("Progress Bar Demo"));
25. }
26. void objectCreator()
27. {
28. panel1=new JPanel();
29. frame=new JFrame("Progress Bar Demo");
30. progressbar=new JProgressBar(JProgressBar.HORIZONTAL,1,100);
31. progressbar.setStringPainted(true);
32. progressbar.setString("Progressing...");
33. t=new Thread(this);
34. progressbar.setBorderPainted(true);
35. }
36. void addControlsToPanels()
37. {
38. panel1.add(progressbar);
39. }
40. void addPanelsToJFrame()
41. {
42. frame.getContentPane().add(panel1);
43. }
44. void layoutProvider()
45. {
46. panel1.setLayout(new FlowLayout(FlowLayout.CENTER));
47. frame.getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER));
48. }
49. public void run()
50. {
51. while (true)
52. {
53. try
54. {
55. Thread.sleep(50);
56. }
57. catch(Exception e){}
58. if (progressbar.getValue()<=100)
59. progressbar.setValue(progressbar.getValue()+1);
60. else
61. {
62. t=null;
63. frame.getContentPane().remove(progressbar);
64. }
65. }//while
66. }//method
67. void jframeShow()
68. {
69. frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
70. frame.setVisible(true);
71. }
72. public static void main(String args[])
73. {
74. new ProgressBarDemo();
75. }
Output
1. import java.awt.*;
2. import java.awt.image.*;
3. import javax.swing.*;
4. import com.sun.image.codec.jpeg.*;
5. import java.io.*;
6. public class RobotDemo implements Runnable
7. {
8. int i=0;
9. Robot robot;
10. RobotDemo()
11. {
12. try
13. {
14. robot=new Robot();
15. //robot.delay(100);
16. Thread t=new Thread(this);
17. t.start();
18. }
19. catch(Exception e){}
20. }
21. public void run()
22. {
23. try
24. {
25. while (true)
26. {
27. BufferedImage bi=robot.createScreenCapture(new Rectangle(8
00,600));
28. FileOutputStream fout=new FileOutputStream("a"+i+".jpg");
32. fout.close();
33. i++;
34. Thread.sleep(5000);
35. }
36. }
37. catch(Exception e)
38. {
39. System.out.println(e);
40. }
41. }
42.
43. public static void main(String args[])
44. {
45. new RobotDemo();
46. }
47. }
Output
Scrollbar Demonstration
1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. import javax.swing.border.*;
5. class JScrollBarDemo implements AdjustmentListener,ActionListener
6. {
7. JFrame frame;
8. JTextField redtxt,bluetxt,greentxt;
9. JPanel northpanel,centerpanel,mainpanel,southpanel;
10. JLabel titlelbl,redlbl,greenlbl,bluelbl,previewlbl;
11. JScrollBar redscrollbar,greenscrollbar,bluescrollbar;
12. JButton applycmd;
13. int redvalue,greenvalue,bluevalue;
14. JScrollBarDemo()
15. {
16. objectCreator();
17. effectsProvider();
18. layoutProvider();
19. register();
20. addControlsToPanels();
21. addPanelsToJFrame();
22. jframeShow();
23. }
24.
25. void objectCreator()
26. {
27. titlelbl=new JLabel("JSCROLLBAR",JLabel.CENTER);
28. frame=new JFrame("Scrollbar demo");
29. redtxt=new JTextField(10);
30. greentxt=new JTextField(10);
31. bluetxt=new JTextField(10);
32. northpanel=new JPanel();
33. centerpanel=new JPanel();
69. greenlbl.setForeground(Color.green);
70. bluelbl.setForeground(Color.blue);
71. previewlbl.setForeground(Color.red);
72. applycmd.setForeground(Color.red);
applycmd.setBackground(Color.black);
73.
74. redlbl.setFont(new Font("Arial",Font.BOLD,16));
75. greenlbl.setFont(new Font("Arial",Font.BOLD,16));
76. bluelbl.setFont(new Font("Arial",Font.BOLD,16));
77. previewlbl.setFont(new Font("Arial",Font.BOLD,16));
78. applycmd.setFont(new Font("Arial",Font.BOLD,16));
79.
80.
81. //jsb.setMinimum(0);
82. //jsb.setMaximum(255);
83.
84.
85. // redscrollbar.setValue(255);
86. }
87. void addControlsToPanels()
88. {
89. northpanel.add(titlelbl,BorderLayout.CENTER);
90. centerpanel.add(redlbl);
91. centerpanel.add(greenlbl);
92. centerpanel.add(bluelbl);
93. centerpanel.add(redtxt);
94. centerpanel.add(greentxt);
95. centerpanel.add(bluetxt);
96. centerpanel.add(redscrollbar);
97. centerpanel.add(greenscrollbar);
98. centerpanel.add(bluescrollbar);
99.
100. southpanel.add(previewlbl,BorderLayout.WEST);
101. previewlbl.setBorder(new BevelBorder(BevelBorder.LOWERED));
102. southpanel.add(applycmd,BorderLayout.EAST);
103.
104. mainpanel.add(northpanel,BorderLayout.NORTH);
105. mainpanel.add(centerpanel,BorderLayout.CENTER);
106. mainpanel.add(southpanel,BorderLayout.SOUTH);
107.
108. }
109. void addPanelsToJFrame()
110. {
111. frame.add(mainpanel,BorderLayout.CENTER);
112. redscrollbar.setPreferredSize(new Dimension(50,200));
113. greenscrollbar.setPreferredSize(new Dimension(50,200));
114. bluescrollbar.setPreferredSize(new Dimension(50,200));
115.
116. }
117. void register()
118. {
119. applycmd.addActionListener(this);
120. redscrollbar.addAdjustmentListener(this);
121. greenscrollbar.addAdjustmentListener(this);
122. bluescrollbar.addAdjustmentListener(this);
123. }
124. void jframeShow()
125. {
126. frame.setSize(750,600);
127. frame.show();
128.
129. }
130. void layoutProvider()
131. {
132. frame.getContentPane().setLayout(new BorderLayout());
133. mainpanel.setLayout(new BorderLayout());
134. northpanel.setLayout(new BorderLayout());
135. centerpanel.setLayout(new FlowLayout(FlowLayout.CENTER,90,30));
136. southpanel.setLayout(new BorderLayout());
137. }
138.
139.
140. public void adjustmentValueChanged(AdjustmentEvent ae)
141. {
142. if (ae.getSource()==redscrollbar)
143. {
144. redlbl.setForeground(new Color(redscrollbar.getValue(),0,0));
167. {
168. String caption=ea.getActionCommand();
169. if (caption.equals("Apply"))
170. {
171. northpanel.setBackground(new Color(redvalue,greenvalue,blueval
ue));
172.
173. southpanel.setBackground(new Color(redvalue,greenvalue,blueval
ue));
174.
175. centerpanel.setBackground(new Color(redvalue,greenvalue,blueva
lue));
176. }//if
177. }//method
178.
179.
180.
181. public static void main(String args[])
182. {
183.
184. JScrollBarDemo jsb=new JScrollBarDemo();
185. }
186. }
1. /*CTRL = 18
2. SHIFT =17
3. ALT =24
4. */
5. import java.awt.*;
6. import java.awt.event.*;
7. import javax.swing.*;
8. class First implements ActionListener
9. {
10. JFrame frame;
11. JButton cmd;
12. First()
13. {
14. frame=new JFrame("My Frame");
15. cmd=new JButton("Click");
16. frame.setLayout(new FlowLayout());
17. frame.add(cmd);
18. cmd.addActionListener(this);
19. frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
20. frame.show();
21. }
22.
23. public static void main(String args[])
24. {
25. First f=new First();
26. //first f1=new First();
27. }
28. public void actionPerformed(ActionEvent ae)
29. {
30. System.out.println("Action Event Raised"+ae.getActionCommand());
31. System.out.println("getModifiers="+ae.getModifiers());
32. if (ae.getModifiers()==24)
33. System.out.println("Alt Key Pressed");
Output
getModifiers=16
Mouse Pressed
getModifiers=18
getModifiers=24
getModifiers=17
JSlider Demonstration
1. import javax.swing.*;
2. import java.awt.*;
3. import javax.swing.event.*;
4. import java.awt.event.*;
5. import javax.swing.border.*;
6. class Slider implements ChangeListener
7. {
8. JFrame frame;
9. JPanel panel;
10. JSlider slider1,slider2,slider3;
11. JLabel redlbl,greenlbl,bluelbl;
12. JPanel redpanel,greenpanel,bluepanel;
13. Slider()
14. {
15. redpanel=new JPanel();
16. greenpanel=new JPanel();
17. bluepanel=new JPanel();
18. redlbl=new JLabel();
19. greenlbl=new JLabel();
20. bluelbl=new JLabel();
21. slider1=new JSlider();
22. slider2=new JSlider(0,255,1);
23. slider3=new JSlider(SwingConstants.VERTICAL,0,255,1);
24. slider1.addChangeListener(this);
25. slider2.addChangeListener(this);
26. slider3.addChangeListener(this);
27. panel=new JPanel();
28. frame=new JFrame();
29. frame.getContentPane().setLayout(new BorderLayout());
30. panel.setLayout(new FlowLayout(FlowLayout.CENTER,50,100));
31. redlbl.setForeground(Color.white);
32. bluelbl.setForeground(Color.white);
33. greenlbl.setForeground(Color.white);
34. redlbl.setFont(new Font("Arial",Font.BOLD,20));
35. greenlbl.setFont(new Font("Arial",Font.BOLD,20));
36. bluelbl.setFont(new Font("Arial",Font.BOLD,20));
37. redpanel.add(redlbl);
38. greenpanel.add(greenlbl);
39. bluepanel.add(bluelbl);
40. redpanel.setBorder(new LineBorder(Color.red));
41. greenpanel.setBorder(new LineBorder(Color.red));
42. bluepanel.setBorder(new LineBorder(Color.red));
43. panel.add(redpanel);
44. panel.add(slider1);
45. panel.add(greenpanel);
46. panel.add(slider2);
47. panel.add(bluepanel);
48. panel.add(slider3);
49. frame.getContentPane().add(panel);
50. frame.setSize(500,500);
51. frame.show();
52. }
53. public void stateChanged(ChangeEvent ce)
54. {
55. int r=0;
56. int g=0;
57. int b=0;
58. if (ce.getSource()==slider1)
59. {
60. redlbl.setText(Integer.toString(slider1.getValue()));
61. redpanel.setBackground(new Color(slider1.getValue(),0,0));
62. }
63. else if (((JSlider)(ce.getSource()))==slider2)
64. {
65. greenlbl.setText(Integer.toString(slider2.getValue()));
66. greenpanel.setBackground(new Color(0,slider2.getValue(),0));
67. }
68. else if (((JSlider)(ce.getSource()))==slider3)
69. {
70. bluelbl.setText(Integer.toString(slider3.getValue()));
71. bluepanel.setBackground(new Color(0,0,slider3.getValue()));
72. }
73. panel.setBackground(new Color(slider1.getValue(),slider2.getValue(),slider
3.getValue()));
74. }
75. public static void main(String args[])
76. {
77. new Slider();
78. }
79. }
Output
JTable Demonstration
1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. import javax.swing.border.*;
5. import javax.swing.event.*;
6. class TableDemo implements ListSelectionListener
7. {
8. JFrame frame;
9. JTable table;
10. JScrollPane jsp;
11. JLabel titlelbl;
12. int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
13. int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
14. JPanel p1,p2;
15. TableDemo()
16. {
17. objectCreator();
18. effectsProvider();
19. layoutProvider();
20. register();
21. addControlsToPanels();
22. addPanelsToJFrame();
23. jframeShow();
24. }
25.
26. void objectCreator()
27. {
28. frame=new JFrame("Table");
29. String data[][]={{"Rama.A","55","50"},{"Raja.B","65","60"},{"Ragava.A","55
","50"}};
30. String column[]={"Name","Tamil","English"};
31. table=new JTable(data,column);
32. jsp=new JScrollPane(table,v,h);
68. {
69. table.print();
70. }
71. catch(Exception e){}
72. //table.addListSelectionListener(this);
73. }
74. void jframeShow()
75. {
76. frame.setExtendedState(Frame.MAXIMIZED_BOTH);
77. frame.show();
78. /*try
79. {
80. table.print();
81. }
82. catch(Exception e){}*/
83. }
84. void layoutProvider()
85. {
86. p2.setLayout(new BorderLayout());
87. p1.setLayout(new FlowLayout(FlowLayout.CENTER));
88. frame.getContentPane().setLayout(new BorderLayout());
89. }
90. public void valueChanged(ListSelectionEvent ce)
91. {
92. JTable jt=(JTable)ce.getSource();
93. int rowno=jt.getSelectedRow();
94. System.out.println(jt.getValueAt(rowno,0).toString());
95. }
96. public static void main(String args[])
97. {
98. new TableDemo();
99. }
100. }
Output
JToolBar Demonstration
1. import java.awt.*;
2. import javax.swing.*;
3. class JToolBarDemo
4. {
5. public static void main(String args[])
6. {
7. JFrame jframe=new JFrame();
8. jframe.setExtendedState(Frame.MAXIMIZED_BOTH);
9. JToolBar jtoolbar=new JToolBar("Name",JToolBar.HORIZONTAL);
10. jtoolbar.setLayout(new FlowLayout(FlowLayout.CENTER,0,0));
11. for (int i=0;i<10;i++)
12. {
13. jtoolbar.add(new JButton("Button "+i));
14. jtoolbar.addSeparator();
15. }
Output
Chapter 35 - Applet
In java to develop GUI application there are two types of window available.
Frame
Applet
In simple words, applet is the interfacing tool between web development and
swing. It means swing functionalities can be applied by using applet in web.
The main reason is that applet is highly secured tool, because sun assures
applet cannot make any changes in client machine. Because applet is used in
web.
Each one applet program must have following html tab to run applet in
appletviewer tool
</applet>
applet viewer
Type
appletviewer <filename>.java
Html calling
So applet program should be compiled separately and html file should be created
separately. Then you can run html page and view the output in browser.
Note:
This method will be called when applet is initialized in memory. This method is
called only once.
When applet is shown in screen and after the applet is loaded and initialized.
And it is called when the user returns to the HTML page that contains the
applet after browsing through other webpages.
Applet Tag
Codebase – specify the folder path of applet, if applet class and html file are
in different folder.
(Left,Right,Top,Bottom)
Ex. Codebase
</applet>
1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. import java.applet.*;
5. /* <applet code="KeyEventsDemo" width=500 height=500>
6. </applet> */
7. public class KeyEventsDemo extends Applet implements KeyListener,MouseListener,M
ouseMotionListener
8. {
9. int x,y;
10. JFrame jf;
11. String msg="";
12. public void init()
13. {
14. objectCreator();
15. effectsProvider();
16. register();
17. layoutProvider();
18. addControlsToJFrame();
19. //showJFrame();
20. setBackground(Color.red);
21. requestFocus();
22. }
23. public void register()
24. {
25. addKeyListener(this);
26. addMouseListener(this);
27. addMouseMotionListener(this);
28. }
29. public void mouseEntered(MouseEvent me)
30. {
31. showStatus("Mouse Entered into Frame");
32. msg="Mouse is in x="+me.getX()+"y="+me.getY();
33. repaint();
34. }
35. public void mouseExited(MouseEvent me)
36. {
37. showStatus("Mouse Exited into Frame");
38. }
39. public void mousePressed(MouseEvent me)
40. {
41. showStatus("Mouse Pressed into Frame");
42. msg="Mouse is in x="+me.getX()+"y="+me.getY();
43. repaint();
44. }
45. public void mouseReleased(MouseEvent me)
46. {
47. showStatus("Mouse Released into Frame");
48. msg="Mouse is in x="+me.getX()+"y="+me.getY();
49. repaint();
50. }
86. {
87. x=me.getX();
88. y=me.getY();
89. msg="Mouse Dragged"+"x="+x+"y="+y;
90. repaint();
91. }
92. public void mouseMoved(MouseEvent me)
93. {
94. x=me.getX();
95. y=me.getY();
96. msg="Mouse Moved "+"x="+x+"y="+y;
97. repaint();
98. }
99.
100. public void keyTyped(KeyEvent ke)
101. {
102. msg=ke.getKeyChar()+" is pressed";
103. System.out.println("From key Typed getKeyChar() ="+msg);
104. System.out.println("From Key Typed getKeyCode()="+ke.getKeyCode());
105. repaint();
106. }
107.
108. void objectCreator()
109. {
110. jf=new JFrame("Key Board Events");
111. }
112. void effectsProvider()
113. {
114. jf.setSize(600,500);
115. }
116. void layoutProvider()
117. {
118.
119. }
120. void addControlsToJFrame()
121. {
122.
123. }
124. /*void showJFrame()
125. {
126. jf.setSize(500,400);
127. jf.show();
128. }*/
129. /*public static void main(String args[])
130. {
131. KeyEventsDemo ked=new KeyEventsDemo();
132. }*/
133. public void paint(Graphics g)
134. {
135. g.drawString(msg,x,y);
136. }
137. }
Output
1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. import javax.swing.border.*;
5. import javax.swing.tree.*;
6. import java.util.*;
7. /*
8. <applet code="TreeDemo" width=800 height=500>
9. </applet>
10. */
11.
12. public class TreeDemo extends JApplet
13. {
14. JTree tree;
15. JTextField jtf;
16. public void init()
17. {
18. setLayout(new BorderLayout());
19. DefaultMutableTreeNode top=new DefaultMutableTreeNode("Top");
20. DefaultMutableTreeNode courses=new DefaultMutableTreeNode("Courses");
21. top.add(courses);
22. DefaultMutableTreeNode mcom=new DefaultMutableTreeNode("M.Com.,");
23. courses.add(mcom);
24. DefaultMutableTreeNode msc=new DefaultMutableTreeNode("M.Sc.,");
25. courses.add(msc);
26. DefaultMutableTreeNode mba=new DefaultMutableTreeNode("MBA");
27. courses.add(mba);
28.
29. DefaultMutableTreeNode fees=new DefaultMutableTreeNode("Fees");
30. top.add(fees);
34. fees.add(mscfees);
35. DefaultMutableTreeNode mbafees=new DefaultMutableTreeNode("MBA Fees");
36. fees.add(mbafees);
37.
38. /*DefaultMutableTreeNode top1=new DefaultMutableTreeNode("Top");
39. DefaultMutableTreeNode courses1=new DefaultMutableTreeNode("Courses");
40. top1.add(courses1);
41. DefaultMutableTreeNode mcom1=new DefaultMutableTreeNode("M.Com.,");
42. courses.add(mcom1);
43. DefaultMutableTreeNode msc1=new DefaultMutableTreeNode("M.Sc.,");
44. courses.add(msc1);
45. DefaultMutableTreeNode mba1=new DefaultMutableTreeNode("MBA");
46. courses.add(mba1);
47.
48. DefaultMutableTreeNode fees1=new DefaultMutableTreeNode("Fees");
49. top1.add(fees1);
50. DefaultMutableTreeNode mcomfees1=new DefaultMutableTreeNode("M.Com., Fees"
);
51. fees1.add(mcomfees1);
52. DefaultMutableTreeNode mscfees1=new DefaultMutableTreeNode("M.Sc., Fees");
53. fees1.add(mscfees1);
54. DefaultMutableTreeNode mbafees1=new DefaultMutableTreeNode("MBA Fees");
55. fees1.add(mbafees1);
56. Vector vector=new Vector();
57. vector.addElement(top);
58. vector.addElement(top1);*/
59.
60. tree=new JTree(top);
61.
Output
1. import java.awt.*;
2. import javax.swing.*;
3. import java.applet.*;
4. /* <applet code="ImageDemo" width=600 height=600>
5. </applet>
6. */
7. public class ImageDemo extends Applet
8. {
9. JPanel jp;
10. JLabel jl;
11. Image img;
12. public void init()
13. {
14. jp=new JPanel();
15. img=getImage(getDocumentBase(),"Wave.jpg");
16. jl=new JLabel(new ImageIcon(img));
17. jp.add(jl);
18. add(jp,BorderLayout.CENTER);
19. jp.setPreferredSize(new Dimension(500,500));
20. }
21. }
Output
JTabbedPane Demonstration
1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. import javax.swing.event.*;
5. import java.util.*;
6. /* <applet code="TabbedPane" width=600 height=600>
7. </applet> */
8.
9. public class TabbedPane extends JApplet implements ChangeListener
10. {
11. JTabbedPane jtp=new JTabbedPane();
12. JPanel firstpanel=new JPanel();
13. JPanel secondpanel=new JPanel();
14. JPanel thirdpanel=new JPanel();
15. JScrollPane jsp1,jsp2,jsp3;
16. JList fontnamelist;
17. JList fontsizelist;
18. JList fontstylelist;
19. GraphicsEnvironment ge;
20. public void init()
21. {
22. ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
23. String fontnames[]=ge.getAvailableFontFamilyNames();
24. fontnamelist=new JList(fontnames);
25. String style[]={"Bold","Italic","BoldItalic","Normal"};
26. fontstylelist=new JList(style);
27. Vector v=new Vector();
28. for (int i=8;i<=100;i+=2)
29. v.addElement(i);
30. fontsizelist=new JList(v);
31. setLayout(new BorderLayout());
32. jsp1=new JScrollPane(fontnamelist,ScrollPaneConstants.VERTICAL_SCROLLBAR_A
LWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
Output
Binary Literals
17.
18. System.out.println("aByte="+aByte);
19. System.out.println("aShort="+aShort);
20. System.out.println("anInt1="+anInt1);
21. System.out.println("anInt2="+anInt2);
22. System.out.println("aLong="+aLong);
23. }
24. }
25.
26. Output
27.
28. aByte=2
29. aShort=41
30. anInt1=5
31. anInt2=5
32. aLong=161
Any number of underscore characters (_) can appear anywhere between digits in a
numerical literal to separate digits in groups to understand better.
float pi = 3.14_15F;
String in Switch
We can use String in switch statement. Runtime checks the string literals
equality using String.equals().
28. }
29.
30. Output:
31.
32. Start of work week
Since 1.7, type inference in right side not required. Note that diamond
operator <> must be specified in right side. Otherwise compiler throws warning
"HashMap is a raw type. References to generic type HashMap<K,V> should be
parameterized"
try with resources closes an object declared within try automatically when try
block is completed or try block is exited even abruptly.
try {
return br.readLine();
} finally {
1.7 Example
return br.readLine();
In above example br is a resource and will be closed after the try block by
runtime. The resource must be the subclass of java.lang.AutoCloseable
interface(added in 1.7).
The object must be completely declared and used within try block. This is the
drawback of this feature.
In Java SE 7 and later, a single catch block can handle more than one type of
exception. This feature can reduce code duplication.
try
//statements
logger.log(ex);
throw ex;
logger.log(ex);
throw ex;
try
//statements
logger.log(ex);
throw ex;
throw in 1.7
Example 1
3. void m1()
4. {
5. try {
6. throw new ArrayIndexOutOfBoundsException();
7. } catch (Exception e) {
8. System.out.println("m1=" + e.getClass().getName());
9. }
10.
11. }
12.
13. public static void main(String[] args) {
14. // TODO Auto-generated method stub
15. try {
16. RethrowExceptionDemo rethrowExceptionDemo = new RethrowExcepti
onDemo();
17. rethrowExceptionDemo.m1();
18.
19. } catch (Exception e) {
20. System.out.println(e.getClass().getName());
21. }
22.
23. }
24. }
25.
26. Output :
27.
28. m1=java.lang.ArrayIndexOutOfBoundsException
Example 2
In Example 1, the same method catches the exception thrown by try block.
In Example 2, the same method doesn't have the catch block so the caller catch
catches the exception thrown method.
In Example 3, there is no catch in the same method and caller so runtime catche
s the exception.
Example 3:
2.
3. void m1() {
4. throw new ArrayIndexOutOfBoundsException();
5. }
6.
7. public static void main(String[] args) {
8. // TODO Auto-generated method stub
9.
10. RethrowExceptionDemo rethrowExceptionDemo = new RethrowExceptionDe
mo();
11. rethrowExceptionDemo.m1();
12.
13. }
14.
15. }
16.
17. Output:
18.
19. Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
20. at com.book.java7.prgs.RethrowExceptionDemo.m1(RethrowExceptionDemo.ja
va:6)
21. at com.book.java7.prgs.RethrowExceptionDemo.main(RethrowExceptionDemo.
java:13)
It is the first LTS(Long Term Support Version), released at March 2014. Its
support details as below.
Method References
Method references is the feature to create the reference for static method.
ClassName::methodName
As we know above program is the normal one to invoke the static method.
1. class MyStringClass
2. {
3. static String processString()
4. {
5. return "test";
6. }
7. }
8.
9. public class MethodReference1 {
10.
11. public static void main(String args[])
12. {
13. String outStr=MyStringClass.processString();
14. }
15. }
1. //Functional Interface
2. interface MyStringInterface {
3. String processString();
4. }
5.
6. //Class with static method to return the string
7. class MyStringClass {
8. static String processString() {
9. return "test";
10. }
11. }
12.
13. public class MethodReference1 {
14. //static method to accept MyStringInterface type as the parameter and invoke the processString() /
/ of MyStringInterface.
15. static String invokeProcessString(MyStringInterface myStringInterface) {
16. return myStringInterface.processString();
17. }
18.
19. public static void main(String args[]) {
20. String outStr = invokeProcessString(MyStringClass::processString);
21. System.out.println(outStr);
22. }
23. }
24. Output
25. test
1. // A functional interface
2. interface StringInterface {
3. String processString(String str);
4. }
5.
6. class StringClass1 {
7. static String returnString(String str) {
8. return str + " StringClass1";
9. }
10. }
11.
12. class StringClass2 {
13. static String returnString(String str) {
14. return str + " StringClass2";
15. }
16. }
17.
18. class StringClass3 {
19. String returnString(String str) {
20. return str + " StringClass3";
21. }
22. }
23.
24. class InvokeStringClass {
First two statements are the examples of Static Method References and third one
statement is the example of Instance Method Reference.
outStr = InvokeStringClass.invokeProcessString(StringClass1::returnString,
inStr);
outStr = InvokeStringClass.invokeProcessString(StringClass2::returnString,
inStr);
outStr = InvokeStringClass.invokeProcessString(new
StringClass3()::returnString, inStr);
Constructor Reference
The below one parameter constructor accepts V value and getValue() returns the
same V value.
Empty constructor added to avoid the compile time error as if any parameterized
constructor is added the empty constructor should be added explicitly.
The statement 2 assigns value=100 of MyClass and returns the MyClass object.
MyClass(V value) {
this.value = value;
1. //Functional Interface
2. interface ObjectFactoryInterface<T, V> {
3. T func(V v);
4. }
5.
6. class MyClass<V> {
7. V value;
8. MyClass(V value) {
9. this.value = value;
10. }
11. MyClass() {
12. value = null;
13. }
14. V getValue() {
15. return value;
16. };
17. }
18.
19. public class ConstructorReferenceDemo {
20. public static void main(String args[]) {
21. ObjectFactoryInterface<MyClass, Integer> objectFactoryInterface1 =
MyClass<Integer>::new;
22. MyClass<Integer> myClass1 = objectFactoryInterface1.func(100);
23. System.out.println("val in mc is " + myClass1.getValue());
24.
25. ObjectFactoryInterface<MyClass, Double> objectFactoryInterface2 =
MyClass<Double>::new;
26. MyClass<Integer> myClass2 = objectFactoryInterface2.func(100D);
27. System.out.println("val in mc is " + myClass2.getValue());
28. }
29. }
Benefit
By using constructor reference and this example, we can create the interface to
accept to any type of parameter and returns any type of parameter. So this will
be useful to create the factory method design pattern.
Lets see the example program to understand how we can use Collectors better
1.
2. public class Employee {
3.
4. String name;
5.
6. int salary;
7.
8. public String getName() {
9. return name;
10. }
11.
12. public void setName(String name) {
13. this.name = name;
14. }
15.
16. public int getSalary() {
17. return salary;
18. }
19.
20. public void setSalary(int salary) {
21. this.salary = salary;
22. }
23.
24. }
1. package java12Project;
2.
3. import java.util.ArrayList;
4. import java.util.List;
5. import java.util.stream.Collectors;
6.
7. public class CollectorsDemo {
8.
9. public static void main(String[] args) {
10. // TODO Auto-generated method stub
11.
12. List<String> names = new ArrayList<>();
13. List<Employee> employeesList = new ArrayList<>();
14.
15. Employee employee1 = new Employee();
16. employee1.name = "Ram";
17. employee1.salary = 6000;
18.
19. Employee employee2 = new Employee();
20. employee2.name = "Raj";
21. employee2.salary = 3000;
22.
23. employeesList.add(employee1);
24. employeesList.add(employee2);
25.
26. names.add("Ram");
27. names.add("Raju");
28.
29. // Convert elements to strings and concatenate them, separated by commas
30. String joinedNames = names.stream().map(Object::toString).collect(Collectors.joining(", ")
);
31.
32. System.out.println("joinedNames=" + joinedNames);
33.
34. // Compute sum of salaries of employee
35.
36. int total = employeesList.stream().collect(Collectors.summingInt(Employee::getSalary));
37.
38. System.out.println(total);
39.
40. }
41.
42. }
43.
44. Output
45.
46. joinedNames=Ram, Raju
47. 9000
Lambda Experssions
1) Parameters for Lambda expressions: Parameter list that can be used in Lambda
expression empay paranthesis if no parameters.
2) Arrow Operator It divides Parameters for Lambda expressions and Lambda expression
Functional Interface
A functional interface is an interface that contains one and only one abstract method.
interface DrawingBoard{
1. @FunctionalInterface
2. interface DrawingBoard{
4. }
7. {
9. {
11. };
12. drawingBoard.startDrawing();
13. }
14. }
2 to 4 interface and only one method defined. Functional Interface should have
only one method.
12 invoking startDrawing()
1. @FunctionalInterface
2. interface DrawingBoard{
3. public void startDrawing(String color);
4. }
5. public class LambdaDemo1 {
6. public static void main(String[] args)
7. {
8. DrawingBoard drawingBoard =(String color)->
9. {
10. System.out.println("Start Drawing using "+color);
11. };
12. drawingBoard.startDrawing("Green);
13. }
14. }
8. Lambda Expression's argument list comes with parameter name and type.
1. import java.util.Arrays;
2. // Functional Interface with only one abstract method to accept array and return
array.
3. @FunctionalInterface
4. interface NumberInterface
5. {
6. int[] processArray(int num[]);
7. }
8.
9. public class LambdaExpressionBody {
10.
11. public static void main(String[] args) {
12. int numberArrays[]= {2,5,7,4,9,15,34};
13. /*
14. * Lambda expression returns ever Functional Interface type.
15. * In below example return type is NumberInterface
16. * paramArray is the input parameter for Lambda expression
17. * Lambda expression returns one Array
18. * */
19. NumberInterface numberInterface1 = (paramArray) -> {
20. return Arrays.stream(paramArray).filter(number -
> number % 2 != 0).toArray();
21.
22. };
23.
24. NumberInterface numberInterface2 = (paramArray) -> {
25. return Arrays.stream(paramArray).filter(number -
> number % 2 == 0).toArray();
26. };
27.
28. int oddArray[]= numberInterface1.processArray(numberArrays);
29. int evenArray[]= numberInterface2.processArray(numberArrays);
30.
31.
32. Arrays.stream(oddArray).forEach(System.out::println);
33. Arrays.stream(evenArray).forEach(System.out::println);
34. }
35. }
Arrays.stream(oddArray).forEach(System.out::println);
1. import java.util.ArrayList;
2. import java.util.Collections;
3. import java.util.Comparator;
4. import java.util.List;
5.
6. class Employee {
7. String name;
8. double salary;
9. int age;
10.
11. Employee(String name, double salary, int age) {
12. this.name = name;
13. this.salary = salary;
14. this.age = age;
15. }
16.
17. public String getName() {
18. return name;
19. }
20.
21. public void setName(String name) {
22. this.name = name;
23. }
24.
25. public double getSalary() {
26. return salary;
27. }
28.
29. public void setSalary(double salary) {
30. this.salary = salary;
31. }
32.
33. public int getAge() {
34. return age;
35. }
36.
37. public void setAge(int age) {
38. this.age = age;
39. }
40. }
41.
42. public class LambdaComparator {
43.
44. public static void main(String[] args) {
45.
46. List<Employee> listEmployees = getEmployees();
47.
48. System.out.println("Before Sort");
49. for (Employee employee : listEmployees) {
50. System.out.println(
51. "Name=" + employee.getName() + " Salary=" + employee.getSalary()
+ " Age=" + employee.getAge());
52. }
53.
54. // using lambda - java 8 - sort by salary ascending
55.
56. listEmployees.sort((Employee employee1, Employee
57. employee2)->(int)(employee1.getSalary()-employee2.getSalary()));
58.
59.
60. // using lambda - java 8 - sort by salary ascending - type is optional
61. listEmployees.sort((employee1, employee2) -
> (int) (employee1.getSalary() - employee2.getSalary()));
62.
63. System.out.println("============= After Sort by salary ascending =========
==========");
64.
65. for (Employee employee : listEmployees) {
66. System.out.println("Name=" + employee.getName() + " Salary=" + employ
ee.getSalary() + " Age=" + employee.getAge());
67. }
68.
69. // using lambda - java 8 - sort by salary descending
For Each
1. import java.util.ArrayList;
2. import java.util.List;
3. public class ForEachDemo {
4. public static void main(String args[])
5. {
6. List<String> itemsList = new ArrayList<>();
7. itemsList.add("A");
8. itemsList.add("B");
9. itemsList.add("C");
10. itemsList.add("D");
11. itemsList.add("E");
12.
13. // Class model
14. for (String item : itemsList) {
15. System.out.println("Item : " + item);
16. }
17. //Java 8 way for each
18. itemsList.forEach((itemStr) ->System.out.println("Item : " + itemStr ));
19. }
20. }
java.util.Stream
Methods of BaseStream
myList - ArrayList
myStream - stream
A terminal operation consumes the stream and produce a result, such as finding
the minimum value in the stream,or to execute some action. Once a stream has
been consumed, it cannot be reused.
Terminal Operation
Once a stream has been consumed, it cannot be reused. For example below
example will produce the below exception.
if (minVal.isPresent())
if (maxVal.isPresent())
desired because a stateful operation may require more than one pass to
complete.
List<Integer> distinctList =
numbersList.stream().distinct().collect(Collectors.toList());
In below example, we will get odd numbers from the list and the comments added
in the program to understand how each line works.
1. import java.util.ArrayList;
2. import java.util.List;
3. import java.util.stream.Collectors;
4.
5. public class StreamDemo1 {
6.
7. public static void main(String[] args) {
8. // TODO Auto-generated method stub
9.
10. List<Integer> numbersList = new ArrayList<>();
11. numbersList.add(5);
12. numbersList.add(7);
13. numbersList.add(2);
14. numbersList.add(9);
15. numbersList.add(4);
16.
17. List<Integer> oddNumbersList = numbersList.stream() // convert list to str
eam
18. .filter(number -
> number % 2 != 0) // filter() Stream to map reduce operation
19. .collect(Collectors.toList()); // collect and convert stream to a List
20.
21. oddNumbersList.forEach(System.out::println); // java 8 forEach style and S
ystem.out::println is the method to just print the list
22. }
23. }
24.
ParallelStream
Once a parallel stream has been obtained, operations on the stream can occur in
parallel way.
is specified by BaseStream.
you can use an iterator with a stream in just the same way that you do with a
collection. Iterators
1. import java.util.ArrayList;
2. import java.util.Iterator;
3. import java.util.List;
4.
5. public class StreamWithIteratorDemo {
6.
7. public static void main(String[] args) {
8. // TODO Auto-generated method stub
9. List<String> itemsList = new ArrayList<>();
10. itemsList.add("A");
11. itemsList.add("B");
12. itemsList.add("C");
13. itemsList.add("D");
14. itemsList.add("E");
15.
LocalDate
1. import java.time.LocalDate;
2. import java.time.LocalDateTime;
3. import java.time.Month;
4. import java.time.format.DateTimeFormatter;
5. import java.time.format.FormatStyle;
6. import java.util.Locale;
7.
8. public class LocalDateDemo {
9. public static void main(String args[]) {
10.
11. // LocaleDate
12. System.out.println(LocalDate.now());
13. System.out.println(LocalDate.of(2019, 6, 19));
14. System.out.println(LocalDate.of(2019, Month.JUNE, 19));
15. System.out.println(LocalDate.of(2019, Month.JUNE, 19));
16. System.out.println(LocalDate.ofYearDay(2019, 120));
17. System.out.println(LocalDate.parse("2019-05-20"));
18.
19. LocalDate date = LocalDate.now();
20. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-
yyyy");
21. String text = date.format(formatter);
22. System.out.println(text);
23. LocalDate parsedDate = LocalDate.parse("18-06-2019", formatter);
24.
25. System.out.println(parsedDate);
26. // LocaleDateTime
27. System.out.println(LocalDateTime.now());
28. System.out.println(LocalDateTime.of(2019, 6, 19, 10, 21));
29. System.out.println(LocalDateTime.of(2019, Month.JUNE, 19, 10, 21,
40));
30. System.out.println(LocalDateTime.of(2019, Month.JUNE, 19, 10, 21,
40, 403));
31.
32. // Date and Time Formatting with Locale
33.
34. LocalDateTime todayLocalDateTime = LocalDateTime.now();
35.
36. DateTimeFormatter localeSpecficFormatter = DateTimeFormatter.ofLoc
alizedDateTime(FormatStyle.MEDIUM) .withLocale(Locale.CANADA);
37. System.out.println("Locale Specific Date=" + localeSpecficFormatte
r.format(todayLocalDateTime));
38.
39. }
40. }
41.
42. Output
43.
44. 2019-06-18
45. 2019-06-19
46. 2019-06-19
47. 2019-06-19
48. 2019-04-30
49. 2019-05-20
50. 18-06-2019
51. 2019-06-18
52. 2019-06-18T18:38:30.470
53. 2019-06-19T10:21
54. 2019-06-19T10:21:40
55. 2019-06-19T10:21:40.000000403
56. Locale Specific Date=18-Jun-2019 6:38:30 PM
1. interface MyInterface {
2.
3. default void m1() {
4. System.out.println("m1()-default method of MyInterface");
5. }
6.
7. static void m2() {
8. System.out.println("m2()-static method of MyInterface");
9. }
10. }
11.
12. class MyClass implements MyInterface {
13. void invokeM1() {
14. m1();
15. }
16. }
17.
18. public class DefaultStaticMethodsInterfaceDemo {
19. public static void main(String args[]) {
20. MyInterface myInterface = new MyClass();
21. MyClass myClass = new MyClass();
22. myInterface.m1();
23. myClass.m1();
24. MyInterface.m2();
25. myClass.invokeM1();
26. }
27. }
28.
29. Output
30.
31. m1()-default method of MyInterface
32. m1()-default method of MyInterface
33. m2()-static method of MyInterface
34. m1()-default method of MyInterface
The m1() is default method and can be accessed using myInterface object and
myClass object. m2() is static, so it is invoked by using MyInterface.m2().
By using this feature, MyInterface class can be extended by many classess and
the default, private, static methods we can distribute common functionality to
all sub classes.
of()
In java 9, there is an easy way to create the List or Map using of().
In prior release we have to instantiate the object snf add(),to add the items
to the list and put() to add the key value pairs in Map.
Instead, we can use below example in easier way to create List or Map
of() List
The list created by of() is immutable and can't be modified (add, remove or
replace). The null will not be allowed. The below example illustrates how
of() can be used and exception raised when we use null or trying to change the
list.
1. import java.util.List;
2. public class ListOfMethodDemo {
3. public static void main(String args[]) {
4. List list1 = List.of();
5. List list2 = List.of("Ram", "Rama", "Ragava", "Anbu");
6.
7. System.out.println(list1);
8. System.out.println(list2);
9. // Below statements are not supported with of() list and raises the
10. // java.lang.UnsupportedOperationException
11. /*
12. * list1.add("Mani");
13. * list1.add(null);
14. */
15. }
16. }
17.
18. Output
19.
20. []
21. [Ram, Rama, Ragava, Anbu]
22.
1. import java.util.Map;
2.
3. public class MapOfMethodDemo {
4. public static void main(String args[]) {
5. Map map1 = Map.of();
6. Map map2 = Map.of("Name", "Ram", "Age", "23", "Salary", "24000");
7. map2.forEach((k, v) -> System.out.println(k + "," + v));
8. // Below statements are not supported with of() Map and raises the
9. // java.lang.UnsupportedOperationException
10. /*
11. * map2.put("City", "chennai");
12. * map2.put("MS",null);
13. */
14. }
15. }
16.
17. Output
18.
19. Age,23
20. Name,Ram
21. Salary,24000
JShell
The Java Shell tool (JShell) is added in java 9 to learn and evaluate Java
programming language. JShell is a Read-Evaluate-Print Loop (REPL), which
evaluates declarations, statements, and expressions as they are entered and
immediately shows the results.
jshell>
jshell>/exit
As like below you can enter and evaluate any java statements, and you will get the
results or errors immediatelty.
x ==> 45
| Error:
| byte b1=209423;
In below example the MyInterface9 has one private method m1() and it is called
by default void m2() of same interface.
The MyClass9 is the sub class of MyInterface9 and it has invokeM2() to call
m2() of MyInterface9, in turns it calls m1() private method of MyInterface9.
1. interface MyInterface9 {
2. private void m1() {
3. System.out.println("m1() - private method of MyInterface");
4. }
5. default void m2() {
6. m1();
7. }
8. }
9.
10. class MyClass9 implements MyInterface9 {
11. void invokeM2() {
12. m2();
13. }
14. }
15. public class PrivateMethodInterfaceDemo {
16. public static void main(String args[]) {
17. MyClass9 myClass9 = new MyClass9();
18. myClass9.invokeM2();
19. }
20. }
21.
22. Output
23.
24. m1() - private method of MyInterface
25.
In java7 try with resources were introduced. The feature allows the runtime to
close the objects automatically (The class must implement
java.io.AutoCloseable) when try block is completed. But the object must be
declared within the try block and this is the blockage of this feature.
In Java9, we can even use the objects that are declared outside can be used
within try with resources block.
1. import java.io.BufferedReader;
2. import java.io.FileNotFoundException;
3. import java.io.FileReader;
4. import java.io.IOException;
5.
6. public class TryWithResourceDemo {
7. public static void main(String[] args) throws FileNotFoundException, IOExcep
tion {
8. // TODO Auto-generated method stub
9. String path = "d:\\abc.txt";
10. BufferedReader br = new BufferedReader(new FileReader(path));
11. try (br) {
12. System.out.println(br.readLine());
13. }
14. System.out.println();
15. }
16. }
The BufferedReader declared outside of try block, used within try and it will
be closed automatically when try block is completed.
Prior we have packages to group classes and interfaces. These packages can be
imported to other classes using import statement.
Also we have access modifiers to control which properties of the class can be
used in other classes in different or same package.
Packages and import statements are completely compile time dependencies thus
these dependencies should be resolved at compile time. There is no way to tell
java about runtime dependencies.
Massive amounts of legacy code are there in monolithic approach, because the
Java platform has primarily been a monolithic.
Monolithic means one project comes with all the solutions and, the developers
depend Maven, Gradle like build tool to separate the project like service
layer, common layer, business layer for enterprise project development.
For example below image illustrates how the enterprise project is packed and
prior Java 9 Modular system, we completely depend other tool such Maven, Gradle
to acheive this.
Exapnded view
The above project is created using Maven. This is the structure of enterprise java
project. Ear file will contain all other modules as a jar file as like below.
EmployeeEAR.ear
EmployeeBusiness.jar
EmployeeDAO.jar
EmployeeDomain.jar
EmployeeFacade.jar
EmployeeRest.jar
EmployeeService.jar
EmployeeWeb.jar
Java 9 Modular System resolves this important problam by introducing Java 9 Modular
System.
Java 9 Platform Module System (JPMS), is the most important feature in java
since its inception and it is the result of Project Jigsaw.
Modularity adds a higher level of aggregation above packages. The key new
language element is the module—a uniquely named to group the packages, as well
as resources (such as images and XML files).
A Java module can specify which of the Java packages it contains that should be
visible to other Java modules using this module.
Each Java module needs a Java module descriptor named module-info.java which has
to be located in the corresponding module root directory. The module descriptor
specifies which packages a module exports, and what other modules the module
requires. These details will be explained in the following sections.
In below diagram
EmployeeBusiness |
EmployeeWeb |
In every one module, module-info.java will be automatically created and you can
see the code in that file as like above image.
1) Using File -> New Project create the Java Modular Application as like
"JavaModularApplication1" in above image
module EmployeeBusiness {
exports com.mycomp.info.layer;
module EmployeeDAO {
requires EmployeeBusiness;
package com.mycomp.dao.layer;
import com.mycomp.info.layer.EmployeeBusinessProcess;
/**
* @author Chidambaram
*/
Now the UI can invoke business logic in businss module and business module
invokes DAO module to do the database logics and return the result web module.
Method and constructor parameters can be var where as the formal parameter
should not be var and we should declare variable explicitely in formal
parameter.
var b=null;
Several new APIs have been added that facilitate the creation of unmodifiable
collections. The List.copyOf, Set.copyOf, and Map.copyOf methods create new
collection instances from existing instances. New
methods toUnmodifiableList, toUnmodifiableSet, and toUnmodifiableMap have been
added to the Collectors class in the Stream package. These allow the elements of
a Stream to be collected into an unmodifiable collection.
Lets see the example program below to understand to get the unmodifiable
collections.
Collector toUnmodifiableList()
1. package Java10Project;
2.
3. import java.util.ArrayList;
4. import java.util.Arrays;
5. import java.util.List;
6. import java.util.stream.Collectors;
7. import java.util.stream.Stream;
8.
9. public class CollectionChangesDemo2 {
10.
11. public static void main(String[] args) {
12. // TODO Auto-generated method stub
13.
14. List<String> namesList = new ArrayList<>();
15. namesList.add("Ram");
16. namesList.add("Ragu");
17. namesList.add("Sundar");
18. namesList.add("Anbu");
19. List<String> namesListCopy = List.copyOf(namesList);
20. namesList.add("Subbu");
21. System.out.println(namesList);
22. /*
23. * Below line throws Exception in thread "main"
24. * java.lang.UnsupportedOperationException
25. */
26.
27. // namesListCopy.add("Siva");
28. System.out.println(namesListCopy);
29.
30. List<Integer> intList = new ArrayList<Integer>();
31. intList.add(5);
32. intList.add(10);
33. intList.add(50);
34.
35. // toUnmodifiableList example
36. List<String> result = namesList.stream().collect(Collectors.toUnmo
difiableList());
37.
38. /*
39. * Below line throws Exception in thread "main"
40. * java.lang.UnsupportedOperationException
41. */
42. result.add("test");
43.
44. }
45. }
46.
47. Output
48.
49. [Ram, Ragu, Sundar, Anbu, Subbu]
50. [Ram, Ragu, Sundar, Anbu]
java.util.Optional orElseThrow()
1. import java.util.ArrayList;
2. import java.util.List;
3. import java.util.Optional;
4. import java.util.stream.Collectors;
5. import java.util.stream.Stream;
6.
7. public class OptionalOrElseThrowDemo {
8. // TODO Auto-generated method stub
9. public static void main(String args[]) {
10.
11. List<Integer> numbersList = new ArrayList<>();
12. numbersList.add(5);
13. numbersList.add(7);
14. numbersList.add(2);
15. numbersList.add(9);
16. numbersList.add(4);
17. numbersList.add(4);
18.
19. Stream<Integer> numberListStream = numbersList.stream();
20.
21. Optional<Integer> minVal = numberListStream.min(Integer::compare);
22.
23. if (minVal.isPresent())
24. /*
25. * java 8 way System.out.println("Minimum value: " + minVal.ge
t());
26. */
27. //java 10 way
28. System.out.println("Minimum value: " + minVal.orElseThrow());
29. }
30. }
31.
32. Output
33.
34. Minimum value: 2
For many years, the full code base of the JDK has been broken into numerous Mercurial repositories.
In JDK 9 there are eight repos: root, corba, hotspot, jaxp, jaxws, jdk, langtools, and nashorn.
During JDK's evolution it was separated into multiple repositories where as the bug fixes for even
single and simple bug fix affect different repositories and different commit operations, which increases
the over manitenance for current and future bug fixes.
For GC developers, implementing a new garbage collector requires knowledge about all those
various places, and how to extend them for their specific needs in prior releases.
A cleaner GC interface would make it much easier to implement new collectors, it would make the code
much cleaner, and simpler to exclude one or several collectors at build time. Adding a new garbage
collector should be a matter of implementing a well documented set of interfaces such as
CollectedHeap and BarrierSet, rather than figuring out all the places in HotSpot that needs
changing.
This is mainly a refactoring of HotSpot internal code and GC developers can use this technique to
create new GC interface.
Class-Data Sharing, introduced in JDK 5, allows a set of classes to be pre-processed into a shared
archive file that can then be memory-mapped at runtime to reduce startup time. It can also reduce
dynamic memory footprint when multiple JVMs share the same archive file.
Currently CDS only allows the bootstrap class loader to load archived classes. Application CDS
("AppCDS") extends CDS to allow the built-in system class loader (a.k.a., the "app class loader"), the
built-in platform class loader, and custom class loaders to load archived classes.
Make it both possible and cheap to stop individual threads and not just all
threads or none.
A handshake operation is a callback that is executed for each thread while that
thread is in a safepoint safe state. The callback is executed either by the
thread itself or by the VM thread while keeping the thread in a blocked state.
In new feature, the per thread operation will be performed on all threads as
soon as possible and they will continue to execute as soon as it’s own
operation is completed.
javah tool has been removed from JDK and which was used to generate C header
and source files that are needed to implement native methods.
Enhance java.util.Locale and related APIs to implement additional Unicode extensions of BCP 47
language tags. Support for BCP 47 language tags was initially added in Java SE 7, with support for the
Unicode locale extension limited to calendars and numbers. This JEP will implement more of the
extensions specified in the latest LDML specification, in the relevant JDK classes.
Provide a default set of root Certification Authority (CA) certificates in the JDK. Open-source the root
certificates in Oracle's Java SE Root CA program in order to make OpenJDK builds more attractive to
developers, and to reduce the differences between those builds and Oracle JDK builds
The Java language has undergone several changes since JDK 1.0 as well as
numerous additions of classes and packages to the standard library. Since
J2SE 1.4, the evolution of the Java language has been governed by the Java
Community Process (JCP), which uses Java Specification Requests (JSRs) to
propose and specify additions and changes to the Java platform. The language is
specified by the Java Language Specification (JLS); changes to the JLS are
managed under JSR 901.
Since java 9, proposed to change the release train to "one feature release every
six months" and LTS(Long Term Support) release once in three year. Currently
java 11 is the LTS release.
In prior releases, the version system idetified as JDK 7 Update 55, or JDK 7
Update 60. In this phrase
For example, the version standards don't reveal the answer for the question
what's the difference between releases named "JDK 7 Update 60", "1.7.0_60", and
"JDK 7u60"?
The new model resolves this one with below naming standards.
$FEATURE.$INTERIM.$UPDATE.$PATCH
$FEATURE — This counter will be incremented at every feature release regardless of release
content. The feature counter for the current release is 10. (Formerly $MAJOR.).
It will be incremented every six months: The March 2018 release is JDK 10, the September
2018 release is JDK 11, and so forth.
$INTERIM — The interim-release counter, incremented for non-feature releases that
contain compatible bug fixes and enhancements but no incompatible changes, no feature
removals, and no changes to standard APIs. (Formerly $MINOR.)
Since the six-month model does not include interim releases, this will always be zero. It is
reserved for flexibility, so that a future revision may include something like JDK $N.1 and
JDK $N.2 etc. For example, JDK 1.4.1 and 1.4.2 releases were interim releases, and
according to the new versioning system, they would have been numbered 4.1 and 4.2.
$UPDATE — The update-release counter, incremented for compatible update releases that
fix security issues, regressions, and bugs in newer features. (Formerly $SECURITY, but with
a non-trivial incrementation rule.)
The update-release counter, incremented for compatible update releases.
The April 2018 release will be JDK 10.0.1 with the update counter 1, the July release will
be JDK 10.0.2 with the update counter 2, and so forth.
$PATCH — The emergency patch-release counter, incremented only when it's necessary to
produce an emergency release to fix a critical issue. (Using an additional element for this
purpose minimizes disruption to both developers and users of in-flight update releases.)
The emergency patch-release counter, incremented only when it's necessary to produce an
emergency release to fix a critical issue
Introduce nests, an access-control context that aligns with the existing notion
of nested types in the Java programming language. Nests allow classes that are
logically part of the same code entity, but which are compiled to distinct
class files, to access each other's private members without the need for
compilers to insert accessibility-broadening bridge methods.
This feature enables java command to directly run the program and internally it
will complete the compilation. This feature supports only run the single file
java program.
In this below example, HelloWorld.java contains the single file java program
and in java 8 it didn't work, where as after the path set to java 12 it is
working fine. The feature is added in java 11.
Additions in java.lang.String
Returns true if the string is empty or contains only white space codepoints,
otherwise false.
26. str3:isBlank()=true
27. str3:isEmpty()=false
Below program illustrates how lines() is working and splits into lines using \r
or \r\n delimiters
1. import java.util.Set;
2. import java.util.stream.Collectors;
3. import java.util.stream.Stream;
4.
5. public class StringIsBlankDemo {
6. public static void main(String args[])
7. {
8. String str1=new String("Java 11 Features\r\nJava 12 Features\rJava 13 Features");
9. Stream stream = str1.lines();
10. Set<String> set=(Set)stream.collect(Collectors.toSet());
11. set.forEach(System.out::println);
12.
13. }
14. }
15.
16. Output
17.
18. Java 13 Features
19. Java 11 Features
20. Java 12 Features
String strip()
String stripLeading():
String stripTrailing():
You probably look at strip() and ask, “How is this different to the existing
trim() method?” The answer is that how whitespace is defined differs between
the two.
1. class StringRepeatDemo {
2. public static void main(String args[])
3. {
4. String str = "String ";
5. System.out.println(str.repeat(10));
6. }
7. }
8.
9. Output
10.
11. String String String String String String String String String String
This feature allows var to be used when declaring the formal parameters of
implicitly typed lambda expressions.
In below example, the lambda expression formal parameters do not have types as
it is optional. This feature allows us to mention var along with the data type
as usual.
if we mention the type as var, must add param type to all formal parameter
1.
2. @FunctionalInterface
3. interface Addition {
4. public int addTwoNumbers(int num1, int mum2);
5. }
6.
7. @FunctionalInterface
8. interface BigNumbers {
9. public int findBigNumber(int num1, int mum2);
10. }
11.
12. public class LambdaAdditionsDemo {
13. public static void main(String[] args) {
14.
15. Addition addition = (num1, num2) -> num1 + num2;
16. BigNumbers bigNumbers = (num1, num2) -> {
17. if (num1 > num2)
18. return num1;
19. else
20. return num2;
21. };
22.
23. System.out.println(addition.addTwoNumbers(10, 5));
24.
25. System.out.println(bigNumbers.findBigNumber(10, 5));
26. System.out.println(bigNumbers.findBigNumber(1, 2));
27. }
28. }
29.
30. Output
31.
32. 15
33. 10
34. 2
In nested classes, Inner class can access the outer class private members. Let's see the below example.
Today private access between nestmates is not permitted by the JVM access rules. To provide the
permitted access a Java source code compiler has to introduce a level of indirection. For example, an
invocation of a private member is compiled into an invocation of a compiler-generated package-
private, bridging method in the target class, which in turn invokes the intended private method. These
access bridges are generated only as needed to satisfy the member accesses requested within the
nest.
1. class Outer {
2. private int pri_var = 10;
3.
4. private void privateMethod() {
5. System.out.println("private method");
6. }
7.
8. class Inner {
9. void innerMethod() {
10. System.out.println(pri_var);
11. privateMethod();
12. }
13. }
14. }
15.
16. public class NestDemo {
17.
18. public static void main(String[] args) {
19. // TODO Auto-generated method stub
20. Outer outer = new Outer();
21. Outer.Inner inner = outer.new Inner();
22. inner.innerMethod();
23. }
24.
25. }
26.
27. Output
28.
29. 10
30. private method
1. Using Java 8
2.
3. F:\Java_Office\sample_prgs\java11\nest>set path=C:\Program Files\Java\jdk1.8.0_66\bin
4.
5. F:\Java_Office\sample_prgs\java11\nest>javac NestDemo.java
6.
7. F:\Java_Office\sample_prgs\java11\nest>javap NestDemo.class
8. Compiled from "NestDemo.java"
9. public class NestDemo {
10. public NestDemo();
11. public static void main(java.lang.String[]);
12. }
13.
14. F:\Java_Office\sample_prgs\java11\nest>javap Outer.class
15. Compiled from "NestDemo.java"
16. class Outer {
17. Outer();
18. static int access$000(Outer);
19. static void access$100(Outer);
20. }
21.
22. F:\Java_Office\sample_prgs\java11\nest>javap Outer$Inner.class
23. Compiled from "NestDemo.java"
24. class Outer$Inner {
25. final Outer this$0;
26. Outer$Inner(Outer);
27. void innerMethod();
28. }
29. Using Java 12
30.
31. F:\Java_Office\sample_prgs\java11\nest>set path=C:\Program Files\Java\jdk-12.0.2\bin
32.
33. F:\Java_Office\sample_prgs\java11\nest>javac NestDemo.java\
34. error: invalid flag: NestDemo.java\
35. Usage: javac <options> <source files>
36. use --help for a list of possible options
37.
38. F:\Java_Office\sample_prgs\java11\nest>javac NestDemo.java
39.
40. F:\Java_Office\sample_prgs\java11\nest>javap NestDemo.class
41. Compiled from "NestDemo.java"
42. public class NestDemo {
43. public NestDemo();
44. public static void main(java.lang.String[]);
45. }
46.
47. F:\Java_Office\sample_prgs\java11\nest>javap Outer.class
48. Compiled from "NestDemo.java"
49. class Outer {
50. Outer();
51. }
52.
53. F:\Java_Office\sample_prgs\java11\nest>javap Outer$Inner.class
54. Compiled from "NestDemo.java"
55. class Outer$Inner {
56. final Outer this$0;
57. Outer$Inner(Outer);
58. void innerMethod();
59. }
Just as the linkage of an invokedynamic call site involves an upcall from the JVM to Java-based linkage
logic, we can apply this same trick to the resolution of a constant-pool entry.
A CONSTANT_Dynamic constant-pool entry encodes the bootstrap method to perform the resolution
(a MethodHandle), the type of the constant (a Class), and any static bootstrap arguments (an
arbitrary sequence of constants, barring cycles in the constant pool between dynamic constants.)
We add a new constant-pool form, CONSTANT_Dynamic (new constant tag 17), which has two
components following its tag byte: the index of a bootstrap method, in the same format as the index
found in a CONSTANT_InvokeDynamic, and a CONSTANT_NameAndType, which encodes the expected type.
Improve the existing string and array intrinsics, and implement new intrinsics for
the java.lang.Math sin, cos and log functions, on AArch64 processors. Intrinsics are used to leverage
CPU architecture-specific assembly code which is executed instead of generic Java code for a given
method to improve performance. While most of the intrinsics are already implemented in AArch64 port,
optimized intrinsics for the following java.lang.Math methods are still missing:
Develop a GC that handles memory allocation but does not implement any actual memory reclamation
mechanism. Once the available Java heap is exhausted, the JVM will shut down.
java.net.http.HttpClient API standardaized in Java 11 from its incubating version Java 9. The API provides non-blocking
request and response semantics through CompletableFutures, which can be chained to trigger
dependent actions. Back-pressure and flow-control of request and response bodies is provided for via
the Platform's reactive-streams support in thejava.util.concurrent.Flow API.
The implementation is now completely asynchronous (the previous HTTP/1.1 implementation was
blocking). Use of the RX Flow concept has been pushed down into the implementation, which
eliminated many of the original custom concepts needed to support HTTP/2. The flow of data can now
be more easily traced, from the user-level request publishers and response subscribers all the way
down to the underlying socket. This significantly reduces the number of concepts and complexity in the
code, and maximizes the possibility of reuse between HTTP/1.1 and HTTP/2.
1. import java.net.URI;
2. import java.net.http.HttpClient;
3. import java.net.http.HttpClient.Redirect;
4. import java.net.http.HttpClient.Version;
5. import java.net.http.HttpRequest;
6. import java.net.http.HttpResponse;
7. import java.net.http.HttpResponse.BodyHandlers;
8. import java.time.Duration;
9. /* Synchronous HttpClient example */
10.
11. public class SyncHttpClientDemo {
12. public static void main(String args[])
13. {
14. try
15. {
16. HttpClient client = HttpClient.newBuilder()
17. .version(Version.HTTP_1_1)
18. .followRedirects(Redirect.NORMAL)
19. .connectTimeout(Duration.ofSeconds(20))
20.
21. .build();
22.
23. HttpRequest request1 = HttpRequest.newBuilder()
24. .uri(URI.create("http://www.example.com/"))
25. .GET()//used by default if we don't specify
26. .build();
27. HttpResponse<String> response1 = client.send(request1, BodyHandlers.ofString());
28. System.out.println(response1.statusCode());
29. System.out.println(response1.body());
30.
31.
32. HttpRequest request2 = HttpRequest.newBuilder()
33. .uri(URI.create("http://www.google.co.in/"))
34. .GET()//used by default if we don't specify
35. .build();
36. HttpResponse<String> response2 = client.send(request2, BodyHandlers.ofString()
);
37. System.out.println(response2.statusCode());
38. System.out.println(response2.body());
39.
40.
41. }
42. catch(Exception e)
43. {
44. e.printStackTrace();
45. }
46. }
47. }
48.
49. Output
50.
51. Output from the HTML files
1.
2. import java.net.URI;
3. import java.net.http.HttpClient;
4. import java.net.http.HttpRequest;
5. import java.net.http.HttpResponse;
6. import java.util.concurrent.CompletableFuture;
7. import java.util.concurrent.Executor;
8.
9. /* Asynchronous HttpClient example */
10. public class AsyncHttpClientDemo {
11.
12. public static void main(String[] args) {
13. //building request
14. HttpRequest request1 = HttpRequest.newBuilder()
15. .uri(URI.create("http://www.example.com/"))
16. .GET()//used by default if we don't specify
17. .build();
18.
19.
20. HttpRequest request2 = HttpRequest.newBuilder()
21. .uri(URI.create("http://www.google.co.in/"))
22. .GET()//used by default if we don't specify
23. .build();
24.
25.
26. //creating response body handler
27. HttpResponse.BodyHandler<String> bodyHandler = HttpResponse.BodyHandlers.ofString();
28.
29. //sending request and receiving response via HttpClient
30. HttpClient client = HttpClient.newHttpClient();
31.
32. System.out.println("Starting to access ... www.example.com");
33.
34. CompletableFuture<HttpResponse<String>> future1 = client.sendAsync(request1, bodyHandler);
35. future1.thenApply(HttpResponse::body)
36. .thenAccept(System.out::println);
37.
38.
39. System.out.println("Completed access ... www.example.com");
40.
41. System.out.println("Starting to access ... www.google.co.in");
42.
43. CompletableFuture<HttpResponse<String>> future2 = client.sendAsync(request2, bodyHandler);
44. future2.thenApply(HttpResponse::body)
45. .thenAccept(System.out::println);
46.
47.
48. System.out.println("Completed ... www.google.co.in");
49.
50. }
51.
52. class ThreadPerTaskExecutor implements Executor {
53. public void execute(Runnable r) {
54. new Thread(r).start();
55. }
56. }
57. }
58. Output
59.
60. Output from the HTML files
The Nashorn JavaScript engine was first incorporated into JDK 8 via JEP 174 as a replacement for the
Rhino scripting engine. When it was released, it was a complete implementation of the ECMAScript-262
5.1 standard.
With the rapid pace at which ECMAScript language constructs, along with APIs, are adapted and
modified, we have found Nashorn challenging to maintain.
Remove the Java EE and CORBA modules from the Java SE Platform and the JDK. These modules
were deprecated in Java SE 9 with the declared intent to remove them in a future release.
Java SE 6 included a full Web Services stack for the convenience of Java developers. The stack
consisted of four technologies that were originally developedfor the Java EE Platform: JAX-WS (Java
API for XML-Based Web Services), JAXB (Java Architecture for XML Binding), JAF (the JavaBeans
Activation Framework), and Common Annotations. At the time of inclusion, the versions in Java SE
were identical to the versions in Java EE, except for Java SE dropping a package in Common
Annotations that concerned the Java EE security model. However, over time, the versions in Java EE
evolved, which led to difficulties for the versions in Java SE:
1. Removal of thread functions: stop(Throwable obj) and destroy() objects have been
removed from the JDK 11 because they only
throw UnSupportedOperation and NoSuchMethodError respectively. Other than that, they
were of no use.
Provide a KeyGenerator implementation that creates keys suitable for ChaCha20 and
ChaCha20-Poly1305 algorithms.
The ChaCha20 and ChaCha20-Poly1305 algorithms will implement the javax.crypto.CipherSpi API
within the SunJCE provider. Ciphers will be instantiated in the same way as other ciphers, using
the Cipher.getInstance() method. For both ciphers, two acceptable transforms are allowed. The
single-name transform is the preferred approach, "ChaCha20" for ChaCha20 as a simple stream cipher
with no authentication, and "ChaCha20-Poly1305" for ChaCha20 as an AEAD cipher using Poly1305 as
the authenticator. "ChaCha20/None/NoPadding" and "ChaCha20-Poly1305/None/NoPadding" are also
acceptable transform strings, though no other mode or padding values
besides "None" and "NoPadding" will be accepted. Use of other mode or padding values will cause an
exception to be thrown.
Flight Recorder records events originating from applications, the JVM and the OS. Events are stored in
a single file that can be attached to bug reports and examined by support engineers, allowing after-
the-fact analysis of issues in the period leading up to a problem. Tools can use an API to extract
information from recording files.
JFR is profiling tool used to gather diagnostics and profiling data from a running Java
application. It’s performance overhead is negligible and that’s usually below 1%. For short
running apps this overhead might be above that, because JFR requires some warm-up time on the
start.
Diagnosing faulty apps with JFR might shorten resolution times significantly. An anomaly can be
seem from its first emergence, as it unfolds and finally until that point when it causes the
application die. Of course, not all of the issues are that severe. JFR collects data about the
running threads, GC cycles, locks, sockets, memory usage and about a lot more.
JMC is a client tool used to open those production time performance and diagnostic
recordings JFR produced. JMC also delivers other features, such as a JMX console and a heap
dump analyzer. Oracle JDK releases from 7 to 10 contain JMC, but it has been separated and it’s
now available as a separate download.
JMC has was recently open sourced as well and that means that now the whole toolset
(JFR + JMC) are available to anyone using OpenJDK 11. At the time of writing, the first open
source JMC version 7 hasn’t reached GA yet, but early access builds are provided.
Page 645 of 660
Java Book - Chidambaram.S
Provide a low-overhead way of sampling Java heap allocations, accessible via JVMTI.
Provide a way to get information about Java object heap allocations from the JVM that:
Is low-overhead enough to be enabled by default continuously,
Is accessible via a well-defined, programmatic interface,
Can sample all allocations (i.e., is not limited to allocations that are in one particular heap
region or that were allocated in one particular way),
Can be defined in an implementation-independent way (i.e., without relying on any
particular GC algorithm or VM implementation), and
Can give information about both live and dead Java objects.
Implement version 1.3 of the Transport Layer Security (TLS) Protocol RFC 8446. TLS 1.3 is a new TLS
version which supersedes and obsoletes previous versions of TLS including version 1.2 (RFC 5246). It
also obsoletes or changes other TLS features such as the OCSP stapling extensions (RFC 6066, RFC
6961), and the session hash and extended master secret extension (RFC 7627).
The Java Secure Socket Extension (JSSE) in the JDK provides a framework and a Java implementation
of the SSL, TLS, and DTLS protocols. Currently, the JSSE API and JDK implementation supports SSL
3.0, TLS 1.0, TLS 1.1, TLS 1.2, DTLS 1.0 and DTLS 1.2.
A core design principle/choice in ZGC is the use of load barriers in combination with colored object
pointers (i.e., colored oops). This is what enables ZGC to do concurrent operations, such as object
relocation, while Java application threads are running. From a Java thread's perspective, the act of
loading a reference field in a Java object is subject to a load barrier. In addition to an object address, a
colored object pointer contains information used by the load barrier to determine if some action needs
to be taken before allowing a Java thread to use the pointer. For example, the object might have been
relocated, in which case the load barrier will detect the situation and take appropriate action.
Internal changes
Modern machines have more memory and more processors than ever before. Service
Level Agreement (SLA) applications guarantee response times of 10-500ms. In
order to meet the lower end of that goal we need garbage collection algorithms
which are efficient enough to allow programs to run in the available memory,
but also optimized to never interrupt the running program for more than a
handful of milliseconds. Shenandoah is an open-source low-pause time collector
for OpenJDK designed to move us closer to those goals.
Shenandoah trades concurrent cpu cycles and space for pause time improvements.
We've added an indirection pointer to every Java object which enables the GC
threads to compact the heap while the Java threads are running. Marking and
compacting are performed concurrently so we only need to pause the Java threads
long enough to scan the thread stacks to find and update the roots of the
object graph.
The microbenchmark suite will be co-located with the JDK source code in a
single directory and, when built, will produce a single JAR file. Co-location
will simplify adding and locating benchmarks during development. When running
benchmarks, JMH provides powerful filtering capabilities that allow the user to
run only the benchmarks that are currently of interest. The exact location
remains to be determined.
Two 64-bit ARM ports exist in the JDK. The main sources for these are in
the src/hotspot/cpu/arm and open/src/hotspot/cpu/aarch64 directories. Although both
ports produce aarch64 implementations, for the sake of this JEP we shall refer
to the former, which was contributed by Oracle, as arm64, and the latter
as aarch64.
Modify the JDK build to run java -Xshare:dump after linking the image.
(Additional command-line options may be included to fine-tune GC heap size,
etc., in order to obtain better memory layout for common cases.) Leave the
Users will benefit from the CDS feature automatically, since -Xshare:auto was
enabled by default for the server VM in JDK 11 (JDK-8197967). To disable CDS,
run with -Xshare:off.
Users with more advanced requirements (e.g., using custom class lists that
include application classes, different GC configurations, etc.) can still
create a custom CDS archive as before.
As the predictions get more accurate again, the optional part of a collection
are made smaller and smaller, until the mandatory part once again comprises all
of the collection set (i.e., G1 completely relies on its heuristics). If the
predictions becomes inaccurate again, then the next collections will consist of
both a mandatory and optional part again.
This will cause it to automatically return unused portions of the Java heap
back to the operating system. Optionally, under user control, a full GC can be
performed to maximize the amount of memory returned.
Development changes
Switch Expressions
Java 12 imporves the switch statement with the below features and released as a
preview feature.
Switch statement allows lambda expressons as the condition, and one or more
condition labels we can add.
No need to add break for every case. In previous releases it is must to prevent
the flow of control will fall through to subsequent cases. Also break now can
return the value too.
To enable preview features in eclipse (version used : Version: 2019-06 (4.12.0)), we must
enable following properties in project properties dialog. To get this dialog,
right click on the project name and select properties.
also you can notice that the compiler option selected as Java 12.
1. package java12Project;
2.
3. class SwitchDemo {
4. public static void main(String args[]) {
5. try {
6. int number = 5;
7. String result = switch (number) {
8. case 0, 1, 2, 3, 4, 5 -> "Number is less than or equal to 5";
9. case 6, 7, 8, 9, 10 -> "Number is greater than 5 and less than or equal to 10";
10. default -> {
11. if (number < 0)
12. break "Number is negative";
13. else
14. break "Number is positive and greater than 10";
15. }
16. };
17. System.out.println("result" + result);
18.
19. } catch (Exception e) {
20. e.printStackTrace();
21. }
22. }
23. }
24.
25. Output
26.
27. result=Number is less than or equal to 5
File.mismatch method
Finds and returns the position of the first mismatched byte in the content of
two files, or -1L if there is no mismatch. The position will be in the
inclusive range of 0L up to the size (in bytes) of the smaller file.
Two files are considered to match if they satisfy one of the following
conditions:
The two paths locate the same file, even if two equal paths locate a file does
not exist, or
The two files are the same size, and every byte in the first file is identical
to the corresponding byte in the second file.
Otherwise there is a mismatch between the two files and the value returned by
this method is:
The size of the smaller file (in bytes) when the files are different sizes and
every
Parameters:
Returns:
1. import java.io.File;
2. import java.nio.file.Files;
3.
4. public class FileMismatchDemo {
5.
6. public static void main(String[] args) {
7. // TODO Auto-generated method stub
8. try {
9. File file1 = new File("FileMismatchDemo.java");
10. File file2 = new File("FileMismatchDemo.java");
11. long result = Files.mismatch(file1.toPath(), file2.toPath());
12. System.out.println("result=" + result);
13.
14. } catch (Exception e) {
15. e.printStackTrace();
16. }
17.
18. }
19. }
20.
21. Output
22.
23. result=-1
1.
2. import java.text.NumberFormat;
3. import java.util.Locale;
4.
5. public class CompactNumberFormatDemo {
6.
7. public static void main(String[] args) {
8.
9. System.out.println("***** Default locale en US *****");
10.
11. NumberFormat numberFormat1 = NumberFormat.getCompactNumberInstance
();
12. // we can set the max fraction digits
13. // numberFormat1.setMaximumFractionDigits(1);
14. System.out.println(numberFormat1.format(2592356356534563D));
15. System.out.println(numberFormat1.format(259235));
16. System.out.println("***** en and CA Short format *****");
17. NumberFormat numberFormat2 = NumberFormat.getCompactNumberInstance
(new Locale("en", "CA"),
18. NumberFormat.Style.SHORT);
19. System.out.println(numberFormat2.format(2592356356534563D));
20. System.out.println(numberFormat2.format(259235));
21.
1. import java.util.List;
2. import java.util.stream.Collector;
3. import java.util.stream.Collectors;
4. import java.util.stream.Stream;
5.
This method adjusts indentation of the given string's lines based on int n.
Postive numbers adds the space in each line and negative numbers removes the
space in each line.
If n < 0 then up to n white space characters are removed from the beginning of
each line. Tab character will also be treated as single character.
transform()
This method allows the application of a function to this string. The function
should expect a single String argument and produce an R result.
1.
2. public class StringTransformDemo {
3.
4. public static void main(String[] args) {
5. // TODO Auto-generated method stub
6.
7. String str = "10,15,3";
8.
9. String newStr[] = str.transform(s -> {
10. return s.split(",");
11. });
12.
13. for (String s : newStr)
14. System.out.println(s);
15.
16. }
17.
18. }
19.
20. Output
21.
22. 10
23. 15