Java Tutorial (Multithreadig)
Java Tutorial (Multithreadig)
Java Tutorial or Core Java Tutorial or Java Programming Tutorial is a widely used robust
technology. Let's start learning of java from basic questions like what is java tutorial, core java,
where it is used, what type of applications are created in java and why use java.
What is Java
Java is a programming language and a platform.
Java is a high level, robust, secured and object-oriented programming language.
Platform:
Any hardware or software environment in which a program runs, is known as a platform.
Since Java has its own runtime environment (JRE) and API, it is called platform.
Java Example
Let's have a quick look at java programming example. A detailed description of hello
java example is given in next page.
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
Where it is used?
According to Sun, 3 billion devices run java. There are many devices where java is
currently used. Some of them are as follows:
Desktop Applications such as acrobat reader, media player, antivirus etc.
Web Applications such as irctc.co.in, java.com etc.
Enterprise Applications such as banking applications.
● Mobile
● Embedded System
● Smart Card
● Robotics
● Games.
2) Web Application
An application that runs on the server side and creates dynamic page, is called web
application. Currently, servlet, jsp, struts, jsf etc. technologies are used for creating web
applications in java.
3) Enterprise Application
An application that is distributed in nature, such as banking applications etc. It has the
advantage of high level security, load balancing and clustering. In java, EJB is used for creating
enterprise applications.
4) Mobile Application
An application that is created for mobile devices. Currently Android and Java ME are
used for creating mobile applications.
History of Java
Java history is interesting to know. The history of java starts from Green Team. Java
team members (also known as Green Team), initiated a revolutionary task to develop a
language for digital devices such as set-top boxes, televisions etc.
For the green team members, it was an advance concept at that time. But, it was suited for
internet programming. Later, Java technology as incorporated by Netscape.
Features of Java
There is given many features of java. They are also known as java buzzwords. The Java Features
given below are simple and easy to understand.
Simple
Object-Oriented
Platform independent
Secured
Robust
Architecture neutral
Portable
Dynamic
Interpreted
High Performance
Multithreaded
Distributed
Simple
According to Sun, Java language is simple because:
syntax is based on C++ (so easier for programmers to learn it after C++).
removed many confusing and/or rarely-used features e.g., explicit pointers, operator
overloading etc.
No need to remove unreferenced objects because there is Automatic Garbage Collection in
java.
Object-oriented
Object-oriented means we organize our software as a combination of different types of objects
that incorporates both data and behaviour.
Object-oriented programming(OOPs) is a methodology that simplify software development and
maintenance by providing some rules.
Basic concepts of OOPs are:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Platform Independent
A platform is the hardware or software environment in which a program runs. There are two
types of platforms software-based and hardware-based. Java provides software-based platform.
The Java platform differs from most other platforms in the sense that it's a software-based
platform that runs on top of other hardware-based platforms.It has two components:
Runtime Environment
API(Application Programming Interface)
Java code can be run on
multiple platforms e.g.Windows,Linux,Sun Solaris,Mac/OS etc. Java code is compiled by the
compiler and converted into bytecode.This bytecode is a platform independent code because it
can be run on multiple platforms i.e. Write Once and Run Anywhere(WORA).
Secured
Java is secured because:
No explicit pointer
Programs run inside virtual machine sandbox.
Classloader- adds security by separating the package for the classes of the local file system from
those that are imported from network sources.
Bytecode Verifier- checks the code fragments for illegal code that can violate access right to
objects.
Security Manager- determines what resources a class can access such as reading and writing to
the local disk.
These security are provided by java language. Some security can also be provided by application
developer through SSL,JAAS,cryptography etc.
Robust
Robust simply means strong. Java uses strong memory management. There are lack of pointers
that avoids security problem. There is automatic garbage collection in java. There is exception
handling and type checking mechanism in java. All these points makes java robust.
Architecture-neutral
There is no implementation dependent features e.g. size of primitive types is set.
Portable
We may carry the java bytecode to any platform.
High-performance
Java is faster than traditional interpretation since byte code is "close" to native code still
somewhat slower than a compiled language (e.g., C++)
Distributed
We can create distributed applications in java. RMI and EJB are used for creating distributed
applications. We may access files by calling the methods from any machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs
that deal with many tasks at once by defining multiple threads. The main advantage of multi-
threading is that it shares the same memory. Threads are important for multi-media, Web
applications etc.
To write the simple program, open notepad by start menu -> All Programs -> Accessories ->
notepad and write simple program as displayed below:
As displayed in the above diagram, write the simple program of java in notepad and saved it as
Simple.java. To compile and run this program, you need to open command prompt by start
menu -> All Programs -> Accessories -> command prompt.
To compile and run the above program, go to your current directory first; my current directory is
c:\new . Write here:
Q)Can you save a java source file by other name than the class name?
Yes, if the class is not public. It is explained in the figure given below:
For Example:
set path=C:\Program Files\Java\jdk1.6.0_23\bin
Let's see it in the figure given below:
2) How to set Permanent Path of JDK in Windows
For setting the permanent path of JDK, you need to follow these steps:
Go to MyComputer properties -> advanced tab -> environment variables -> new tab of user
variable -> write path in variable name -> write path of bin folder in variable value -> ok -> ok ->
ok
For Example:
1)Go to MyComputer properties
2)click on advanced tab
3)click on environment variables
4)click on new tab of user variables
5)write path in variable name
6)Copy the path of bin folder
7)paste path of bin folder in variable value
8)click on ok button
9)click on ok button
Now your permanent path is set.You can now execute any program of java from any drive.
export PATH=$PATH:/home/jdk1.6.01/bin/
Here, we have installed the JDK in the home directory under Root (/home).
JRE
JRE is an acronym for Java Runtime Environment.It is used to provide runtime environment.It is
the implementation of JVM.It physically exists.It contains set of libraries + other files that JVM
uses at runtime.
Implementation of JVMs are also actively released by other companies besides Sun Micro
Systems.
JDK
JDK is an acronym for Java Development Kit.It physically exists.It contains JRE +
development tools.
What is JVM?
It is:
A specification where working of Java Virtual Machine is specified. But implementation
provider is independent to choose the algorithm. Its implementation has been provided by Sun
and other companies.
An implementation Its implementation is known as JRE (Java Runtime Environment).
Runtime Instance Whenever you write java command on the command prompt to run the java
class, and instance of JVM is created.
What it does?
The JVM performs following operation:
Loads code
Verifies code
Executes code
Provides runtime environment
JVM provides definitions for the:
Memory area
Class file format
Register set
Garbage-collected heap
Fatal error reporting etc.
2) Class(Method) Area:
Class(Method) Area stores per-class structures such as the runtime constant pool, field and
method data, the code for methods.
3) Heap:
It is the runtime data area in which objects are allocated.
4) Stack:
Java Stack stores frames.It holds local variables and partial results, and plays a part in method
invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its method
invocation completes.
7) Execution Engine:
It contains:
1) A virtual processor
2) Interpreter:Read bytecode stream then execute the instructions.
3) Just-In-Time(JIT) compiler:It is used to improve the performance.JIT compiles parts of the
byte code that have similar functionality at the same time, and hence reduces the amount of
time needed for compilation.Here the term ?compiler? refers to a translator from the
instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.
In this page, we will learn about the variable and java data types. Variable is a name of memory
location. There are three types of variables: local, instance and static. There are two types of
datatypes in java, primitive and non-primitive.
Variable
Variable is name of reserved area allocated in memory.
int data=50;//Here data is variable
Types of Variable
There are three types of variables in java
local variable
instance variable
static variable
Local Variable
A variable that is declared inside the method is called local variable.
Instance Variable
A variable that is declared inside the class but outside the method is called instance variable . It
is not declared as static.
Static variable
A variable that is declared as static is called static variable. It cannot be local.
Unicode System
Unicode is a universal international standard character encoding that is capable of representing
most of the world's written languages.
Operators in java
Operator in java is a symbol that is used to perform operations. There are many types of
operators in java such as unary operator, arithmetic operator, relational operator, shift operator,
bitwise operator, ternary operator and assignment operator.
Operators Precedence
postfix expr++ expr--
unary ++expr --expr +expr -expr ~ !
multiplicative * / %
additive + -
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ? :
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.
Class
Collection of objects is called class. It is a logical entity.
Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example: to
convense the customer differently, to draw something e.g. shape or rectangle etc.
In java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example:
phone call, we don't know the internal processing.
In java, we use abstract class and interface to achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation.
For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all
the data members are private here.
An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table,
car etc. It can be physical or logical (tengible and intengible). The example of integible object is
banking system.
An object has three characteristics:
state: represents data (value) of an object.
behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.
identity: Object identity is typically implemented via a unique ID. The value of the ID is not
visible to the external user. But,it is used internally by the JVM to identify each object uniquely.
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is
used to write, so writing is its behavior.
Object is an instance of a class. Class is a template or blueprint from which objects are created.
So object is the instance(result) of a class.
Class in Java
A class is a group of objects that has common properties. It is a template or blueprint from
which objects are created.
A class in java can contain:
data member
method
constructor
block
class and interface
Method in Java
In java, a method is like function i.e. used to expose behaviour of an object.
Advantage of Method
Code Reusability
Code Optimization
new keyword
The new keyword is used to allocate memory at runtime.
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
111 Karan
222 Aryan
As you see in the above figure, object gets the memory in Heap area and reference variable
refers to the object allocated in the Heap memory area. Here, s1 and s2 both are reference
variables that refer to the objects allocated in memory.
void calculateArea(){System.out.println(length*width);}
r1.calculateArea();
r2.calculateArea();
}
}
Output:55
45
Annonymous object
Annonymous simply means nameless.An object that have no reference is known as
annonymous object.
If you have to use an object only once, annonymous object is a good approach.
class Calculation{
void calculateArea(){System.out.println(length*width);}
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
Output:55
45
In java, Methood Overloading is not possible by changing the return type of the
method.
}
}
Output:30
40
2)Example of Method Overloading by changing data type of argument
In this example, we have created two overloaded methods that differs in data type. The first sum
method receives two integer arguments and second sum method receives two double arguments.
class Calculation2{
void sum(int a,int b){System.out.println(a+b);}
void sum(double a,double b){System.out.println(a+b);}
}
}
Output:21.0
40
Que) Why Method Overloaing is not possible by changing the return type of
method?
In java, method overloading is not possible by changing the return type of the method because
there may occur ambiguity. Let's see how ambiguity may occur:
because there was problem:
class Calculation3{
int sum(int a,int b){System.out.println(a+b);}
double sum(int a,int b){System.out.println(a+b);}
}
}
int result=obj.sum(20,20); //Here how can java determine which sum() method should be called
}
}
Output:40
60
Output:
Bike is created
Output:
0 null
0 null
Explanation:In the above class,you are not creating any constructor so compiler provides you a
default constructor.Here 0 and null values are provided by default constructor.
Output:
111 Karan
222 Aryan
Output:
111 Karan 0
222 Aryan 25
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}
Output:
111 Karan
111 Karan
Output:
111 Karan
111 Karan
class Student8{
int rollno;
String name;
static String college ="ITS";
s1.display();
s2.display();
}
}
Counter(){
count++;
System.out.println(count);
}
Output:1
1
1
Counter2(){
count++;
System.out.println(count);
}
}
}
Output:1
2
3
class Student9{
int rollno;
String name;
static String college = "ITS";
s1.display();
s2.display();
s3.display();
}
}
class Calculate{
static int cube(int x){
return x*x*x;
}
Output:125
The static method can not use non static data member or call non-static method directly.
this and super cannot be used in static context.
class A{
int a=40;//non static
1) The this keyword can be used to refer current class instance variable.
If there is ambiguity between the instance variable and parameter, this keyword resolves the
problem of ambiguity.
Output:0 null
0 null
In the above example, parameter (formal arguments) and instance variables are same that is
why we are using this keyword to distinguish between local variable and instance variable.
Output111 Karan
222 Aryan
If local variables(formal arguments) and instance variables are different, there is no need to use
this keyword like in the following program:
Output:111 Karan
222 Aryan
2) this() can be used to invoked current class constructor.
The this() constructor call can be used to invoke the current class constructor (constructor
chaining). This approach is better if you have many constructors in the class and want to reuse
that constructor.
//Program of this() constructor call (constructor chaining)
class Student13{
int id;
String name;
Student13(){System.out.println("default constructor is invoked");}
Output:
default constructor is invoked
default constructor is invoked
111 Karan
222 Aryan
class S{
void m(){
System.out.println("method is invoked");
}
void n(){
this.m();//no need because compiler does it for you.
}
void p(){
n();//complier will add this to invoke n() method as this.n()
}
public static void main(String args[]){
S s1 = new S();
s1.p();
}
}
Output:method is invoked
Output:method is invoked
class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
Output:10
Example of this keyword that you return as a statement from the method
class A{
A getA(){
return this;
}
void msg(){System.out.println("Hello java");}
}
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}
Output:Hello java
obj.m();
}
}
Output:A5@22b3ea59
A5@22b3ea59
Inheritance in Java
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object.
The idea behind inheritance in java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of parent
class, and you can add new methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-child relationship.
As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
Relationship between two classes is Programmer IS-A Employee.It means that Programmer is
a type of Employee.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Aggregation in Java
If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A
relationship.
Consider a situation, Employee object contains many informations such as id, name, emailId etc.
It contains one more object named address, which contains its own informations such as city,
state, country, zipcode etc. as given below.
class Employee{
int id;
String name;
Address address;//Address is a class
...
}
In such case, Employee has an entity reference address, so relationship is Employee HAS-A
address.
In this example, we have created the reference of Operation class in the Circle class.
class Operation{
int square(int n){
return n*n;
}
}
class Circle{
Operation op;//aggregation
double pi=3.14;
Output:78.5
Address.java
public class Address {
String city,state,country;
Emp.java
public class Emp {
int id;
String name;
Address address;
void display(){
System.out.println(id+" "+name);
System.out.println(address.city+" "+address.state+" "+address.country);
}
}
}
Output:111 varun
gzb UP india
112 arun
gno UP india
Output:Vehicle is running
Problem is that I have to provide a specific implementation of run() method in subclass that is
why we use method overriding.
class Bank{
int getRateOfInterest(){return 0;}
}
class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
Note: If you are beginner to java, skip this topic and return to it after OOPs
concepts.
class B1 extends A{
B1 get(){return this;}
void message(){System.out.println("welcome to covariant return type");}
Output:100
In the above example Vehicle and Bike both class have a common property speed. Instance
variable of current class is refered by instance bydefault, but I have to refer parent class instance
variable that is why we use super keyword to distinguish between parent class instance variable
and current class instance variable.
class Vehicle{
int speed=50;
}
void display(){
System.out.println(super.speed);//will print speed of Vehicle now
}
public static void main(String args[]){
Bike4 b=new Bike4();
b.display();
}
}
Output:50
}
}
Output:Vehicle is created
Bike is created
As we know well that default constructor is provided by compiler automatically but it also adds
super() for the first statement.If you are creating your own constructor and you don't have either
this() or super() as the first statement, compiler will provide super() as the first statement of the
constructor.
Output:Vehicle is created
10
void display(){
message();//will invoke current class message() method
super.message();//will invoke parent class message() method
}
Output:welcome to java
welcome
In the above example Student and Person both classes have message() method if we call
message() method from Student class, it will call the message() method of Student class not of
Person class because priority is given to local.
In case there is no method in subclass as parent, there is no need to use super. In the example
given below message() method is invoked from Student class but Student class does not have
message() method, so you can directly call message() method.
void display(){
message();//will invoke parent class message() method
}
Output:welcome
Instance Initializer block is used to initialize the instance data member. It run each time when
object of the class is created.
The initialization of the instance variable can be directly but there can be performed extra
operations while initializing the instance variable in the instance initializer block.
Que) What is the use of instance initializer block while we can directly assign a
value in instance data member? For example:
class Bike{
int speed=100;
}
Bike7(){System.out.println("speed is "+speed);}
{speed=100;}
public static void main(String args[]){
Bike7 b1=new Bike7();
Bike7 b2=new Bike7();
}
}
Output:speed is 100
speed is 100
There are three places in java where you can perform operations:
method
constructor
block
Bike8(){System.out.println("constructor is invoked");}
class B3 extends A{
B3(){
super();
System.out.println("child class constructor invoked");
}
B3(int a){
super();
System.out.println("child class constructor invoked "+a);
}
Output:running...
Bike10(){
speedlimit=70;
System.out.println(speedlimit);
}
Output:70
Upcasting
When reference variable of Parent class refers to the object of Child class, it is known as
upcasting. For example:
class A{}
class B extends A{}
A a=new B();//upcasting
class Test3{
public static void main(String args[]){
Bank b1=new SBI();
Bank b2=new ICICI();
Bank b3=new AXIS();
System.out.println("SBI Rate of Interest: "+b1.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+b2.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+b3.getRateOfInterest());
}
}
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
Output:90
Java Runtime Polymorphism with Multilevel Inheritance
Let's see the simple example of Runtime Polymorphism with multilevel inheritance.
class Animal{
void eat(){System.out.println("eating");}
}
a1.eat();
a2.eat();
a3.eat();
}
}
Output: eating
eating fruits
drinking Milk
Understanding Type
Let's understand the type of instance.
Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.
Output:dog is eating...
In the above example object type cannot be determined by the compiler, because the instance
of Dog is also an instance of Animal.So compiler doesn't know its type, only its base type.
Java instanceof
The java instanceof operator is used to test whether the object is an instance of the specified
type (class or subclass or interface).
The instanceof in java is also known as type comparison operator because it compares the
instance with type. It returns either true or false. If we apply the instanceof operator with any
variable that has null value, it returns false.
Simple example of java instanceof
Let's see the simple example of instance operator where it tests the current class.
1. class Simple1{
2. public static void main(String args[]){
3. Simple1 s=new Simple1();
4. System.out.println(s instanceof Simple);//true
5. }
6. }
Output:true
An object of subclass type is also a type of parent class. For example, if Dog extends Animal
then object of Dog can be referred by either Dog or Animal class.
1. class Animal{}
2. class Dog1 extends Animal{//Dog inherits Animal
3.
4. public static void main(String args[]){
5. Dog1 d=new Dog1();
6. System.out.println(d instanceof Animal);//true
7. }
8. }
Output:true
1. class Dog2{
2. public static void main(String args[]){
3. Dog2 d=null;
4. System.out.println(d instanceof Dog2);//false
5. }
6. }
Output:false
Downcasting with java instanceof operator
When Subclass type refers to the object of Parent class, it is known as downcasting. If we
perform it directly, compiler gives Compilation error. If you perform it by typecasting,
ClassCastException is thrown at runtime. But if we use instanceof operator, downcasting is
possible.
1. class Animal { }
2.
3. class Dog3 extends Animal {
4. static void method(Animal a) {
5. if(a instanceof Dog3){
6. Dog3 d=(Dog3)a;//downcasting
7. System.out.println("ok downcasting performed");
8. }
9. }
10.
11. public static void main (String [] args) {
12. Animal a=new Dog3();
13. Dog3.method(a);
14. }
15.
16. }
1. class Animal { }
2. class Dog4 extends Animal {
3. static void method(Animal a) {
4. Dog4 d=(Dog4)a;//downcasting
5. System.out.println("ok downcasting performed");
6. }
7. public static void main (String [] args) {
8. Animal a=new Dog4();
9. Dog4.method(a);
10. }
11. }
1. interface Printable{}
2. class A implements Printable{
3. public void a(){System.out.println("a method");}
4. }
5. class B implements Printable{
6. public void b(){System.out.println("b method");}
7. }
8.
9. class Call{
10. void invoke(Printable p){//upcasting
11. if(p instanceof A){
12. A a=(A)p;//Downcasting
13. a.a();
14. }
15. if(p instanceof B){
16. B b=(B)p;//Downcasting
17. b.b();
18. }
19.
20. }
21. }//end of Call class
22.
23. class Test4{
24. public static void main(String args[]){
25. Printable p=new B();
26. Call c=new Call();
27. c.invoke(p);
28. }
29. }
Output: b method
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
Another way, it shows only important things to the user and hides the internal details for
example sending sms, you just type the text and send the message. You don't know the internal
processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
running safely..
drawing circle
bike is created
running safely..
gear changed
Rule: If there is any abstract method in a class, that class must be abstract.
1. class Bike12{
2. abstract void run();
3. }
Note: If you are beginner to java, learn interface first and skip this example.
1. interface A{
2. void a();
3. void b();
4. void c();
5. void d();
6. }
7.
8. abstract class B implements A{
9. public void c(){System.out.println("I am C");}
10. }
11.
12. class M extends B{
13. public void a(){System.out.println("I am a");}
14. public void b(){System.out.println("I am b");}
15. public void d(){System.out.println("I am d");}
16. }
17.
18. class Test5{
19. public static void main(String args[]){
20. A a=new M();
21. a.a();
22. a.b();
23. a.c();
24. a.d();
25. }}
Output:I am a
I am b
I am c
I am d
Interface in Java
An interface in java is a blueprint of a class. It has static constants and abstract methods only.
The interface in java is a mechanism to achieve fully abstraction. There can be only abstract
methods in the java interface not method body. It is used to achieve fully abstraction and
multiple inheritance in Java.
Java Interface also represents IS-A relationship.
It cannot be instantiated just like abstract class.
The java compiler adds public and abstract keywords before the interface
method and public, static and final keywords before data members.
In other words, Interface fields are public, static and final bydefault, and methods are public and
abstract.
Understanding relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends another
interface but a class implements an interface.
Simple example of Java interface
In this example, Printable interface have only one method, its implementation is provided in the
A class.
1. interface printable{
2. void print();
3. }
4.
5. class A6 implements printable{
6. public void print(){System.out.println("Hello");}
7.
8. public static void main(String args[]){
9. A6 obj = new A6();
10. obj.print();
11. }
12. }
Output:Hello
Output:Hello
Welcome
Hello
As you can see in the above example, Printable and Showable interface have same methods but
its implementation is provided by class TestTnterface1, so there is no ambiguity.
Interface inheritance
A class implements interface but one interface extends another interface .
1. interface Printable{
2. void print();
3. }
4. interface Showable extends Printable{
5. void show();
6. }
7. class Testinterface2 implements Showable{
8.
9. public void print(){System.out.println("Hello");}
10. public void show(){System.out.println("Welcome");}
11.
12. public static void main(String args[]){
13. Testinterface2 obj = new Testinterface2();
14. obj.print();
15. obj.show();
16. }
17. }
Hello
Welcome
1. interface printable{
2. void print();
3. interface MessagePrintable{
4. void msg();
5. }
6. }
Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
For example
1. javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
The import keyword is used to make the classes and interface of another package accessible to
the current package.
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2.
3. package mypack;
4. import pack.*;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();
9. obj.msg();
10. }
11. }
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2.
3. package mypack;
4. import pack.A;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();
9. obj.msg();
10. }
11. }
Output:Hello
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2.
3. package mypack;
4. class B{
5. public static void main(String args[]){
6. pack.A obj = new pack.A();//using fully qualified name
7. obj.msg();
8. }
9. }
Output:Hello
Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize the
package further.
Let's take an example, Sun Microsystem has definded a package named java that contains many
classes like System, String, Reader, Writer, Socket etc. These classes represent a particular group
e.g. Reader and Writer classes are for Input/Output operation, Socket and ServerSocket classes
are for networking etc and so on. So, Sun has subcategorized the java package into subpackages
such as lang, net, io etc. and put the Input/Output related classes in io package, Server and
ServerSocket classes in net packages and so on.
1. package com.java.core;
2. class Simple{
3. public static void main(String args[]){
4. System.out.println("Hello subpackage");
5. }
6. }
1. //save as Simple.java
2.
3. package mypack;
4. public class Simple{
5. public static void main(String args[]){
6. System.out.println("Welcome to package");
7. }
8. }
To Compile:
e:\sources> javac -d c:\classes Simple.java
To Run:
To run this program from e:\source directory, you need to set classpath of the directory where
the class file resides.
e:\sources> set classpath=c:\classes;.;
e:\sources> java mypack.Simple
Another way to run this program by -classpath switch of java:
The -classpath switch can be used with javac and java tool.
To run this program from e:\source directory, you can use -classpath switch of java that tells
where to look for class file. For example:
e:\sources> java -classpath c:\classes mypack.Simple
Output:Welcome to package
Rule: There can be only one public class in a java source file and it must be
saved by the public class name.
1. private
2. default
3. protected
4. public
There are many non-access modifiers such as static, abstract, synchronized, native, volatile,
transient etc. Here, we will learn access modifiers.
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
1. //save by A.java
2. package pack;
3. public class A{
4. protected void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B extends A{
6. public static void main(String args[]){
7. B obj = new B();
8. obj.msg();
9. }
10. }
Output:Hello
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2.
3. package mypack;
4. import pack.*;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();
9. obj.msg();
10. }
11. }
Output:Hello
1. class A{
2. protected void msg(){System.out.println("Hello java");}
3. }
4.
5. public class Simple extends A{
6. void msg(){System.out.println("Hello java");}//C.T.Error
7. public static void main(String args[]){
8. Simple obj=new Simple();
9. obj.msg();
10. }
11. }
The default modifier is more restrictive than protected. That is why there is compile time error.
Encapsulation in Java
Encapsulation in java is a process of wrapping code and data together into a single unit, for
example capsule i.e. mixed of several medicines.
We can create a fully encapsulated class in java by making all the data members of the class
private. Now we can use setter and getter methods to set and get the data in it.
The Java Bean class is the example of fully encapsulated class.
1. //save as Student.java
2. package com.java;
3. public class Student{
4. private String name;
5.
6. public String getName(){
7. return name;
8. }
9. public void setName(String name){
10. this.name=name
11. }
12. }
1. //save as Test.java
2. package com.java;
3. class Test{
4. public static void main(String[] args){
5. Student s=new Student();
6. s.setname("vijay");
7. System.out.println(s.getName());
8. }
9. }
1. Object obj=getObject();//we don't what object would be returned from this method
The Object class provides some common behaviours to all the objects such as object can be
compared, object can be cloned, object can be notified etc.
Method Description
returns the Class class object of this object. The
public final ClassgetClass() Class class can further be used to get the metadata
of this class.
public int hashCode() returns the hashcode number for this object.
public boolean equals(Object obj) compares the given object to this object.
protected Object clone() throws creates and returns the exact copy (clone) of this
CloneNotSupportedException object.
public String toString() returns the string representation of this object.
public final void notify() wakes up single thread, waiting on this object's
monitor.
wakes up all the threads, waiting on this object's
public final void notifyAll()
monitor.
causes the current thread to wait for the specified
public final void wait(long timeout)throws
milliseconds, until another thread notifies (invokes
InterruptedException
notify() or notifyAll() method).
causes the current thread to wait for the specified
public final void wait(long timeout,int
miliseconds and nanoseconds, until another thread
nanos)throws InterruptedException
notifies (invokes notify() or notifyAll() method).
causes the current thread to wait, until another
public final void wait()throws
thread notifies (invokes notify() or notifyAll()
InterruptedException
method).
is invoked by the garbage collector before object is
protected void finalize()throws Throwable
being garbage collected.
We will have the detailed learning of these methods in next chapters.
Output:101 amit
101 amit
As you can see in the above example, both reference variables have the same value. Thus, the
clone() copies the values of an object to another. So we don't need to write explicit code to copy
the value of an object to another.
If we create another object by new keyword and assign the values of another object to this one, it
will require a lot of processing on this object. So to save the extra processing task we use clone()
method.
Java Array
Normally, array is a collection of similar type of elements that have contiguous memory location.
Java array is an object the contains elements of similar data type. It is a data structure where we
store similar elements. We can store only fixed set of elements in a java array.
Array in java is index based, first element of the array is stored at 0 index.
● Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
● Random access: We can get any data located at any index position.
● Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size
at runtime. To solve this problem, collection framework is used in java.
1. arrayRefVar=new datatype[size];
1. class Testarray{
2. public static void main(String args[]){
3.
4. int a[]=new int[5];//declaration and instantiation
5. a[0]=10;//initialization
6. a[1]=20;
7. a[2]=70;
8. a[3]=40;
9. a[4]=50;
10.
11. //printing array
12. for(int i=0;i<a.length;i++)//length is the property of array
13. System.out.println(a[i]);
14.
15. }}
Output: 10
20
70
40
50
1. class Testarray1{
2. public static void main(String args[]){
3.
4. int a[]={33,3,4,5};//declaration, instantiation and initialization
5.
6. //printing array
7. for(int i=0;i<a.length;i++)//length is the property of array
8. System.out.println(a[i]);
9.
10. }}
Output:33
3
4
5
1. class Testarray2{
2. static void min(int arr[]){
3. int min=arr[0];
4. for(int i=1;i<arr.length;i++)
5. if(min>arr[i])
6. min=arr[i];
7.
8. System.out.println(min);
9. }
10.
11. public static void main(String args[]){
12.
13. int a[]={33,3,4,5};
14. min(a);//passing array to method
15.
16. }}
Output:3
1. arr[0][0]=1;
2. arr[0][1]=2;
3. arr[0][2]=3;
4. arr[1][0]=4;
5. arr[1][1]=5;
6. arr[1][2]=6;
7. arr[2][0]=7;
8. arr[2][1]=8;
9. arr[2][2]=9;
1. class Testarray3{
2. public static void main(String args[]){
3.
4. //declaring and initializing 2D array
5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
6.
7. //printing 2D array
8. for(int i=0;i<3;i++){
9. for(int j=0;j<3;j++){
10. System.out.print(arr[i][j]+" ");
11. }
12. System.out.println();
13. }
14.
15. }}
Output:1 2 3
2 4 5
4 4 5
What is the class name of java array?
In java, array is an object. For array object, an proxy class is created whose name can be
obtained by getClass().getName() method on the object.
1. class Testarray4{
2. public static void main(String args[]){
3.
4. int arr[]={4,4,5};
5.
6. Class c=arr.getClass();
7. String name=c.getName();
8.
9. System.out.println(name);
10.
11. }}
Output:I
1. class TestArrayCopyDemo {
2. public static void main(String[] args) {
3. char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
4. 'i', 'n', 'a', 't', 'e', 'd' };
5. char[] copyTo = new char[7];
6.
7. System.arraycopy(copyFrom, 2, copyTo, 0, 7);
8. System.out.println(new String(copyTo));
9. }
10. }
Output:caffein
Addition of 2 matrices in java
Let's see a simple example that adds two matrices.
1. class Testarray5{
2. public static void main(String args[]){
3. //creating two matrices
4. int a[][]={{1,3,4},{3,4,5}};
5. int b[][]={{1,3,4},{3,4,5}};
6.
7. //creating another matrix to store the sum of two matrices
8. int c[][]=new int[2][3];
9.
10. //adding and printing addition of 2 matrices
11. for(int i=0;i<2;i++){
12. for(int j=0;j<3;j++){
13. c[i][j]=a[i][j]+b[i][j];
14. System.out.print(c[i][j]+" ");
15. }
16. System.out.println();//new line
17. }
18.
19. }}
Output:2 6 8
6 8 10
Output:
20 20 20
Output:
3 3 3
Output:before change 50
after change 50
1. class Operation2{
2. int data=50;
3.
4. void change(Operation2 op){
5. op.data=op.data+100;//changes will be in the instance variable
6. }
7.
8.
9. public static void main(String args[]){
10. Operation2 op=new Operation2();
11.
12. System.out.println("before change "+op.data);
13. op.change(op);//passing object
14. System.out.println("after change "+op.data);
15.
16. }
17. }
Output:before change 50
after change 150
1. class B{
2. strictfp abstract void m();//Illegal combination of modifiers
3. }
1. class B{
2. strictfp int data=10;//modifier strictfp not allowed here
3. }
1. class B{
2. strictfp B(){}//modifier strictfp not allowed here
3. }
1. package com.abc;
2. /** This class is a user-defined class that contains one methods cube.*/
3. public class M{
4.
5. /** The cube method prints cube of the given number */
6. public static void cube(int n){System.out.println(n*n*n);}
7. }
To create the document API, you need to use the javadoc tool followed by java file name. There
is no need to compile the javafile.
On the command prompt, you need to write:
javadoc M.java
to generate the document api. Now, there will be created a lot of html files. Open the index.html
file to get the information about the classes.
Output: sonoo
jaiswal
1
3
abc
1. class OverloadingExample{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("eating bread...");}
6. }
Java String
Java String provides a lot of concepts that can be performed on a string such as compare,
concat, equals, split, length, replace, compareTo, intern, substring etc.
In java, string is basically an object that represents sequence of char values.
An array of characters works same as java string. For example:
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as:
1. String s="java";
1. By string literal
2. By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
1. String s="welcome";
Each time you create a string literal, the JVM checks the string constant pool first. If the string
already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in
the pool, a new string instance is created and placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//will not create new instance
In the above example only one object will be created. Firstly JVM will not find any string object
with the value "Welcome" in string constant pool, so it will create a new object. After that it will
find the string with the value "Welcome" in the pool, it will not create new object but will return
the reference to the same instance.
Note: String objects are stored in a special memory area known as string
constant pool.
2) By new keyword
java
strings
example
1. class Testimmutablestring{
2. public static void main(String args[]){
3. String s="Sachin";
4. s.concat(" Tendulkar");//concat() method appends the string at the end
5. System.out.println(s);//will print Sachin because strings are immutable objects
6. }
7. }
Output:Sachin
Now it can be understood by the diagram given below. Here Sachin is not changed but a new
object is created with sachintendulkar. That is why string is known as immutable.
As you can see in the above figure that two objects are created but s reference variable still refers
to "Sachin" not to "Sachin Tendulkar".
But if we explicitely assign it to the reference variable, it will refer to "Sachin Tendulkar"
object.For example:
1. class Testimmutablestring1{
2. public static void main(String args[]){
3. String s="Sachin";
4. s=s.concat(" Tendulkar");
5. System.out.println(s);
6. }
7. }
Output:Sachin Tendulkar
In such case, s points to the "Sachin Tendulkar". Please notice that still sachin object is not
modified.
1. By equals() method
2. By = = operator
3. By compareTo() method
Output:true
true
false
1. class Teststringcomparison2{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="SACHIN";
5.
6. System.out.println(s1.equals(s2));//false
7. System.out.println(s1.equalsIgnoreCase(s3));//true
8. }
9. }
Output:false
true
1. class Teststringcomparison3{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3=new String("Sachin");
6. System.out.println(s1==s2);//true (because both refer to same instance)
7. System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)
8. }
9. }
Output:true
false
● s1 == s2 :0
● s1 > s2 :positive value
● s1 < s2 :negative value
1. class Teststringcomparison4{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3="Ratan";
6. System.out.println(s1.compareTo(s2));//0
7. System.out.println(s1.compareTo(s3));//1(because s1>s3)
8. System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
9. }
10. }
Output:0
1
-1
1. class TestStringConcatenation1{
2. public static void main(String args[]){
3. String s="Sachin"+" Tendulkar";
4. System.out.println(s);//Sachin Tendulkar
5. }
6. }
Output:Sachin Tendulkar
The Java compiler transforms above code to this:
In java, String concatenation is implemented through the StringBuilder (or StringBuffer) class
and its append method. String concatenation operator produces a new string by appending the
second operand onto the end of the first operand. The string concatenation operator can concat
not only string but primitive values also. For Example:
1. class TestStringConcatenation2{
2. public static void main(String args[]){
3. String s=50+30+"Sachin"+40+40;
4. System.out.println(s);//80Sachin4040
5. }
6. }
80Sachin4040
Note: After a string literal, all the + will be treated as string concatenation
operator.
2) String Concatenation by concat() method
The String concat() method concatenates the specified string to the end of current string. Syntax:
1. class TestStringConcatenation3{
2. public static void main(String args[]){
3. String s1="Sachin ";
4. String s2="Tendulkar";
5. String s3=s1.concat(s2);
6. System.out.println(s3);//Sachin Tendulkar
7. }
8. }
Sachin Tendulkar
Substring in Java
A part of string is called substring. In other words, substring is a subset of another string. In case
of substring startIndex is inclusive and endIndex is exclusive.
1. public String substring(int startIndex): This method returns new String object
containing the substring of the given string from specified startIndex (inclusive).
2. public String substring(int startIndex, int endIndex): This method returns new String
object containing the substring of the given string from specified startIndex to endIndex.
In case of string:
● startIndex: inclusive
● endIndex: exclusive
Let's understand the startIndex and endIndex by the code given below.
1. String s="hello";
2. System.out.println(s.substring(0,2));//he
In the above substring, 0 points to h but 2 points to e (because end index is exclusive).
Tendulkar
Sachin
Java String class methods
The java.lang.String class provides a lot of methods to work on string. By the help of these
methods, we can perform operations on string such as trimming, concatenating, converting,
comparing, replacing strings etc.
Java String is a powerful concept because everything is treated as a string if you submit any form
in window based, web based or mobile application.
Let's see the important methods of String class.
1. String s="Sachin";
2. System.out.println(s.toUpperCase());//SACHIN
3. System.out.println(s.toLowerCase());//sachin
4. System.out.println(s);//Sachin(no change in original)
SACHIN
sachin
Sachin
Sachin
Sachin
1. String s="Sachin";
2. System.out.println(s.startsWith("Sa"));//true
3. System.out.println(s.endsWith("n"));//true
true
true
Java String charAt() method
The string charAt() method returns a character at specified index.
1. String s="Sachin";
2. System.out.println(s.charAt(0));//S
3. System.out.println(s.charAt(3));//h
S
h
1. String s="Sachin";
2. System.out.println(s.length());//6
Sachin
1. int a=10;
2. String s=String.valueOf(a);
3. System.out.println(s+10);
Output:
1010
Java String replace() method
The string replace() method replaces all occurrence of first sequence of character with second
sequence of character.
Output:
Kava is a programming language. Kava is a platform. Kava is an Island.
Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously. So it is safe and will result in an order.
Important Constructors of StringBuffer class
1. StringBuffer(): creates an empty string buffer with the initial capacity of 16.
2. StringBuffer(String str): creates a string buffer with the specified string.
3. StringBuffer(int capacity): creates an empty string buffer with the specified capacity as
length.
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7. }
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.insert(1,"Java");//now original string is changed
5. System.out.println(sb);//prints HJavaello
6. }
7. }
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.replace(1,3,"Java");
5. System.out.println(sb);//prints HJavalo
6. }
7. }
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.delete(1,3);
5. System.out.println(sb);//prints Hlo
6. }
7. }
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.reverse();
5. System.out.println(sb);//prints olleH
6. }
7. }
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer();
4. System.out.println(sb.capacity());//default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity());//now 16
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. }
10. }
7) StringBuffer ensureCapacity() method
The ensureCapacity() method of StringBuffer class ensures that the given capacity is the
minimum to the current capacity. If it is greater than the current capacity, it increases the
capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be
(16*2)+2=34.
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer();
4. System.out.println(sb.capacity());//default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity());//now 16
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. sb.ensureCapacity(10);//now no change
10. System.out.println(sb.capacity());//now 34
11. sb.ensureCapacity(50);//now (34*2)+2
12. System.out.println(sb.capacity());//now 70
13. }
14. }
1. StringBuilder(): creates an empty string Builder with the initial capacity of 16.
2. StringBuilder(String str): creates a string Builder with the specified string.
3. StringBuilder(int length): creates an empty string Builder with the specified capacity as
length.
1. class A{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7. }
1. class A{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello ");
4. sb.insert(1,"Java");//now original string is changed
5. System.out.println(sb);//prints HJavaello
6. }
7. }
3) StringBuilder replace() method
The StringBuilder replace() method replaces the given string from the specified beginIndex and
endIndex.
1. class A{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.replace(1,3,"Java");
5. System.out.println(sb);//prints HJavalo
6. }
7. }
1. class A{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.delete(1,3);
5. System.out.println(sb);//prints Hlo
6. }
7. }
1. class A{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.reverse();
5. System.out.println(sb);//prints olleH
6. }
7. }
1. class A{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder();
4. System.out.println(sb.capacity());//default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity());//now 16
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. }
10. }
1. class A{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder();
4. System.out.println(sb.capacity());//default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity());//now 16
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. sb.ensureCapacity(10);//now no change
10. System.out.println(sb.capacity());//now 34
11. sb.ensureCapacity(50);//now (34*2)+2
12. System.out.println(sb.capacity());//now 70
13. }
14. }
StringBuffer Example
hellojava
StringBuilder Example
hellojava
● The instance variable of the class is final i.e. we cannot change the value of it after
creating an object.
● The class is final so we cannot create the subclass.
● There is no setter methods i.e. we have no option to change the value of the instance
variable.
1. class Student{
2. int rollno;
3. String name;
4. String city;
5.
6. Student(int rollno, String name, String city){
7. this.rollno=rollno;
8. this.name=name;
9. this.city=city;
10. }
11.
12. public static void main(String args[]){
13. Student s1=new Student(101,"Raj","lucknow");
14. Student s2=new Student(102,"Vijay","ghaziabad");
15.
16. System.out.println(s1);//compiler writes here s1.toString()
17. System.out.println(s2);//compiler writes here s2.toString()
18. }
19. }
Output:Student@1fee6fc
Student@1eed786
As you can see in the above example, printing s1 and s2 prints the hashcode values of the
objects but I want to print the values of these objects. Since java compiler internally calls
toString() method, overriding this method will return the specified values. Let's understand it
with the example given below:
1. class Student{
2. int rollno;
3. String name;
4. String city;
5.
6. Student(int rollno, String name, String city){
7. this.rollno=rollno;
8. this.name=name;
9. this.city=city;
10. }
11.
12. public String toString(){//overriding the toString() method
13. return rollno+" "+name+" "+city;
14. }
15. public static void main(String args[]){
16. Student s1=new Student(101,"Raj","lucknow");
17. Student s2=new Student(102,"Vijay","ghaziabad");
18.
19. System.out.println(s1);//compiler writes here s1.toString()
20. System.out.println(s2);//compiler writes here s2.toString()
21. }
22. }
StringTokenizer in Java
The java.util.StringTokenizer class allows you to break a string into tokens. It is simple way to
break string.
It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like
StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter.
1. import java.util.StringTokenizer;
2. public class Simple{
3. public static void main(String args[]){
4. StringTokenizer st = new StringTokenizer("my name is khan"," ");
5. while (st.hasMoreTokens()) {
6. System.out.println(st.nextToken());
7. }
8. }
9. }
Output:my
name
is
khan
1. import java.util.*;
2.
3. public class Test {
4. public static void main(String[] args) {
5. StringTokenizer st = new StringTokenizer("my,name,is,khan");
6.
7. // printing next token
8. System.out.println("Next token is : " + st.nextToken(","));
9. }
10. }
Output:Next token is : my
Signature
The signature of string charAt() method is given below:
Parameter
index : index number, starts with 0
Returns
char value
Specified by
CharSequence interface
Throws
IndexOutOfBoundsException : if index is negative value or greater than this string length.
Signature
Returns
an integer value
Output:
0
-5
-1
Signature
The signature of string concat() method is given below:
Parameter
anotherString : another string i.e. to be combined at the end of this string.
Returns
combined string
java string
java string is immutable so assign it explicitly
Signature
The signature of string contains() method is given below:
Parameter
sequence : specifies the sequence of characters to be searched.
Returns
true if sequence of char value exists, otherwise false.
Throws
NullPointerException : if sequence is null.
1. class ContainsExample{
2. public static void main(String args[]){
3. String name="what do you know about me";
4. System.out.println(name.contains("do you know"));
5. System.out.println(name.contains("about"));
6. System.out.println(name.contains("hello"));
7. }}
true
true
false
Signature
The syntax or signature of endsWith() method is given below.
Parameter
suffix : Sequence of character
Returns
true or false
Output:
true
true
Signature
Parameter
anotherObject : another object i.e. compared with this string.
Returns
true if characters of both strings are equal otherwise false.
Overrides
equals() method of java Object class.
true
false
false
Signature
There are two type of string format() method:
Parameters
locale : specifies the locale to be applied on the format() method.
format : format of the string.
args : arguments for the format string. It may be zero or more.
Returns
formatted string
Throws
NullPointerException : if format is null.
IllegalFormatException : if format is illegal or incompatible.
name is sonoo
value is 32.334340
value is 32.334340000000
Signature
There are 3 variant of getBytes() method. The signature or syntax of string getBytes() method is
given below:
Returns
sequence of bytes.
Output:
65
66
67
68
69
70
71
Signature
There are 4 types of indexOf method in java. The signature of indexOf methods are given below:
No. Method Description
1 int indexOf(int ch) returns index position for the given char value
returns index position for the given char value and
2 int indexOf(int ch, int fromIndex)
from index
3 int indexOf(String substring) returns index position for the given substring
int indexOf(String substring, int returns index position for the given substring and
4
fromIndex) from index
Parameters
ch: char value i.e. a single character e.g. 'a'
fromIndex: index position from where index of the char value or substring is retured
substring: substring to be searched in this string
Returns
index of the string
Java String indexOf() method example
2 8
5
3
Signature
The signature of intern method is given below:
Returns
interned string
Java String intern() method example
false
true
Signature
The signature or syntax of string isEmpty() method is given below:
Returns
true if length is 0 otherwise false.
Since
1.6
true
false
Signature
The signature or syntax of string join method is given below:
Parameters
delimiter : char value to be added with each element
elements : char value to be attached with delimiter
Returns
joined string with delimiter
Throws
NullPointerException if element or delimiter is null.
Since
1.8
welcome-to-java
Signature
There are 4 types of lastIndexOf method in java. The signature of lastIndexOf methods are given
below:
No. Method Description
1 int lastIndexOf(int ch) returns last index position for the given char value
returns last index position for the given char value
2 int lastIndexOf(int ch, int fromIndex)
and from index
3 int lastIndexOf(String substring) returns last index position for the given substring
int lastIndexOf(String substring, int returns last index position for the given substring
4
fromIndex) and from index
Parameters
ch: char value i.e. a single character e.g. 'a'
fromIndex: index position from where index of the char value or substring is retured
substring: substring to be searched in this string
Returns
last index of the string
Java String lastIndexOf() method example
Output:
6
Signature
The signature of the string length() method is given below:
Specified by
CharSequence interface
Returns
length of characters
Signature
There are two type of replace methods in java string.
Parameters
oldChar : old character
newChar : new character
target : target sequence of characters
replacement : replacement sequence of characters
Returns
replaced string
Signature
Parameters
regex : regular expression
replacement : replacement sequence of characters
Returns
replaced string
MynamewasKhan.MynamewasBob.MynamewasSonoo.
Signature
There are two signature for split() method in java string.
Returns
array of strings
Throws
PatternSyntaxException if pattern for regular expression is invalid
Since
1.4
java
string
split
method
by
java
Java String split() method with regex and length example
returning words:
welcome
to
split
world
returning words:
welcome to split world
returning words:
welcome
to split world
Signature
The syntax or signature of startWith() method is given below.
Returns
true or false
Output:
true
true
Signature
If you don't specify endIndex, java substring() method will return all the characters from
startIndex.
Parameters
startIndex : starting index is inclusive
endIndex : ending index is exclusive
Returns
specified string
Throws
StringIndexOutOfBoundsException if start index is negative value or end index is lower than
starting index.
va
vatpoint
Signature
The signature or syntax of string toCharArray() method is given below:
Returns
character array
Java String toCharArray() method example
Output:
hello
Signature
There are two variant of toLowerCase() method. The signature or syntax of string toLowerCase()
method is given below:
The second method variant of toLowerCase(), converts all the characters into lowercase using
the rules of given Locale.
Returns
string in lowercase letter.
Output:
java hello string
Signature
There are two variant of toUpperCase() method. The signature or syntax of string toUpperCase()
method is given below:
The second method variant of toUpperCase(), converts all the characters into uppercase using the
rules of given Locale.
Returns
string in uppercase letter.
Output:
HELLO STRING
Java String trim
The java string trim() method eliminates leading and trailing spaces. The unicode value of
space character is '\u0020'. The trim() method in java string checks this unicode value before and
after the string, if it exists then removes the spaces and returns the omitted string.
Signature
The signature or syntax of string trim method is given below:
Returns
string with omitted leading and trailing spaces
Signature
The signature or syntax of string valueOf() method is given below:
Returns
string representation of given value
Output:
3010
Java Regex
The Java Regex or Regular Expression is an API to define pattern for searching or
manipulating strings.
It is widely used to define constraint on strings such as password and email validation. After
learning java regex tutorial, you will be able to test your own regular expressions by the Java
Regex Tester Tool.
Java Regex API provides 1 interface and 3 classes in java.util.regex package.
java.util.regex package
It provides following classes and interface for regular expressions. The Matcher and Pattern
classes are widely used in java regular expression.
1. MatchResult interface
2. Matcher class
3. Pattern class
4. PatternSyntaxException class
Matcher class
It implements MatchResult interface. It is a regex engine i.e. used to perform match operations
on a character sequence.
No. Method Description
1 boolean matches() test whether the regular expression matches the pattern.
2 boolean find() finds the next expression that matches the pattern.
boolean find(int finds the next expression that matches the pattern from the given start
3
start) number.
Pattern class
It is the compiled version of a regular expression. It is used to define a pattern for the regex
engine.
No. Method Description
static Pattern compile(String compiles the given regex and return the instance of
1
regex) pattern.
Matcher matcher(CharSequence creates a matcher that matches the given input with
2
input) pattern.
It works as the combination of compile and matcher
static boolean matches(String
3 methods. It compiles the regular expression and
regex, CharSequence input)
matches the given input with the pattern.
splits the given input string around matches of given
4 String[] split(CharSequence input)
pattern.
5 String pattern() returns the regex pattern.
1. import java.util.regex.*;
2. public class RegexExample1{
3. public static void main(String args[]){
4. //1st way
5. Pattern p = Pattern.compile(".s");//. represents single character
6. Matcher m = p.matcher("as");
7. boolean b = m.matches();
8.
9. //2nd way
10. boolean b2=Pattern.compile(".s").matcher("as").matches();
11.
12. //3rd way
13. boolean b3 = Pattern.matches(".s", "as");
14.
15. System.out.println(b+" "+b2+" "+b3);
16. }}
Output
true true true
1. import java.util.regex.*;
2. class RegexExample2{
3. public static void main(String args[]){
4. System.out.println(Pattern.matches(".s", "as"));//true (2nd char is s)
5. System.out.println(Pattern.matches(".s", "mk"));//false (2nd char is not s)
6. System.out.println(Pattern.matches(".s", "mst"));//false (has more than 2 char)
7. System.out.println(Pattern.matches(".s", "amms"));//false (has more than 2 char)
8. System.out.println(Pattern.matches("..s", "mas"));//true (3rd char is s)
9. }}
1. import java.util.regex.*;
2. class RegexExample3{
3. public static void main(String args[]){
4. System.out.println(Pattern.matches("[amn]", "abcd"));//false (not a or m or n)
5. System.out.println(Pattern.matches("[amn]", "a"));//true (among a or m or n)
6. System.out.println(Pattern.matches("[amn]", "ammmna"));//false (m and a comes more
than once)
7. }}
Regex Quantifiers
The quantifiers specify the number of occurrences of a character.
Regex Description
X? X occurs once or not at all
X+ X occurs once or more times
X* X occurs zero or more times
X{n} X occurs n times only
X{n,} X occurs n or more times
X{y,z} X occurs at least y times but less than z times
1. import java.util.regex.*;
2. class RegexExample4{
3. public static void main(String args[]){
4. System.out.println("? quantifier ....");
5. System.out.println(Pattern.matches("[amn]?", "a"));//true (a or m or n comes one time)
Regex Metacharacters
The regular expression metacharacters work as a short codes.
Regex Description
. Any character (may or may not match terminator)
\d Any digits, short of [0-9]
\D Any non-digit, short for [^0-9]
\s Any whitespace character, short for [\t\n\x0B\f\r]
\S Any non-whitespace character, short for [^\s]
\w Any word character, short for [a-zA-Z_0-9]
\W Any non-word character, short for [^\w]
\b A word boundary
\B A non word boundary
1. import java.util.regex.*;
2. class RegexExample5{
3. public static void main(String args[]){
4. System.out.println("metacharacters d....");\\d means digit
5.
6. System.out.println(Pattern.matches("\\d", "abc"));//false (non-digit)
7. System.out.println(Pattern.matches("\\d", "1"));//true (digit and comes once)
8. System.out.println(Pattern.matches("\\d", "4443"));//false (digit but comes more than o
nce)
9. System.out.println(Pattern.matches("\\d", "323abc"));//false (digit and char)
10.
11. System.out.println("metacharacters D....");\\D means non-digit
12.
13. System.out.println(Pattern.matches("\\D", "abc"));//false (non-
digit but comes more than once)
14. System.out.println(Pattern.matches("\\D", "1"));//false (digit)
15. System.out.println(Pattern.matches("\\D", "4443"));//false (digit)
16. System.out.println(Pattern.matches("\\D", "323abc"));//false (digit and char)
17. System.out.println(Pattern.matches("\\D", "m"));//true (non-digit and comes once)
18.
19. System.out.println("metacharacters D with quantifier....");
20. System.out.println(Pattern.matches("\\D*", "mak"));//true (non-
digit and may come 0 or more times)
21.
22. }}
1. /*Create a regular expression that accepts alpha numeric characters only. Its
2. length must be 6 characters long only.*/
3.
4. import java.util.regex.*;
5. class RegexExample6{
6. public static void main(String args[]){
7. System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "arun32"));//true
8. System.out.println(Pattern.matches("[a-zA-Z0-
9]{6}", "kkvarun32"));//false (more than 6 char)
9. System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "JA2Uk2"));//true
10. System.out.println(Pattern.matches("[a-zA-Z0-
9]{6}", "arun$2"));//false ($ is not matched)
11. }}
What is exception
Dictionary Meaning: Exception is an abnormal condition.
In java, exception is an event that disrupts the normal flow of the program. It is an object which
is thrown at runtime.
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Suppose there is 10 statements in your program and there occurs an exception at statement 5, rest
of the code will not be executed i.e. statement 6 to 10 will not run. If we perform exception
handling, rest of the statement will be executed. That is why we use exception handling in java.
Do You Know ?
● What is the difference between checked and unchecked exceptions ?
● What happens behind the code int data=50/0; ?
● Why use multiple catch block ?
● Is there any possibility when finally block is not executed ?
● What is exception propagation ?
● What is the difference between throw and throws keyword ?
● What are the 4 rules for using exception handling with method overriding ?
Hierarchy of Java Exception classes
Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is considered as
unchecked exception. The sun microsystem says there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
Difference between checked and unchecked exceptions
1) Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known as
checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at
compile-time.
2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked
exceptions are not checked at compile-time rather they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
1. int a=50/0;//ArithmeticException
1. String s=null;
2. System.out.println(s.length());//NullPointerException
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
4) Scenario where ArrayIndexOutOfBoundsException occurs
If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:
1. try
2. catch
3. finally
4. throw
5. throws
Java try-catch
1. try{
2. //code that may throw exception
3. }catch(Exception_class_Name ref){}
1. try{
2. //code that may throw exception
3. }finally{}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
As displayed in the above example, rest of the code is not executed (in such case, rest of the
code... statement is not printed).
There can be 100 lines of code after exception. So all the code after exception will not be
executed.
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
Now, as displayed in the above example, rest of the code is executed i.e. rest of the code...
statement is printed.
Internal working of java try-catch block
The JVM firstly checks whether the exception is handled or not. If exception is not handled,
JVM provides a default exception handler that performs the following tasks:
But if exception is handled by the application programmer, normal flow of the application is
maintained i.e. rest of the code is executed.
Output:task1 completed
rest of the code...
Rule: At a time only one Exception is occured and at a time only one catch block
is executed.
Rule: All catch blocks must be ordered from most specific to most general i.e.
catch for ArithmeticException must come before catch for Exception .
1. class TestMultipleCatchBlock1{
2. public static void main(String args[]){
3. try{
4. int a[]=new int[5];
5. a[5]=30/0;
6. }
7. catch(Exception e){System.out.println("common task completed");}
8. catch(ArithmeticException e){System.out.println("task1 is completed");}
9. catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
10. System.out.println("rest of the code...");
11. }
12. }
Output:
Compile-time error
Syntax:
1. ....
2. try
3. {
4. statement 1;
5. statement 2;
6. try
7. {
8. statement 1;
9. statement 2;
10. }
11. catch(Exception e)
12. {
13. }
14. }
15. catch(Exception e)
16. {
17. }
18. ....
1. class Excep6{
2. public static void main(String args[]){
3. try{
4. try{
5. System.out.println("going to divide");
6. int b =39/0;
7. }catch(ArithmeticException e){System.out.println(e);}
8.
9. try{
10. int a[]=new int[5];
11. a[5]=4;
12. }catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
13.
14. System.out.println("other statement);
15. }catch(Exception e){System.out.println("handeled");}
16.
17. System.out.println("normal flow..");
18. }
19. }
● Finally block in java can be used to put "cleanup" code such as closing a file, closing
connection etc.
Case 1
Let's see the java finally example where exception doesn't occur.
1. class TestFinallyBlock{
2. public static void main(String args[]){
3. try{
4. int data=25/5;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8. finally{System.out.println("finally block is always executed");}
9. System.out.println("rest of the code...");
10. }
11. }
Output:5
finally block is always executed
rest of the code...
Case 2
Let's see the java finally example where exception occurs and not handled.
1. class TestFinallyBlock1{
2. public static void main(String args[]){
3. try{
4. int data=25/0;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8. finally{System.out.println("finally block is always executed");}
9. System.out.println("rest of the code...");
10. }
11. }
Case 3
Let's see the java finally example where exception occurs and handled.
Rule: For each try block there can be zero or more catch blocks, but only one
finally block.
Note: The finally block will not be executed if program exits(either by calling
System.exit() or by causing a fatal error that causes the process to abort).
Output:
Exception in thread main java.lang.ArithmeticException:not valid
1. class TestExceptionPropagation1{
2. void m(){
3. int data=50/0;
4. }
5. void n(){
6. m();
7. }
8. void p(){
9. try{
10. n();
11. }catch(Exception e){System.out.println("exception handled");}
12. }
13. public static void main(String args[]){
14. TestExceptionPropagation1 obj=new TestExceptionPropagation1();
15. obj.p();
16. System.out.println("normal flow...");
17. }
18. }
Output:exception handled
normal flow...
In the above example exception occurs in m() method where it is not handled,so it is propagated
to previous n() method where it is not handled, again it is propagated to p() method where
exception is handled.
Exception can be handled in any method in call stack either in main() method,p() method,n()
method or m() method.
1. class TestExceptionPropagation2{
2. void m(){
3. throw new java.io.IOException("device error");//checked exception
4. }
5. void n(){
6. m();
7. }
8. void p(){
9. try{
10. n();
11. }catch(Exception e){System.out.println("exception handeled");}
12. }
13. public static void main(String args[]){
14. TestExceptionPropagation2 obj=new TestExceptionPropagation2();
15. obj.p();
16. System.out.println("normal flow");
17. }
18. }
1. import java.io.IOException;
2. class Testthrows1{
3. void m()throws IOException{
4. throw new IOException("device error");//checked exception
5. }
6. void n()throws IOException{
7. m();
8. }
9. void p(){
10. try{
11. n();
12. }catch(Exception e){System.out.println("exception handled");}
13. }
14. public static void main(String args[]){
15. Testthrows1 obj=new Testthrows1();
16. obj.p();
17. System.out.println("normal flow...");
18. }
19. }
Output:
exception handled
normal flow...
Rule: If you are calling a method that declares an exception, you must either
caught or declare the exception.
There are two cases:
1. Case1:You caught the exception i.e. handle the exception using try/catch.
2. Case2:You declare the exception i.e. specifying throws with the method.
● In case you handle the exception, the code will be executed fine whether exception
occurs during the program or not.
1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7. public class Testthrows2{
8. public static void main(String args[]){
9. try{
10. M m=new M();
11. m.method();
12. }catch(Exception e){System.out.println("exception handled");}
13.
14. System.out.println("normal flow...");
15. }
16. }
Output:exception handled
normal flow...
● A)In case you declare the exception, if exception does not occur, the code will be
executed fine.
● B)In case you declare the exception if exception occures, an exception will be thrown at
runtime because throws does not handle the exception.
1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. System.out.println("device operation performed");
5. }
6. }
7. class Testthrows3{
8. public static void main(String args[])throws IOException{//declare exception
9. M m=new M();
10. m.method();
11.
12. System.out.println("normal flow...");
13. }
14. }
1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7. class Testthrows4{
8. public static void main(String args[])throws IOException{//declare exception
9. M m=new M();
10. m.method();
11.
12. System.out.println("normal flow...");
13. }
14. }
Output:Runtime Exception
1. void m(){
2. throw new ArithmeticException("sorry");
3. }
1. class FinalExample{
2. public static void main(String[] args){
3. final int x=100;
4. x=200;//Compile Time Error
5. }}
1. class FinallyExample{
2. public static void main(String[] args){
3. try{
4. int x=300;
5. }catch(Exception e){System.out.println(e);}
6. finally{System.out.println("finally block is executed");}
7. }}
1. class FinalizeExample{
2. public void finalize(){System.out.println("finalize called");}
3. public static void main(String[] args){
4. FinalizeExample f1=new FinalizeExample();
5. FinalizeExample f2=new FinalizeExample();
6. f1=null;
7. f2=null;
8. System.gc();
9. }}
1. import java.io.*;
2. class Parent{
3. void msg(){System.out.println("parent");}
4. }
5.
6. class TestExceptionChild extends Parent{
7. void msg()throws IOException{
8. System.out.println("TestExceptionChild");
9. }
10. public static void main(String args[]){
11. Parent p=new TestExceptionChild();
12. p.msg();
13. }
14. }
1. import java.io.*;
2. class Parent{
3. void msg(){System.out.println("parent");}
4. }
5.
6. class TestExceptionChild1 extends Parent{
7. void msg()throws ArithmeticException{
8. System.out.println("child");
9. }
10. public static void main(String args[]){
11. Parent p=new TestExceptionChild1();
12. p.msg();
13. }
14. }
Output:child
If the superclass method declares an exception
1. import java.io.*;
2. class Parent{
3. void msg()throws ArithmeticException{System.out.println("parent");}
4. }
5.
6. class TestExceptionChild2 extends Parent{
7. void msg()throws Exception{System.out.println("child");}
8.
9. public static void main(String args[]){
10. Parent p=new TestExceptionChild2();
11. try{
12. p.msg();
13. }catch(Exception e){}
14. }
15. }
1. import java.io.*;
2. class Parent{
3. void msg()throws Exception{System.out.println("parent");}
4. }
5.
6. class TestExceptionChild3 extends Parent{
7. void msg()throws Exception{System.out.println("child");}
8.
9. public static void main(String args[]){
10. Parent p=new TestExceptionChild3();
11. try{
12. p.msg();
13. }catch(Exception e){}
14. }
15. }
Output:child
1. import java.io.*;
2. class Parent{
3. void msg()throws Exception{System.out.println("parent");}
4. }
5.
6. class TestExceptionChild4 extends Parent{
7. void msg()throws ArithmeticException{System.out.println("child");}
8.
9. public static void main(String args[]){
10. Parent p=new TestExceptionChild4();
11. try{
12. p.msg();
13. }catch(Exception e){}
14. }
15. }
Output:child
1. import java.io.*;
2. class Parent{
3. void msg()throws Exception{System.out.println("parent");}
4. }
5.
6. class TestExceptionChild5 extends Parent{
7. void msg(){System.out.println("child");}
8.
9. public static void main(String args[]){
10. Parent p=new TestExceptionChild5();
11. try{
12. p.msg();
13. }catch(Exception e){}
14. }
15. }
Output:child
1. class Java_Outer_class{
2. //code
3. class Java_Inner_class{
4. //code
5. }
6. }
● What is the internal code generated by the compiler for member inner class ?
● What are the two ways to create annonymous inner class ?
● Can we access the non-final local variable inside the local inner class ?
● How to access the static nested class ?
● Can we define an interface within the class ?
● Can we define a class within the interface ?
Type Description
Member Inner Class A class created within class and outside method.
Anonymous Inner A class created for implementing interface or extending class. Its name is
Class decided by the java compiler.
Local Inner Class A class created within method.
Static Nested Class A static class created within class.
Nested Interface An interface created within class or interface.
1. class Outer{
2. //code
3. class Inner{
4. //code
5. }
6. }
1. class TestMemberOuter1{
2. private int data=30;
3. class Inner{
4. void msg(){System.out.println("data is "+data);}
5. }
6. public static void main(String args[]){
7. TestMemberOuter1 obj=new TestMemberOuter1();
8. TestMemberOuter1.Inner in=obj.new Inner();
9. in.msg();
10. }
11. }
Output:
data is 30
1. import java.io.PrintStream;
2. class Outer$Inner
3. {
4. final Outer this$0;
5. Outer$Inner()
6. { super();
7. this$0 = Outer.this;
8. }
9. void msg()
10. {
11. System.out.println((new StringBuilder()).append("data is ")
12. .append(Outer.access$000(Outer.this)).toString());
13. }
14. }
1. import java.io.PrintStream;
2. static class TestAnonymousInner$1 extends Person
3. {
4. TestAnonymousInner$1(){}
5. void eat()
6. {
7. System.out.println("nice fruits");
8. }
9. }
1. interface Eatable{
2. void eat();
3. }
4. class TestAnnonymousInner1{
5. public static void main(String args[]){
6. Eatable e=new Eatable(){
7. public void eat(){System.out.println("nice fruits");}
8. };
9. e.eat();
10. }
11. }
Output:
nice fruits
Internal working of given code
It performs two main tasks behind this code:
1. import java.io.PrintStream;
2. static class TestAnonymousInner1$1 implements Eatable
3. {
4. TestAnonymousInner1$1(){}
5. void eat(){System.out.println("nice fruits");}
6. }
Output:
30
1. import java.io.PrintStream;
2. class localInner1$Local
3. {
4. final localInner1 this$0;
5. localInner1$Local()
6. {
7. super();
8. this$0 = Simple.this;
9. }
10. void msg()
11. {
12. System.out.println(localInner1.access$000(localInner1.this));
13. }
14. }
2) Local inner class cannot access non-final local variable till JDK 1.7. Since JDK
1.8, it is possible to access the non-final local variable in local inner class.
1. class localInner2{
2. private int data=30;//instance variable
3. void display(){
4. int value=50;//local variable must be final till jdk 1.7 only
5. class Local{
6. void msg(){System.out.println(value);}
7. }
8. Local l=new Local();
9. l.msg();
10. }
11. public static void main(String args[]){
12. localInner2 obj=new localInner2();
13. obj.display();
14. }
15. }
Output:
50
1. class TestOuter1{
2. static int data=30;
3. static class Inner{
4. void msg(){System.out.println("data is "+data);}
5. }
6. public static void main(String args[]){
7. TestOuter1.Inner obj=new TestOuter1.Inner();
8. obj.msg();
9. }
10. }
Output:
data is 30
In this example, you need to create the instance of static nested class because it has instance
method msg(). But you don't need to create the object of Outer class because nested class is static
and static properties, methods or classes can be accessed without object.
1. import java.io.PrintStream;
2. static class TestOuter1$Inner
3. {
4. TestOuter1$Inner(){}
5. void msg(){
6. System.out.println((new StringBuilder()).append("data is ")
7. .append(TestOuter1.data).toString());
8. }
9. }
1. class TestOuter2{
2. static int data=30;
3. static class Inner{
4. static void msg(){System.out.println("data is "+data);}
5. }
6. public static void main(String args[]){
7. TestOuter2.Inner.msg();//no need to create the instance of static nested class
8. }
9. }
Output:
data is 30
● Nested interface must be public if it is declared inside the interface but it can have any
access modifier if declared within the class.
● Nested interfaces are declared static implicitely.
1. interface interface_name{
2. ...
3. interface nested_interface_name{
4. ...
5. }
6. }
Syntax of nested interface which is declared within the class
1. class class_name{
2. ...
3. interface nested_interface_name{
4. ...
5. }
6. }
Internal code generated by the java compiler for nested interface Message
The java compiler internally creates public and static interface as displayed below:.
1. public static interface Showable$Message
2. {
3. public abstract void msg();
4. }
1. interface M{
2. class A{}
3. }
Multithreading in Java
Multithreading in java is a process of executing multiple threads simultaneously.
Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking.
But we use multithreading than multiprocessing because threads share a common memory area.
They don't allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process.
Java Multithreading is mostly used in games, animation etc.
Advantage of Java Multithreading
1) It doesn't block the user because threads are independent and you can perform multiple
operations at same time.
2) You can perform many operations together so it saves time.
3) Threads are independent so it doesn't affect other threads if exception occur in a single
thread.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to
utilize the CPU. Multitasking can be achieved by two ways:
● Process-based Multitasking(Multiprocessing)
● Thread-based Multitasking(Multithreading)
● Each process have its own address in memory i.e. each process allocates separate
memory area.
● Process is heavyweight.
● Cost of communication between the process is high.
● Switching from one process to another require some time for saving and loading
registers, memory maps, updating lists etc.
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
1) New
The thread is in new state if you create an instance of Thread class but before the invocation of
start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not
selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
A thread is in terminated or dead state when its run() method exits.
Thread class:
Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread. Runnable interface have only one method named run().
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following
tasks:
Output:thread is running...
Output:thread is running...
If you are not extending the Thread class,your class object would not be treated as a thread
object.So you need to explicitely create Thread class object.We are passing the object of your
class that implements Runnable so that your class run() method may execute.
Output:
1
1
2
2
3
3
4
4
As you know well that at a time only one thread is executed. If you sleep a thread for the
specified time,the thread shedular picks up another thread and so on.
Can we start a thread twice
No. After starting a thread, it can never be started again. If you does so, an
IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it
will throw exception.
Let's understand it by the example given below:
running
Exception in thread "main" java.lang.IllegalThreadStateException
Output:running...
Problem if you direct call run() method
Output:1
2
3
4
5
1
2
3
4
5
As you can see in the above program that there is no context-switching because here t1 and t2
will be treated as normal object not thread object.
Syntax:
public void join()throws InterruptedException
public void join(long milliseconds)throws InterruptedException
Example of join() method
Output:1
2
3
4
5
1
1
2
2
3
3
4
4
5
5
As you can see in the above example,when t1 completes its task then t2 and t3 starts executing.
Example of join(long miliseconds) method
Output:1
2
3
1
4
1
2
5
2
3
3
4
4
5
5
In the above example,when t1 is completes its task for 1500 miliseconds(3 times) then t2 and t3
starts executing.
getName(),setName(String) and getId() method:
public String getName()
public void setName(String name)
public long getId()
1. class TestJoinMethod3 extends Thread{
2. public void run(){
3. System.out.println("running...");
4. }
5. public static void main(String args[]){
6. TestJoinMethod3 t1=new TestJoinMethod3();
7. TestJoinMethod3 t2=new TestJoinMethod3();
8. System.out.println("Name of t1:"+t1.getName());
9. System.out.println("Name of t2:"+t2.getName());
10. System.out.println("id of t1:"+t1.getId());
11.
12. t1.start();
13. t2.start();
14.
15. t1.setName("Sonoo Jaiswal");
16. System.out.println("After changing name of t1:"+t1.getName());
17. }
18. }
Output:Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
running...
After changling name of t1:Sonoo Jaiswal
running...
Syntax:
public static Thread currentThread()
Example of currentThread() method
Output:Thread-0
Thread-1
Naming a thread:
The Thread class provides methods to change and get the name of a thread.
Output:Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
running...
After changeling name of t1:Sonoo Jaiswal
running...
● public static Thread currentThread(): returns the reference of currently running thread.
●
Output:Thread-0
Thread-1
5.
6. }
7. public static void main(String args[]){
8. TestMultiPriority1 m1=new TestMultiPriority1();
9. TestMultiPriority1 m2=new TestMultiPriority1();
10. m1.setPriority(Thread.MIN_PRIORITY);
11. m2.setPriority(Thread.MAX_PRIORITY);
12. m1.start();
13. m2.start();
14.
15. }
16. }
● It provides services to user threads for background supporting tasks. It has no role in life
than to serve user threads.
● Its life depends on user threads.
● It is a low priority thread.
Output
daemon thread work
user thread work
user thread work
Note: If you want to make a user thread as Daemon, it must not be started
otherwise it will throw IllegalThreadStateException.
File: MyThread.java
1. import java.util.concurrent.ExecutorService;
2. import java.util.concurrent.Executors;
3. class WorkerThread implements Runnable {
4. private String message;
5. public WorkerThread(String s){
6. this.message=s;
7. }
8. public void run() {
9. System.out.println(Thread.currentThread().getName()+" (Start) message = "+messa
ge);
10. processmessage();//call processmessage method that sleeps the thread for 2 secon
ds
11. System.out.println(Thread.currentThread().getName()+" (End)");//prints thread na
me
12. }
13. private void processmessage() {
14. try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); }
15. }
16. }
File: JavaThreadPoolExample.java
Output:
pool-1-thread-1 (Start) message = 0
pool-1-thread-2 (Start) message = 1
pool-1-thread-3 (Start) message = 2
pool-1-thread-5 (Start) message = 4
pool-1-thread-4 (Start) message = 3
pool-1-thread-2 (End)
pool-1-thread-2 (Start) message = 5
pool-1-thread-1 (End)
pool-1-thread-1 (Start) message = 6
pool-1-thread-3 (End)
pool-1-thread-3 (Start) message = 7
pool-1-thread-4 (End)
pool-1-thread-4 (Start) message = 8
pool-1-thread-5 (End)
pool-1-thread-5 (Start) message = 9
pool-1-thread-2 (End)
pool-1-thread-1 (End)
pool-1-thread-4 (End)
pool-1-thread-3 (End)
pool-1-thread-5 (End)
Finished all threads
ThreadGroup in Java
Java provides a convenient way to group multiple threads in a single object. In such way, we can
suspend, resume or interrupt group of threads by a single method call.
Now all 3 threads belong to one group. Here, tg1 is the thread group name, MyRunnable is the
class that implements Runnable interface and "one", "two" and "three" are the thread names.
Now we can interrupt all threads by a single line of code only.
1. Thread.currentThread().getThreadGroup().interrupt();
ThreadGroup Example
File: ThreadGroupDemo.java
Output:
one
two
three
Thread Group Name: Parent ThreadGroup
java.lang.ThreadGroup[name=Parent ThreadGroup,maxpri=10]
Thread[one,5,Parent ThreadGroup]
Thread[two,5,Parent ThreadGroup]
Thread[three,5,Parent ThreadGroup]
Shutdown Hook
The shutdown hook can be used to perform cleanup resource or save the state when JVM shuts
down normally or abruptly. Performing clean resource means closing log file, sending some
alerts or something else. So if you want to execute some code before JVM shuts down, use
shutdown hook.
The object of Runtime class can be obtained by calling the static factory method getRuntime().
For example:
Runtime r = Runtime.getRuntime();
Factory method
The method that returns the instance of a class is known as factory method.
Simple example of Shutdown Hook
Note: The shutdown sequence can be stopped by invoking the halt(int) method
of Runtime class.
Output:task one
task one
task one
Program of performing single task by multiple threads
Output:task one
task one
Output:task one
task two
1. class TestMultitasking4{
2. public static void main(String args[]){
3. Thread t1=new Thread(){
4. public void run(){
5. System.out.println("task one");
6. }
7. };
8. Thread t2=new Thread(){
9. public void run(){
10. System.out.println("task two");
11. }
12. };
13.
14.
15. t1.start();
16. t2.start();
17. }
18. }
Output:task one
task two
1. class TestMultitasking5{
2. public static void main(String args[]){
3. Runnable r1=new Runnable(){
4. public void run(){
5. System.out.println("task one");
6. }
7. };
8.
9. Runnable r2=new Runnable(){
10. public void run(){
11. System.out.println("task two");
12. }
13. };
14.
15. Thread t1=new Thread(r1);
16. Thread t2=new Thread(r2);
17.
18. t1.start();
19. t2.start();
20. }
21. }
Output:task one
task two
● It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
● It is automatically done by the garbage collector(a part of JVM) so we don't need to
make extra efforts.
1) By nulling a reference:
3) By annonymous object:
1. new Employee();
finalize() method
The finalize() method is invoked each time before the object is garbage collected. This method
can be used to perform cleanup processing. This method is defined in Object class as:
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc()
is found in System and Runtime classes.
Synchronization in Java
Synchronization in java is the capability to control the access of multiple threads to any shared
resource.
Java Synchronization is better option where we want to allow only one thread to access the
shared resource.
Why use Synchronization
The synchronization is mainly used to
Types of Synchronization
There are two types of synchronization
1. Process Synchronization
2. Thread Synchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
2. Cooperation (Inter-thread communication in java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data. This
can be done by three ways in java:
1. by synchronized method
2. by synchronized block
3. by static synchronization
1. Class Table{
2.
3. void printTable(int n){//method not synchronized
4. for(int i=1;i<=5;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){System.out.println(e);}
9. }
10.
11. }
12. }
13.
14. class MyThread1 extends Thread{
15. Table t;
16. MyThread1(Table t){
17. this.t=t;
18. }
19. public void run(){
20. t.printTable(5);
21. }
22.
23. }
24. class MyThread2 extends Thread{
25. Table t;
26. MyThread2(Table t){
27. this.t=t;
28. }
29. public void run(){
30. t.printTable(100);
31. }
32. }
33.
34. class TestSynchronization1{
35. public static void main(String args[]){
36. Table obj = new Table();//only one object
37. MyThread1 t1=new MyThread1(obj);
38. MyThread2 t2=new MyThread2(obj);
39. t1.start();
40. t2.start();
41. }
42. }
Output: 5
100
10
200
15
300
20
400
25
500
Output: 5
10
15
20
25
100
200
300
400
500
Output: 5
10
15
20
25
100
200
300
400
500
1. class Table{
2.
3. void printTable(int n){
4. synchronized(this){//synchronized block
5. for(int i=1;i<=5;i++){
6. System.out.println(n*i);
7. try{
8. Thread.sleep(400);
9. }catch(Exception e){System.out.println(e);}
10. }
11. }
12. }//end of the method
13. }
14.
15. class MyThread1 extends Thread{
16. Table t;
17. MyThread1(Table t){
18. this.t=t;
19. }
20. public void run(){
21. t.printTable(5);
22. }
23.
24. }
25. class MyThread2 extends Thread{
26. Table t;
27. MyThread2(Table t){
28. this.t=t;
29. }
30. public void run(){
31. t.printTable(100);
32. }
33. }
34.
35. public class TestSynchronizedBlock1{
36. public static void main(String args[]){
37. Table obj = new Table();//only one object
38. MyThread1 t1=new MyThread1(obj);
39. MyThread2 t2=new MyThread2(obj);
40. t1.start();
41. t2.start();
42. }
43. }
Output:5
10
15
20
25
100
200
300
400
500
1. class Table{
2.
3. void printTable(int n){
4. synchronized(this){//synchronized block
5. for(int i=1;i<=5;i++){
6. System.out.println(n*i);
7. try{
8. Thread.sleep(400);
9. }catch(Exception e){System.out.println(e);}
10. }
11. }
12. }//end of the method
13. }
14.
15. public class TestSynchronizedBlock2{
16. public static void main(String args[]){
17. final Table obj = new Table();//only one object
18.
19. Thread t1=new Thread(){
20. public void run(){
21. obj.printTable(5);
22. }
23. };
24. Thread t2=new Thread(){
25. public void run(){
26. obj.printTable(100);
27. }
28. };
29.
30. t1.start();
31. t2.start();
32. }
33. }
Output:5
10
15
20
25
100
200
300
400
500
Static synchronization
If you make any static method as synchronized, the lock will be on the class not on object.
Problem without static synchronization
Suppose there are two objects of a shared class(e.g. Table) named object1 and object2.In case of
synchronized method and synchronized block there cannot be interference between t1 and t2 or
t3 and t4 because t1 and t2 both refers to a common object that have a single lock.But there can
be interference between t1 and t3 or t2 and t4 because t1 acquires another lock and t3 acquires
another lock.I want no interference between t1 and t3 or t2 and t4.Static synchronization solves
this problem.
1. class Table{
2.
3. synchronized static void printTable(int n){
4. for(int i=1;i<=10;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){}
9. }
10. }
11. }
12.
13. class MyThread1 extends Thread{
14. public void run(){
15. Table.printTable(1);
16. }
17. }
18.
19. class MyThread2 extends Thread{
20. public void run(){
21. Table.printTable(10);
22. }
23. }
24.
25. class MyThread3 extends Thread{
26. public void run(){
27. Table.printTable(100);
28. }
29. }
30.
31.
32.
33.
34. class MyThread4 extends Thread{
35. public void run(){
36. Table.printTable(1000);
37. }
38. }
39.
40. public class TestSynchronization4{
41. public static void main(String t[]){
42. MyThread1 t1=new MyThread1();
43. MyThread2 t2=new MyThread2();
44. MyThread3 t3=new MyThread3();
45. MyThread4 t4=new MyThread4();
46. t1.start();
47. t2.start();
48. t3.start();
49. t4.start();
50. }
51. }
Output: 1
2
3
4
5
6
7
8
9
10
10
20
30
40
50
60
70
80
90
100
100
200
300
400
500
600
700
800
900
1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000
1. class Table{
2.
3. synchronized static void printTable(int n){
4. for(int i=1;i<=10;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){}
9. }
10. }
11. }
12.
13. public class TestSynchronization5 {
14. public static void main(String[] args) {
15.
16. Thread t1=new Thread(){
17. public void run(){
18. Table.printTable(1);
19. }
20. };
21.
22. Thread t2=new Thread(){
23. public void run(){
24. Table.printTable(10);
25. }
26. };
27.
28. Thread t3=new Thread(){
29. public void run(){
30. Table.printTable(100);
31. }
32. };
33.
34. Thread t4=new Thread(){
35. public void run(){
36. Table.printTable(1000);
37. }
38. };
39. t1.start();
40. t2.start();
41. t3.start();
42. t4.start();
43.
44. }
45. }
Output: 1
2
3
4
5
6
7
8
9
10
10
20
30
40
50
60
70
80
90
100
100
200
300
400
500
600
700
800
900
1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000
Deadlock in java
Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a thread is
waiting for an object lock, that is acquired by another thread and second thread is waiting for an
object lock that is acquired by first thread. Since, both threads are waiting for each other to
release the lock, the condition is called deadlock.
Example of Deadlock in java
● wait()
● notify()
● notifyAll()
1) wait() method
Causes current thread to release the lock and wait until either another thread invokes the notify()
method or the notifyAll() method for this object, or a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.
Method Description
public final void wait()throws InterruptedException waits until object is notified.
public final void wait(long timeout)throws waits for the specified amount of
InterruptedException time.
2) notify() method
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on
this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the
discretion of the implementation. Syntax:
public final void notify()
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax:
public final void notifyAll()
Why wait(), notify() and notifyAll() methods are defined in Object class not
Thread class?
It is because they are related to lock and object has a lock.
1. class Customer{
2. int amount=10000;
3.
4. synchronized void withdraw(int amount){
5. System.out.println("going to withdraw...");
6.
7. if(this.amount<amount){
8. System.out.println("Less balance; waiting for deposit...");
9. try{wait();}catch(Exception e){}
10. }
11. this.amount-=amount;
12. System.out.println("withdraw completed...");
13. }
14.
15. synchronized void deposit(int amount){
16. System.out.println("going to deposit...");
17. this.amount+=amount;
18. System.out.println("deposit completed... ");
19. notify();
20. }
21. }
22.
23. class Test{
24. public static void main(String args[]){
25. final Customer c=new Customer();
26. new Thread(){
27. public void run(){c.withdraw(15000);}
28. }.start();
29. new Thread(){
30. public void run(){c.deposit(10000);}
31. }.start();
32.
33. }}
Output: going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
Interrupting a Thread:
If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the
interrupt() method on the thread, breaks out the sleeping or waiting state throwing
InterruptedException. If the thread is not in the sleeping or waiting state, calling the interrupt()
method performs normal behaviour and doesn't interrupt the thread but sets the interrupt flag
to true. Let's first see the methods provided by the Thread class for thread interruption.
Output:Exception in thread-0
java.lang.RuntimeException: Thread interrupted...
java.lang.InterruptedException: sleep interrupted
at A.run(A.java:7)
Output:Exception handled
java.lang.InterruptedException: sleep interrupted
thread is running...
Output:1
2
3
4
5
Let's understand the java reentrant monitor by the example given below:
1. class Reentrant {
2. public synchronized void m() {
3. n();
4. System.out.println("this is m() method");
5. }
6. public synchronized void n() {
7. System.out.println("this is n() method");
8. }
9. }
In this class, m and n are the synchronized methods. The m() method internally calls the n()
method.
Now let's call the m() method on a thread. In the class given below, we are creating thread using
annonymous class.
Stream
A stream is a sequence of data.In Java a stream is composed of bytes. It's called a stream because
it's like a stream of water that continues to flow.
In java, 3 streams are created for us automatically. All these streams are attached with console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
Let's see the code to print output and error message to the console.
1. System.out.println("simple message");
2. System.err.println("error message");
Do You Know ?
● How to write a common data to multiple files using single stream only ?
● How can we access multiple files by single stream ?
● How can we improve the performance of Input and Output operation ?
● How many ways can we read data from the keyboard?
● What is console class ?
● How to compress and uncompress the data of a file?
OutputStream
Java application uses an output stream to write data to a destination, it may be a file,an
array,peripheral device or socket.
InputStream
Java application uses an input stream to read data from a source, it may be a file,an
array,peripheral device or socket.
Let's understand working of Java OutputStream and InputStream by the figure given below.
OutputStream class
OutputStream class is an abstract class.It is the superclass of all classes representing an output
stream of bytes. An output stream accepts output bytes and sends them to some sink.
1. import java.io.*;
2. class Test{
3. public static void main(String args[]){
4. try{
5. FileOutputstream fout=new FileOutputStream("abc.txt");
6. String s="Sachin Tendulkar is my favourite player";
7. byte b[]=s.getBytes();//converting string into byte array
8. fout.write(b);
9. fout.close();
10. System.out.println("success...");
11. }catch(Exception e){system.out.println(e);}
12. }
13. }
Output:success...
1. import java.io.*;
2. class SimpleRead{
3. public static void main(String args[]){
4. try{
5. FileInputStream fin=new FileInputStream("abc.txt");
6. int i=0;
7. while((i=fin.read())!=-1){
8. System.out.println((char)i);
9. }
10. fin.close();
11. }catch(Exception e){system.out.println(e);}
12. }
13. }
1. import java.io.*;
2. class C{
3. public static void main(String args[])throws Exception{
4. FileInputStream fin=new FileInputStream("C.java");
5. FileOutputStream fout=new FileOutputStream("M.java");
6. int i=0;
7. while((i=fin.read())!=-1){
8. fout.write((byte)i);
9. }
10. fin.close();
11. }
12. }
1. import java.io.*;
2. class S{
3. public static void main(String args[])throws Exception{
4. FileOutputStream fout1=new FileOutputStream("f1.txt");
5. FileOutputStream fout2=new FileOutputStream("f2.txt");
6.
7. ByteArrayOutputStream bout=new ByteArrayOutputStream();
8. bout.write(139);
9. bout.writeTo(fout1);
10. bout.writeTo(fout2);
11.
12. bout.flush();
13. bout.close();//has no effect
14. System.out.println("success...");
15. }
16. }
success...
Java SequenceInputStream class
Java SequenceInputStream class is used to read data from multiple streams. It reads data of
streams one by one.
1. import java.io.*;
2. class Simple{
3. public static void main(String args[])throws Exception{
4. FileinputStream fin1=new FileinputStream("f1.txt");
5. FileinputStream fin2=new FileinputStream("f2.txt");
6.
7. SequenceinputStream sis=new SequenceinputStream(fin1,fin2);
8. int i;
9. while((i=sis.read())!=-1){
10. System.out.println((char)i);
11. }
12. sis.close();
13. fin1.close();
14. fin2.close();
15. }
16. }
Example of SequenceInputStream class that reads the data from multiple files
using enumeration
If we need to read the data from more than two files, we need to have these information in the
Enumeration object. Enumeration object can be get by calling elements method of the Vector
class. Let's see the simple example where we are reading the data from the 4 files.
1. import java.io.*;
2. import java.util.*;
3.
4. class B{
5. public static void main(String args[])throws IOException{
6.
7. //creating the FileInputStream objects for all the files
8. FileInputStream fin=new FileInputStream("A.java");
9. FileInputStream fin2=new FileInputStream("abc2.txt");
10. FileInputStream fin3=new FileInputStream("abc.txt");
11. FileInputStream fin4=new FileInputStream("B.java");
12.
13. //creating Vector object to all the stream
14. Vector v=new Vector();
15. v.add(fin);
16. v.add(fin2);
17. v.add(fin3);
18. v.add(fin4);
19.
20. //creating enumeration object by calling the elements method
21. Enumeration e=v.elements();
22.
23. //passing the enumeration object in the constructor
24. SequenceInputStream bin=new SequenceInputStream(e);
25. int i=0;
26.
27. while((i=bin.read())!=-1){
28. System.out.print((char)i);
29. }
30.
31. bin.close();
32. fin.close();
33. fin2.close();
34. }
35. }
1. import java.io.*;
2. class Test{
3. public static void main(String args[])throws Exception{
4. FileOutputStream fout=new FileOutputStream("f1.txt");
5. BufferedOutputStream bout=new BufferedOutputStream(fout);
6. String s="Sachin is my favourite player";
7. byte b[]=s.getBytes();
8. bout.write(b);
9.
10. bout.flush();
11. bout.close();
12. fout.close();
13. System.out.println("success");
14. }
15. }
Output:
success...
1. import java.io.*;
2. class SimpleRead{
3. public static void main(String args[]){
4. try{
5. FileInputStream fin=new FileInputStream("f1.txt");
6. BufferedInputStream bin=new BufferedInputStream(fin);
7. int i;
8. while((i=bin.read())!=-1){
9. System.out.println((char)i);
10. }
11. bin.close();
12. fin.close();
13. }catch(Exception e){system.out.println(e);}
14. }
15. }
Output:
Sachin is my favourite player
1. import java.io.*;
2. class Simple{
3. public static void main(String args[]){
4. try{
5. FileWriter fw=new FileWriter("abc.txt");
6. fw.write("my name is sachin");
7. fw.close();
8. }catch(Exception e){System.out.println(e);}
9. System.out.println("success");
10. }
11. }
Output:
success...
1. import java.io.*;
2. class Simple{
3. public static void main(String args[])throws Exception{
4. FileReader fr=new FileReader("abc.txt");
5. int i;
6. while((i=fr.read())!=-1)
7. System.out.println((char)i);
8.
9. fr.close();
10. }
11. }
Output:
my name is sachin
CharArrayWriter class:
The CharArrayWriter class can be used to write data to multiple files. This class implements the
Appendable interface. Its buffer automatically grows when data is written in this stream. Calling
the close() method on this object has no effect.
1. import java.io.*;
2. class Simple{
3. public static void main(String args[])throws Exception{
4.
5. CharArrayWriter out=new CharArrayWriter();
6. out.write("my name is");
7.
8. FileWriter f1=new FileWriter("a.txt");
9. FileWriter f2=new FileWriter("b.txt");
10. FileWriter f3=new FileWriter("c.txt");
11. FileWriter f4=new FileWriter("d.txt");
12.
13. out.writeTo(f1);
14. out.writeTo(f2);
15. out.writeTo(f3);
16. out.writeTo(f4);
17.
18.
19. f1.close();
20. f2.close();
21. f3.close();
22. f4.close();
23. }
24. }
● InputStreamReader
● Console
● Scanner
● DataInputStream etc.
InputStreamReader class
InputStreamReader class can be used to read data from keyboard.It performs two tasks:
BufferedReader class
BufferedReader class can be used to read data line by line by readLine() method.
1. import java.io.*;
2. class G5{
3. public static void main(String args[])throws Exception{
4.
5. InputStreamReader r=new InputStreamReader(System.in);
6. BufferedReader br=new BufferedReader(r);
7.
8. System.out.println("Enter your name");
9. String name=br.readLine();
10. System.out.println("Welcome "+name);
11. }
12. }
1. import java.io.*;
2. class G5{
3. public static void main(String args[])throws Exception{
4.
5. InputStreamReader r=new InputStreamReader(System.in);
6. BufferedReader br=new BufferedReader(r);
7.
8. String name="";
9.
10. while(!name.equals("stop")){
11. System.out.println("Enter data: ");
12. name=br.readLine();
13. System.out.println("data is: "+name);
14. }
15.
16. br.close();
17. r.close();
18. }
19. }
1. String text=System.console().readLine();
2. System.out.println("Text is: "+text);
Methods of Console class
Let's see the commonly used methods of Console class.
Method Description
1) public String readLine() is used to read a single line of text from the console.
2) public String readLine(String it provides a formatted prompt then reads the single line
fmt,Object... args) of text from the console.
is used to read password that is not being displayed on
3) public char[] readPassword()
the console.
4) public char[] readPassword(String it provides a formatted prompt then reads the password
fmt,Object... args) that is not being displayed on the console.
1. Console c=System.console();
1. import java.io.*;
2. class ReadStringTest{
3. public static void main(String args[]){
4. Console c=System.console();
5. System.out.println("Enter your name: ");
6. String n=c.readLine();
7. System.out.println("Welcome "+n);
8. }
9. }
Output:
Enter your name: james gosling
Welcome james gosling
1. import java.io.*;
2. class ReadPasswordTest{
3. public static void main(String args[]){
4. Console c=System.console();
5. System.out.println("Enter password: ");
6. char[] ch=c.readPassword();
7. String pass=String.valueOf(ch);//converting char array into string
8. System.out.println("Password is: "+pass);
9. }
10. }
Output:
Enter password:
Password is: sonoo
1. import java.util.Scanner;
2. class ScannerTest{
3. public static void main(String args[]){
4. Scanner sc=new Scanner(System.in);
5.
6. System.out.println("Enter your rollno");
7. int rollno=sc.nextInt();
8. System.out.println("Enter your name");
9. String name=sc.next();
10. System.out.println("Enter your fee");
11. double fee=sc.nextDouble();
12. System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
13. sc.close();
14. }
15. }
Output:
Enter your rollno
111
Enter your name
Ratan
Enter
450000
Rollno:111 name:Ratan fee:450000
1. import java.util.*;
2. public class ScannerTest2{
3. public static void main(String args[]){
4. String input = "10 tea 20 coffee 30 tea buiscuits";
5. Scanner s = new Scanner(input).useDelimiter("\\s");
6. System.out.println(s.nextInt());
7. System.out.println(s.next());
8. System.out.println(s.nextInt());
9. System.out.println(s.next());
10. s.close();
11. }}
Output:
10
tea
20
coffee
java.io.PrintStream class:
The PrintStream class provides methods to write data to another stream. The PrintStream class
automatically flushes the data so there is no need to call flush() method. Moreover, its methods
don't throw IOException.
Output:10
DeflaterOutputStream class:
The DeflaterOutputStream class is used to compress the data in the deflate compression format.
It provides facility to the other compression filters, such as GZIPOutputStream.
Example of Compressing file using DeflaterOutputStream class
In this example, we are reading data of a file and compressing it into another file using
DeflaterOutputStream class. You can compress any file, here we are compressing the
Deflater.java file
1. import java.io.*;
2. import java.util.zip.*;
3.
4. class Compress{
5. public static void main(String args[]){
6.
7. try{
8. FileInputStream fin=new FileInputStream("Deflater.java");
9.
10. FileOutputStream fout=new FileOutputStream("def.txt");
11. DeflaterOutputStream out=new DeflaterOutputStream(fout);
12.
13. int i;
14. while((i=fin.read())!=-1){
15. out.write((byte)i);
16. out.flush();
17. }
18.
19. fin.close();
20. out.close();
21.
22. }catch(Exception e){System.out.println(e);}
23. System.out.println("rest of the code");
24. }
25. }
InflaterInputStream class:
The InflaterInputStream class is used to uncompress the file in the deflate compression format. It
provides facility to the other uncompression filters, such as GZIPInputStream class.
1. import java.io.*;
2. import java.util.zip.*;
3.
4. class UnCompress{
5. public static void main(String args[]){
6.
7. try{
8. FileInputStream fin=new FileInputStream("def.txt");
9. InflaterInputStream in=new InflaterInputStream(fin);
10.
11. FileOutputStream fout=new FileOutputStream("D.java");
12.
13. int i;
14. while((i=in.read())!=-1){
15. fout.write((byte)i);
16. fout.flush();
17. }
18.
19. fin.close();
20. fout.close();
21. in.close();
22.
23. }catch(Exception e){System.out.println(e);}
24. System.out.println("rest of the code");
25. }
26. }
1. import java.io.*;
2. class PipedWR{
3. public static void main(String args[])throws Exception{
4. final PipedOutputStream pout=new PipedOutputStream();
5. final PipedInputStream pin=new PipedInputStream();
6.
7. pout.connect(pin);//connecting the streams
8. //creating one thread t1 which writes the data
9. Thread t1=new Thread(){
10. public void run(){
11. for(int i=65;i<=90;i++){
12. try{
13. pout.write(i);
14. Thread.sleep(1000);
15. }catch(Exception e){}
16. }
17. }
18. };
19. //creating another thread t2 which reads the data
20. Thread t2=new Thread(){
21. public void run(){
22. try{
23. for(int i=65;i<=90;i++)
24. System.out.println(pin.read());
25. }catch(Exception e){}
26. }
27. };
28. //starting both threads
29. t1.start();
30. t2.start();
31. }}
Serialization in Java
Serialization in java is a mechanism of writing the state of an object into a byte stream.
It is mainly used in Hibernate, RMI, JPA, EJB, JMS technologies.
The reverse operation of serialization is called deserialization.
The String class and all the wrapper classes implements java.io.Serializable interface by default.
java.io.Serializable interface
Serializable is a marker interface (has no body). It is just used to "mark" java classes which
support a certain capability.
It must be implemented by the class whose object you want to persist. Let's see the example given
below:
1. import java.io.Serializable;
2. public class Student implements Serializable{
3. int id;
4. String name;
5. public Student(int id, String name) {
6. this.id = id;
7. this.name = name;
8. }
9. }
ObjectOutputStream class
The ObjectOutputStream class is used to write primitive data types and Java objects to an
OutputStream. Only objects that support the java.io.Serializable interface can be written to
streams.
Constructor
1) public ObjectOutputStream(OutputStream out) throws IOException {}creates an
ObjectOutputStream that writes to the specified OutputStream.
Important Methods
Method Description
1) public final void writeObject(Object obj) throws writes the specified object to the
IOException {} ObjectOutputStream.
2) public void flush() throws IOException {} flushes the current output stream.
3) public void close() throws IOException {} closes the current output stream.
1. import java.io.*;
2. class Persist{
3. public static void main(String args[])throws Exception{
4. Student s1 =new Student(211,"ravi");
5.
6. FileOutputStream fout=new FileOutputStream("f.txt");
7. ObjectOutputStream out=new ObjectOutputStream(fout);
8.
9. out.writeObject(s1);
10. out.flush();
11. System.out.println("success");
12. }
13. }
success
Deserialization in java
Deserialization is the process of reconstructing the object from the serialized state.It is the reverse
operation of serialization.
ObjectInputStream class
An ObjectInputStream deserializes objects and primitive data written using an
ObjectOutputStream.
Constructor
1) public ObjectInputStream(InputStream in) creates an ObjectInputStream that reads
throws IOException {} from the specified InputStream.
Important Methods
Method Description
1) public final Object readObject() throws IOException, reads an object from the input
ClassNotFoundException{} stream.
2) public void close() throws IOException {} closes ObjectInputStream.
1. import java.io.*;
2. class Depersist{
3. public static void main(String args[])throws Exception{
4.
5. ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
6. Student s=(Student)in.readObject();
7. System.out.println(s.id+" "+s.name);
8.
9. in.close();
10. }
11. }
211 ravi
1. import java.io.Serializable;
2. class Person implements Serializable{
3. int id;
4. String name;
5. Person(int id, String name) {
6. this.id = id;
7. this.name = name;
8. }
9. }
1. class Student extends Person{
2. String course;
3. int fee;
4. public Student(int id, String name, String course, int fee) {
5. super(id,name);
6. this.course=course;
7. this.fee=fee;
8. }
9. }
Now you can serialize the Student class object that extends the Person class which is
Serializable.Parent class properties are inherited to subclasses so if parent class is Serializable,
subclass would also be.
1. class Address{
2. String addressLine,city,state;
3. public Address(String addressLine, String city, String state) {
4. this.addressLine=addressLine;
5. this.city=city;
6. this.state=state;
7. }
8. }
1. import java.io.Serializable;
2. public class Student implements Serializable{
3. int id;
4. String name;
5. Address address;//HAS-A
6. public Student(int id, String name) {
7. this.id = id;
8. this.name = name;
9. }
10. }
Since Address is not Serializable, you can not serialize the instance of Student class.
Externalizable in java
The Externalizable interface provides the facility of writing the state of an object into a byte
stream in compress format. It is not a marker interface.
The Externalizable interface provides two methods:
1. import java.io.Serializable;
2. public class Student implements Serializable{
3. int id;
4. String name;
5. transient int age;//Now it will not be serialized
6. public Student(int id, String name,int age) {
7. this.id = id;
8. this.name = name;
9. this.age=age;
10. }
11. }
1. import java.io.*;
2. class PersistExample{
3. public static void main(String args[])throws Exception{
4. Student s1 =new Student(211,"ravi",22);//creating object
5. //writing object into file
6. FileOutputStream f=new FileOutputStream("f.txt");
7. ObjectOutputStream out=new ObjectOutputStream(f);
8. out.writeObject(s1);
9. out.flush();
10.
11. out.close();
12. f.close();
13. System.out.println("success");
14. }
15. }
Output:
success
Now write the code for deserialization.
1. import java.io.*;
2. class DePersist{
3. public static void main(String args[])throws Exception{
4. ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
5. Student s=(Student)in.readObject();
6. System.out.println(s.id+" "+s.name+" "+s.age);
7. in.close();
8. }
9. }
211 ravi 0
As you can see, printing age of the student returns 0 because value of age was not serialized.
Java Networking
Java Networking is a concept of connecting two or more computing devices together so that we
can share resources.
Java socket programming provides facility to share data between different computing devices.
1. sharing resources
2. centralize software management
Do You Know ?
1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket
1) IP Address
IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is composed
of octets that range from 0 to 255.
It is a logical address that can be changed.
2) Protocol
A protocol is a set of rules basically that is followed for communication. For example:
● TCP
● FTP
● Telnet
● SMTP
● POP etc.
3) Port Number
The port number is used to uniquely identify different applications. It acts as a communication
endpoint between applications.
The port number is associated with the IP address for communication between two applications.
4) MAC Address
MAC (Media Access Control) Address is a unique identifier of NIC (Network Interface
Controller). A network node can have multiple NIC but each with unique MAC.
6) Socket
A socket is an endpoint between two way communication.
Visit next page for java socket programming.
What we will learn in Networking Tutorial
Important methods
Method Description
1) public InputStream getInputStream() returns the InputStream attached with this socket.
2) public OutputStream getOutputStream() returns the OutputStream attached with this socket.
3) public synchronized void close() closes this socket
ServerSocket class
The ServerSocket class can be used to create a server socket. This object is used to establish
communication with the clients.
Important methods
Method Description
returns the socket and establish a connection between server
1) public Socket accept()
and client.
2) public synchronized void
closes the server socket.
close()
1. import java.io.*;
2. import java.net.*;
3. public class MyServer {
4. public static void main(String[] args){
5. try{
6. ServerSocket ss=new ServerSocket(6666);
7. Socket s=ss.accept();//establishes connection
8. DataInputStream dis=new DataInputStream(s.getInputStream());
9. String str=(String)dis.readUTF();
10. System.out.println("message= "+str);
11. ss.close();
12. }catch(Exception e){System.out.println(e);}
13. }
14. }
File: MyClient.java
1. import java.io.*;
2. import java.net.*;
3. public class MyClient {
4. public static void main(String[] args) {
5. try{
6. Socket s=new Socket("localhost",6666);
7. DataOutputStream dout=new DataOutputStream(s.getOutputStream());
8. dout.writeUTF("Hello Server");
9. dout.flush();
10. dout.close();
11. s.close();
12. }catch(Exception e){System.out.println(e);}
13. }
14. }
To execute this program open two command prompts and execute each program at each
command prompt as displayed in the below figure.
After running the client application, a message will be displayed on the server console.
Example of Java Socket Programming (Read-Write both side)
In this example, client will write first to the server then server will receive and print the text.
Then server will write to the client and client will receive and print the text. The step goes on.
File: MyServer.java
1. import java.net.*;
2. import java.io.*;
3. class MyServer{
4. public static void main(String args[])throws Exception{
5. ServerSocket ss=new ServerSocket(3333);
6. Socket s=ss.accept();
7. DataInputStream din=new DataInputStream(s.getInputStream());
8. DataOutputStream dout=new DataOutputStream(s.getOutputStream());
9. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
10.
11. String str="",str2="";
12. while(!str.equals("stop")){
13. str=din.readUTF();
14. System.out.println("client says: "+str);
15. str2=br.readLine();
16. dout.writeUTF(str2);
17. dout.flush();
18. }
19. din.close();
20. s.close();
21. ss.close();
22. }}
File: MyClient.java
1. import java.net.*;
2. import java.io.*;
3. class MyClient{
4. public static void main(String args[])throws Exception{
5. Socket s=new Socket("localhost",3333);
6. DataInputStream din=new DataInputStream(s.getInputStream());
7. DataOutputStream dout=new DataOutputStream(s.getOutputStream());
8. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
9.
10. String str="",str2="";
11. while(!str.equals("stop")){
12. str=br.readLine();
13. dout.writeUTF(str);
14. dout.flush();
15. str2=din.readUTF();
16. System.out.println("Server says: "+str2);
17. }
18.
19. dout.close();
20. s.close();
21. }}
Java URL
The Java URL class represents an URL. URL is an acronym for Uniform Resource Locator. It
points to a resource on the World Wide Web. For example:
1. http://www.java.com/java-tutorial
1. //URLDemo.java
2. import java.io.*;
3. import java.net.*;
4. public class URLDemo{
5. public static void main(String[] args){
6. try{
7. URL url=new URL("http://www.java.com/java-tutorial");
8.
9. System.out.println("Protocol: "+url.getProtocol());
10. System.out.println("Host Name: "+url.getHost());
11. System.out.println("Port Number: "+url.getPort());
12. System.out.println("File Name: "+url.getFile());
13.
14. }catch(Exception e){System.out.println(e);}
15. }
16. }
Output:
Protocol: http
Host Name: www.java.com
Port Number: -1
File Name: /java-tutorial
1. import java.io.*;
2. import java.net.*;
3. public class URLConnectionExample {
4. public static void main(String[] args){
5. try{
6. URL url=new URL("http://www.java.com/java-tutorial");
7. URLConnection urlcon=url.openConnection();
8. InputStream stream=urlcon.getInputStream();
9. int i;
10. while((i=stream.read())!=-1){
11. System.out.print((char)i);
12. }
13. }catch(Exception e){System.out.println(e);}
14. }
15. }
1. import java.io.*;
2. import java.net.*;
3. public class HttpURLConnectionDemo{
4. public static void main(String[] args){
5. try{
6. URL url=new URL("http://www.java.com/java-tutorial");
7. HttpURLConnection huc=(HttpURLConnection)url.openConnection();
8. for(int i=1;i<=8;i++){
9. System.out.println(huc.getHeaderFieldKey(i)+" = "+huc.getHeaderField(i));
10. }
11. huc.disconnect();
12. }catch(Exception e){System.out.println(e);}
13. }
14. }
Output:
Date = Wed, 10 Dec 2014 19:31:14 GMT
Set-Cookie = JSESSIONID=D70B87DBB832820CACA5998C90939D48; Path=/
Content-Type = text/html
Cache-Control = max-age=2592000
Expires = Fri, 09 Jan 2015 19:31:14 GMT
Vary = Accept-Encoding,User-Agent
Connection = close
Transfer-Encoding = chunked
1. import java.io.*;
2. import java.net.*;
3. public class InetDemo{
4. public static void main(String[] args){
5. try{
6. InetAddress ip=InetAddress.getByName("www.java.com");
7.
8. System.out.println("Host Name: "+ip.getHostName());
9. System.out.println("IP Address: "+ip.getHostAddress());
10. }catch(Exception e){System.out.println(e);}
11. }
12. }
Output:
Host Name: www.java.com
IP Address: 206.51.231.148
1. //DSender.java
2. import java.net.*;
3. public class DSender{
4. public static void main(String[] args) throws Exception {
5. DatagramSocket ds = new DatagramSocket();
6. String str = "Welcome java";
7. InetAddress ip = InetAddress.getByName("127.0.0.1");
8.
9. DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);
10. ds.send(dp);
11. ds.close();
12. }
13. }
1. //DReceiver.java
2. import java.net.*;
3. public class DReceiver{
4. public static void main(String[] args) throws Exception {
5. DatagramSocket ds = new DatagramSocket(3000);
6. byte[] buf = new byte[1024];
7. DatagramPacket dp = new DatagramPacket(buf, 1024);
8. ds.receive(dp);
9. String str = new String(dp.getData(), 0, dp.getLength());
10. System.out.println(str);
11. ds.close();
12. }
13. }
Container
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such as
Frame, Dialog and Panel.
Window
The window is the container that have no borders and menu bars. You must use frame, dialog or
another window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.
1. import java.awt.*;
2. class First extends Frame{
3. First(){
4. Button b=new Button("click me");
5. b.setBounds(30,100,80,30);// setting button position
6.
7. add(b);//adding button into frame
8. setSize(300,300);//frame size 300 width and 300 height
9. setLayout(null);//no layout manager
10. setVisible(true);//now frame will be visible, by default not visible
11. }
12. public static void main(String args[]){
13. First f=new First();
14. }}
The setBounds(int xaxis, int yaxis, int width, int height) method is used in the above example
that sets the position of the awt button.
1. import java.awt.*;
2. class First2{
3. First2(){
4. Frame f=new Frame();
5.
6. Button b=new Button("click me");
7. b.setBounds(30,50,80,30);
8.
9. f.add(b);
10. f.setSize(300,300);
11. f.setLayout(null);
12. f.setVisible(true);
13. }
14. public static void main(String args[]){
15. First2 f=new First2();
16. }}
For registering the component with the Listener, many classes provide the registration methods.
For example:
● Button
o public void addActionListener(ActionListener a){}
● MenuItem
o public void addActionListener(ActionListener a){}
● TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
● TextArea
o public void addTextListener(TextListener a){}
● Checkbox
o public void addItemListener(ItemListener a){}
● Choice
o public void addItemListener(ItemListener a){}
● List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
EventHandling Codes:
We can put the event handling code into one of the following places:
1. Same class
2. Other class
3. Annonymous class
1. import java.awt.*;
2. import java.awt.event.*;
3.
4. class AEvent extends Frame implements ActionListener{
5. TextField tf;
6. AEvent(){
7.
8. tf=new TextField();
9. tf.setBounds(60,50,170,20);
10.
11. Button b=new Button("click me");
12. b.setBounds(100,120,80,30);
13.
14. b.addActionListener(this);
15.
16. add(b);add(tf);
17.
18. setSize(300,300);
19. setLayout(null);
20. setVisible(true);
21.
22. }
23.
24. public void actionPerformed(ActionEvent e){
25. tf.setText("Welcome");
26. }
27.
28. public static void main(String args[]){
29. new AEvent();
30. }
31. }
public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the above
example that sets the position of the component it may be button, textfield etc.
1. import java.awt.*;
2. import java.awt.event.*;
3. class AEvent2 extends Frame{
4. TextField tf;
5. AEvent2(){
6.
7. tf=new TextField();
8. tf.setBounds(60,50,170,20);
9.
10. Button b=new Button("click me");
11. b.setBounds(100,120,80,30);
12.
13. Outer o=new Outer(this);
14. b.addActionListener(o);//passing outer class instance
15.
16. add(b);add(tf);
17.
18. setSize(300,300);
19. setLayout(null);
20. setVisible(true);
21. }
22. public static void main(String args[]){
23. new AEvent2();
24. }
25. }
1. import java.awt.event.*;
2. class Outer implements ActionListener{
3. AEvent2 obj;
4. Outer(AEvent2 obj){
5. this.obj=obj;
6. }
7. public void actionPerformed(ActionEvent e){
8. obj.tf.setText("welcome");
9. }
10. }
1. import java.awt.*;
2. import java.awt.event.*;
3. class AEvent3 extends Frame{
4. TextField tf;
5. AEvent3(){
6. tf=new TextField();
7. tf.setBounds(60,50,170,20);
8. Button b=new Button("click me");
9. b.setBounds(50,120,80,30);
10.
11. b.addActionListener(new ActionListener(){
12. public void actionPerformed(){
13. tf.setText("hello");
14. }
15. });
16. add(b);add(tf);
17. setSize(300,300);
18. setLayout(null);
19. setVisible(true);
20. }
21. public static void main(String args[]){
22. new AEvent3();
23. }
24. }
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.
Do You Know
We can write the code of swing inside the main(), constructor or any other method.
1. import javax.swing.*;
2. public class FirstSwingExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame();//creating instance of JFrame
5.
6. JButton b=new JButton("click");//creating instance of JButton
7. b.setBounds(130,100,100, 40);//x axis, y axis, width, height
8.
9. f.add(b);//adding button in JFrame
10.
11. f.setSize(400,500);//400 width and 500 height
12. f.setLayout(null);//using no layout managers
13. f.setVisible(true);//making the frame visible
14. }
15. }
Example of Swing by Association inside constructor
We can also write all the codes of creating JFrame, JButton and method call inside the java
constructor.
File: Simple.java
1. import javax.swing.*;
2. public class Simple {
3. JFrame f;
4. Simple(){
5. f=new JFrame();//creating instance of JFrame
6.
7. JButton b=new JButton("click");//creating instance of JButton
8. b.setBounds(130,100,100, 40);
9.
10. f.add(b);//adding button in JFrame
11.
12. f.setSize(400,500);//400 width and 500 height
13. f.setLayout(null);//using no layout managers
14. f.setVisible(true);//making the frame visible
15. }
16.
17. public static void main(String[] args) {
18. new Simple();
19. }
20. }
The setBounds(int xaxis, int yaxis, int width, int height)is used in the above example that sets the
position of the button.
1. import javax.swing.*;
2. public class Simple2 extends JFrame{//inheriting JFrame
3. JFrame f;
4. Simple2(){
5. JButton b=new JButton("click");//create button
6. b.setBounds(130,100,100, 40);
7.
8. add(b);//adding button on frame
9. setSize(400,500);
10. setLayout(null);
11. setVisible(true);
12. }
13. public static void main(String[] args) {
14. new Simple2();
15. }}
● JButton class
● JRadioButton class
● JTextArea class
● JComboBox class
● JTable class
● JColorChooser class
● JProgressBar class
● JSlider class
● Digital Watch
● Graphics in swing
● Displaying image
● Edit menu code for Notepad
● OpenDialog Box
● Notepad
● Puzzle Game
● Pic Puzzle Game
● Tic Tac Toe Game
● BorderLayout
● GridLayout
● FlowLayout
● CardLayout
JButton class:
The JButton class is used to create a button that have plateform-independent implementation.
1. import java.awt.event.*;
2. import javax.swing.*;
3.
4. public class ImageButton{
5. ImageButton(){
6. JFrame f=new JFrame();
7.
8.
9. JButton b=new JButton(new ImageIcon("b.jpg"));
10. b.setBounds(130,100,100, 40);
11.
12. f.add(b);
13.
14. f.setSize(300,400);
15. f.setLayout(null);
16. f.setVisible(true);
17.
18. f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
19.
20. }
21.
22. public static void main(String[] args) {
23. new ImageButton();
24. }
25. }
JRadioButton class
The JRadioButton class is used to create a radio button. It is used to choose one option from
multiple options. It is widely used in exam systems or quiz.
It should be added in ButtonGroup to select one radio button only.
Note: The JRadioButton class extends the JToggleButton class that extends
AbstractButton class.
1. import javax.swing.*;
2. public class Radio {
3. JFrame f;
4.
5. Radio(){
6. f=new JFrame();
7.
8. JRadioButton r1=new JRadioButton("A) Male");
9. JRadioButton r2=new JRadioButton("B) FeMale");
10. r1.setBounds(50,100,70,30);
11. r2.setBounds(50,150,70,30);
12.
13. ButtonGroup bg=new ButtonGroup();
14. bg.add(r1);bg.add(r2);
15.
16. f.add(r1);f.add(r2);
17.
18. f.setSize(300,300);
19. f.setLayout(null);
20. f.setVisible(true);
21. }
22. public static void main(String[] args) {
23. new Radio();
24. }
25. }
ButtonGroup class:
The ButtonGroup class can be used to group multiple buttons so that at a time only one button
can be selected.
JRadioButton example with event handling
1. import javax.swing.*;
2. import java.awt.event.*;
3. class RadioExample extends JFrame implements ActionListener{
4. JRadioButton rb1,rb2;
5. JButton b;
6. RadioExample(){
7.
8. rb1=new JRadioButton("Male");
9. rb1.setBounds(100,50,100,30);
10.
11. rb2=new JRadioButton("Female");
12. rb2.setBounds(100,100,100,30);
13.
14. ButtonGroup bg=new ButtonGroup();
15. bg.add(rb1);bg.add(rb2);
16.
17. b=new JButton("click");
18. b.setBounds(100,150,80,30);
19. b.addActionListener(this);
20.
21. add(rb1);add(rb2);add(b);
22.
23. setSize(300,300);
24. setLayout(null);
25. setVisible(true);
26. }
27. public void actionPerformed(ActionEvent e){
28. if(rb1.isSelected()){
29. JOptionPane.showMessageDialog(this,"You are male");
30. }
31. if(rb2.isSelected()){
32. JOptionPane.showMessageDialog(this,"You are female");
33. }
34. }
35. public static void main(String args[]){
36. new RadioExample();
37. }}
JTextArea
class (Swing Tutorial):
The JTextArea class is used to create a text area. It is a multiline area that displays the plain text
only.
1. import java.awt.Color;
2. import javax.swing.*;
3.
4. public class TArea {
5. JTextArea area;
6. JFrame f;
7. TArea(){
8. f=new JFrame();
9.
10. area=new JTextArea(300,300);
11. area.setBounds(10,30,300,300);
12.
13. area.setBackground(Color.black);
14. area.setForeground(Color.white);
15.
16. f.add(area);
17.
18. f.setSize(400,400);
19. f.setLayout(null);
20. f.setVisible(true);
21. }
22. public static void main(String[] args) {
23. new TArea();
24. }
25. }
JComboBox class:
The JComboBox class is used to create the combobox (drop-down list). At a time only one item
can be selected from the item list.
Commonly used Constructors of JComboBox class:
JComboBox()
JComboBox(Object[] items)
JComboBox(Vector<?> items)
1. import javax.swing.*;
2. public class Combo {
3. JFrame f;
4. Combo(){
5. f=new JFrame("Combo ex");
6.
7. String country[]={"India","Aus","U.S.A","England","Newzeland"};
8.
9. JComboBox cb=new JComboBox(country);
10. cb.setBounds(50, 50,90,20);
11. f.add(cb);
12.
13. f.setLayout(null);
14. f.setSize(400,500);
15. f.setVisible(true);
16.
17. }
18. public static void main(String[] args) {
19. new Combo();
20.
21. }
22. }
1. import javax.swing.*;
2. public class MyTable {
3. JFrame f;
4. MyTable(){
5. f=new JFrame();
6.
7. String data[][]={ {"101","Amit","670000"},
8. {"102","Jai","780000"},
9. {"101","Sachin","700000"}};
10. String column[]={"ID","NAME","SALARY"};
11.
12. JTable jt=new JTable(data,column);
13. jt.setBounds(30,40,200,300);
14.
15. JScrollPane sp=new JScrollPane(jt);
16. f.add(sp);
17.
18. f.setSize(300,400);
19. // f.setLayout(null);
20. f.setVisible(true);
21. }
22. public static void main(String[] args) {
23. new MyTable();
24. }
25. }
JColorChooser class:
The JColorChooser class is used to create a color chooser dialog box so that user can select any
color.
1. import java.awt.event.*;
2. import java.awt.*;
3. import javax.swing.*;
4.
5. public class JColorChooserExample extends JFrame implements ActionListener{
6. JButton b;
7. Container c;
8.
9. JColorChooserExample(){
10. c=getContentPane();
11. c.setLayout(new FlowLayout());
12.
13. b=new JButton("color");
14. b.addActionListener(this);
15.
16. c.add(b);
17. }
18.
19. public void actionPerformed(ActionEvent e) {
20. Color initialcolor=Color.RED;
21. Color color=JColorChooser.showDialog(this,"Select a color",initialcolor);
22. c.setBackground(color);
23. }
24.
25. public static void main(String[] args) {
26. JColorChooserExample ch=new JColorChooserExample();
27. ch.setSize(400,400);
28. ch.setVisible(true);
29. ch.setDefaultCloseOperation(EXIT_ON_CLOSE);
30. }
31. }
JProgressBar class:
The JProgressBar class is used to display the progress of the task.
1. import javax.swing.*;
2. public class MyProgress extends JFrame{
3. JProgressBar jb;
4. int i=0,num=0;
5.
6. MyProgress(){
7. jb=new JProgressBar(0,2000);
8. jb.setBounds(40,40,200,30);
9.
10. jb.setValue(0);
11. jb.setStringPainted(true);
12.
13. add(jb);
14. setSize(400,400);
15. setLayout(null);
16. }
17.
18. public void iterate(){
19. while(i<=2000){
20. jb.setValue(i);
21. i=i+20;
22. try{Thread.sleep(150);}catch(Exception e){}
23. }
24. }
25. public static void main(String[] args) {
26. MyProgress m=new MyProgress();
27. m.setVisible(true);
28. m.iterate();
29. }
30. }
JSlider class:
The JSlider is used to create the slider. By using JSlider a user can select a value from a specific
range.
● JSlider(): creates a slider with the initial value of 50 and range of 0 to 100.
● JSlider(int orientation): creates a slider with the specified orientation set by either
JSlider.HORIZONTAL or JSlider.VERTICAL with the range 0 to 100 and initial value 50.
● JSlider(int min, int max): creates a horizontal slider using the given min and max.
● JSlider(int min, int max, int value): creates a horizontal slider using the given min, max
and value.
● JSlider(int orientation, int min, int max, int value): creates a slider using the given
orientation, min, max and value.
1. import javax.swing.*;
2.
3. public class SliderExample1 extends JFrame{
4.
5. public SliderExample1() {
6. JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25);
7. JPanel panel=new JPanel();
8. panel.add(slider);
9.
10. add(panel);
11. }
12.
13. public static void main(String s[]) {
14. SliderExample1 frame=new SliderExample1();
15. frame.pack();
16. frame.setVisible(true);
17. }
18. }
Example of JSlider class that paints ticks:
1. import javax.swing.*;
2.
3. public class SliderExample extends JFrame{
4.
5. public SliderExample() {
6.
7. JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25);
8. slider.setMinorTickSpacing(2);
9. slider.setMajorTickSpacing(10);
10.
11. slider.setPaintTicks(true);
12. slider.setPaintLabels(true);
13.
14. JPanel panel=new JPanel();
15. panel.add(slider);
16. add(panel);
17. }
18.
19. public static void main(String s[]) {
20. SliderExample frame=new SliderExample();
21. frame.pack();
22. frame.setVisible(true);
23.
24. }
25. }
Example of digital clock in swing:
1. import javax.swing.*;
2. import java.awt.*;
3. import java.text.*;
4. import java.util.*;
5. public class DigitalWatch implements Runnable{
6. JFrame f;
7. Thread t=null;
8. int hours=0, minutes=0, seconds=0;
9. String timeString = "";
10. JButton b;
11.
12. DigitalWatch(){
13. f=new JFrame();
14.
15. t = new Thread(this);
16. t.start();
17.
18. b=new JButton();
19. b.setBounds(100,100,100,50);
20.
21. f.add(b);
22. f.setSize(300,400);
23. f.setLayout(null);
24. f.setVisible(true);
25. }
26.
27. public void run() {
28. try {
29. while (true) {
30.
31. Calendar cal = Calendar.getInstance();
32. hours = cal.get( Calendar.HOUR_OF_DAY );
33. if ( hours > 12 ) hours -= 12;
34. minutes = cal.get( Calendar.MINUTE );
35. seconds = cal.get( Calendar.SECOND );
36.
37. SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");
38. Date date = cal.getTime();
39. timeString = formatter.format( date );
40.
41. printTime();
42.
43. t.sleep( 1000 ); // interval given in milliseconds
44. }
45. }
46. catch (Exception e) { }
47. }
48.
49. public void printTime(){
50. b.setText(timeString);
51. }
52.
53. public static void main(String[] args) {
54. new DigitalWatch();
55.
56.
57. }
58. }
1. import java.awt.*;
2. import javax.swing.JFrame;
3.
4. public class DisplayGraphics extends Canvas{
5.
6. public void paint(Graphics g) {
7. g.drawString("Hello",40,40);
8. setBackground(Color.WHITE);
9. g.fillRect(130, 30,100, 80);
10. g.drawOval(30,130,50, 60);
11. setForeground(Color.RED);
12. g.fillOval(130,130,50, 60);
13. g.drawArc(30, 200, 40,50,90,60);
14. g.fillArc(30, 130, 40,50,180,40);
15.
16. }
17. public static void main(String[] args) {
18. DisplayGraphics m=new DisplayGraphics();
19. JFrame f=new JFrame();
20. f.add(m);
21. f.setSize(400,400);
22. //f.setLayout(null);
23. f.setVisible(true);
24. }
25.
26. }
1. import java.awt.*;
2. import javax.swing.JFrame;
3.
4. public class MyCanvas extends Canvas{
5.
6. public void paint(Graphics g) {
7.
8. Toolkit t=Toolkit.getDefaultToolkit();
9. Image i=t.getImage("p3.gif");
10. g.drawImage(i, 120,100,this);
11.
12. }
13. public static void main(String[] args) {
14. MyCanvas m=new MyCanvas();
15. JFrame f=new JFrame();
16. f.add(m);
17. f.setSize(400,400);
18. f.setVisible(true);
19. }
20.
21. }
1. import java.io.*;
2. import java.util.Date;
3. import java.awt.*;
4. import java.awt.event.*;
5. import javax.swing.*;
6. import javax.swing.event.*;
7.
8. /************************************/
9. class FileOperation
10. {
11. Notepad npd;
12.
13. boolean saved;
14. boolean newFileFlag;
15. String fileName;
16. String applicationTitle="Notepad - Java";
17.
18. File fileRef;
19. JFileChooser chooser;
20. /////////////////////////////
21. boolean isSave(){return saved;}
22. void setSave(boolean saved){this.saved=saved;}
23. String getFileName(){return new String(fileName);}
24. void setFileName(String fileName){this.fileName=new String(fileName);}
25. /////////////////////////
26. FileOperation(Notepad npd)
27. {
28. this.npd=npd;
29.
30. saved=true;
31. newFileFlag=true;
32. fileName=new String("Untitled");
33. fileRef=new File(fileName);
34. this.npd.f.setTitle(fileName+" - "+applicationTitle);
35.
36. chooser=new JFileChooser();
37. chooser.addChoosableFileFilter(new MyFileFilter(".java","Java Source Files(*.java)"));
38. chooser.addChoosableFileFilter(new MyFileFilter(".txt","Text Files(*.txt)"));
39. chooser.setCurrentDirectory(new File("."));
40.
41. }
42. //////////////////////////////////////
43.
44. boolean saveFile(File temp)
45. {
46. FileWriter fout=null;
47. try
48. {
49. fout=new FileWriter(temp);
50. fout.write(npd.ta.getText());
51. }
52. catch(IOException ioe){updateStatus(temp,false);return false;}
53. finally
54. {try{fout.close();}catch(IOException excp){}}
55. updateStatus(temp,true);
56. return true;
57. }
58. ////////////////////////
59. boolean saveThisFile()
60. {
61.
62. if(!newFileFlag)
63. {return saveFile(fileRef);}
64.
65. return saveAsFile();
66. }
67. ////////////////////////////////////
68. boolean saveAsFile()
69. {
70. File temp=null;
71. chooser.setDialogTitle("Save As...");
72. chooser.setApproveButtonText("Save Now");
73. chooser.setApproveButtonMnemonic(KeyEvent.VK_S);
74. chooser.setApproveButtonToolTipText("Click me to save!");
75.
76. do
77. {
78. if(chooser.showSaveDialog(this.npd.f)!=JFileChooser.APPROVE_OPTION)
79. return false;
80. temp=chooser.getSelectedFile();
81. if(!temp.exists()) break;
82. if( JOptionPane.showConfirmDialog(
83. this.npd.f,"<html>"+temp.getPath()+" already exists.<br>Do you want to replace it?<h
tml>",
84. "Save As",JOptionPane.YES_NO_OPTION
85. )==JOptionPane.YES_OPTION)
86. break;
87. }while(true);
88.
89.
90. return saveFile(temp);
91. }
92.
93. ////////////////////////
94. boolean openFile(File temp)
95. {
96. FileInputStream fin=null;
97. BufferedReader din=null;
98.
99. try
100. {
101. fin=new FileInputStream(temp);
102. din=new BufferedReader(new InputStreamReader(fin));
103. String str=" ";
104. while(str!=null)
105. {
106. str=din.readLine();
107. if(str==null)
108. break;
109. this.npd.ta.append(str+"\n");
110. }
111.
112. }
113. catch(IOException ioe){updateStatus(temp,false);return false;}
114. finally
115. {try{din.close();fin.close();}catch(IOException excp){}}
116. updateStatus(temp,true);
117. this.npd.ta.setCaretPosition(0);
118. return true;
119. }
120. ///////////////////////
121. void openFile()
122. {
123. if(!confirmSave()) return;
124. chooser.setDialogTitle("Open File...");
125. chooser.setApproveButtonText("Open this");
126. chooser.setApproveButtonMnemonic(KeyEvent.VK_O);
127. chooser.setApproveButtonToolTipText("Click me to open the selected file.!");
128.
129. File temp=null;
130. do
131. {
132. if(chooser.showOpenDialog(this.npd.f)!=JFileChooser.APPROVE_OPTION)
133. return;
134. temp=chooser.getSelectedFile();
135.
136. if(temp.exists()) break;
137.
138. JOptionPane.showMessageDialog(this.npd.f,
139. "<html>"+temp.getName()+"<br>file not found.<br>"+
140. "Please verify the correct file name was given.<html>",
141. "Open", JOptionPane.INFORMATION_MESSAGE);
142.
143. } while(true);
144.
145. this.npd.ta.setText("");
146.
147. if(!openFile(temp))
148. {
149. fileName="Untitled"; saved=true;
150. this.npd.f.setTitle(fileName+" - "+applicationTitle);
151. }
152. if(!temp.canWrite())
153. newFileFlag=true;
154.
155. }
156. ////////////////////////
157. void updateStatus(File temp,boolean saved)
158. {
159. if(saved)
160. {
161. this.saved=true;
162. fileName=new String(temp.getName());
163. if(!temp.canWrite())
164. {fileName+="(Read only)"; newFileFlag=true;}
165. fileRef=temp;
166. npd.f.setTitle(fileName + " - "+applicationTitle);
167. npd.statusBar.setText("File : "+temp.getPath()+" saved/opened successfully.");
168. newFileFlag=false;
169. }
170. else
171. {
172. npd.statusBar.setText("Failed to save/open : "+temp.getPath());
173. }
174. }
175. ///////////////////////
176. boolean confirmSave()
177. {
178. String strMsg="<html>The text in the "+fileName+" file has been changed.<br>"+
526. temp.setEnabled(false);
527. editMenu.addSeparator();
528. cutItem=createMenuItem(editCut,KeyEvent.VK_T,editMenu,KeyEvent.VK_X,this)
;
529. copyItem=createMenuItem(editCopy,KeyEvent.VK_C,editMenu,KeyEvent.VK_C,t
his);
530. createMenuItem(editPaste,KeyEvent.VK_P,editMenu,KeyEvent.VK_V,this);
531. deleteItem=createMenuItem(editDelete,KeyEvent.VK_L,editMenu,this);
532. deleteItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE,0));
533. editMenu.addSeparator();
534. findItem=createMenuItem(editFind,KeyEvent.VK_F,editMenu,KeyEvent.VK_F,thi
s);
535. findNextItem=createMenuItem(editFindNext,KeyEvent.VK_N,editMenu,this);
536. findNextItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3,0));
537. replaceItem=createMenuItem(editReplace,KeyEvent.VK_R,editMenu,KeyEvent.V
K_H,this);
538. gotoItem=createMenuItem(editGoTo,KeyEvent.VK_G,editMenu,KeyEvent.VK_G,t
his);
539. editMenu.addSeparator();
540. selectAllItem=createMenuItem(editSelectAll,KeyEvent.VK_A,editMenu,KeyEvent.
VK_A,this);
541. createMenuItem(editTimeDate,KeyEvent.VK_D,editMenu,this)
542. .setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5,0));
543.
544. createCheckBoxMenuItem(formatWordWrap,KeyEvent.VK_W,formatMenu,this);
545.
546. createMenuItem(formatFont,KeyEvent.VK_F,formatMenu,this);
547. formatMenu.addSeparator();
548. createMenuItem(formatForeground,KeyEvent.VK_T,formatMenu,this);
549. createMenuItem(formatBackground,KeyEvent.VK_P,formatMenu,this);
550.
551. createCheckBoxMenuItem(viewStatusBar,KeyEvent.VK_S,viewMenu,this).setSele
cted(true);
552. /************For Look and Feel***/
553. LookAndFeelMenu.createLookAndFeelMenuItem(viewMenu,this.f);
554.
555.
556. temp=createMenuItem(helpHelpTopic,KeyEvent.VK_H,helpMenu,this);
557. temp.setEnabled(false);
558. helpMenu.addSeparator();
559. createMenuItem(helpAboutNotepad,KeyEvent.VK_A,helpMenu,this);
560.
561. MenuListener editMenuListener=new MenuListener()
562. {
563. public void menuSelected(MenuEvent evvvv)
564. {
565. if(Notepad.this.ta.getText().length()==0)
566. {
567. findItem.setEnabled(false);
568. findNextItem.setEnabled(false);
569. replaceItem.setEnabled(false);
570. selectAllItem.setEnabled(false);
571. gotoItem.setEnabled(false);
572. }
573. else
574. {
575. findItem.setEnabled(true);
576. findNextItem.setEnabled(true);
577. replaceItem.setEnabled(true);
578. selectAllItem.setEnabled(true);
579. gotoItem.setEnabled(true);
580. }
581. if(Notepad.this.ta.getSelectionStart()==ta.getSelectionEnd())
582. {
583. cutItem.setEnabled(false);
584. copyItem.setEnabled(false);
585. deleteItem.setEnabled(false);
586. }
587. else
588. {
589. cutItem.setEnabled(true);
590. copyItem.setEnabled(true);
591. deleteItem.setEnabled(true);
592. }
593. }
594. public void menuDeselected(MenuEvent evvvv){}
595. public void menuCanceled(MenuEvent evvvv){}
596. };
597. editMenu.addMenuListener(editMenuListener);
598. f.setJMenuBar(mb);
599. }
600. /*************Constructor**************/
601. ////////////////////////////////////
602. public static void main(String[] s)
603. {
604. new Notepad();
605. }
606. }
607. /**************************************/
608. //public
609. interface MenuConstants
610. {
611. final String fileText="File";
612. final String editText="Edit";
613. final String formatText="Format";
614. final String viewText="View";
615. final String helpText="Help";
616.
617. final String fileNew="New";
618. final String fileOpen="Open...";
619. final String fileSave="Save";
620. final String fileSaveAs="Save As...";
621. final String filePageSetup="Page Setup...";
622. final String filePrint="Print";
623. final String fileExit="Exit";
624.
625. final String editUndo="Undo";
626. final String editCut="Cut";
627. final String editCopy="Copy";
628. final String editPaste="Paste";
629. final String editDelete="Delete";
630. final String editFind="Find...";
631. final String editFindNext="Find Next";
632. final String editReplace="Replace";
633. final String editGoTo="Go To...";
634. final String editSelectAll="Select All";
635. final String editTimeDate="Time/Date";
636.
637. final String formatWordWrap="Word Wrap";
638. final String formatFont="Font...";
639. final String formatForeground="Set Text color...";
640. final String formatBackground="Set Pad color...";
641.
642. final String viewStatusBar="Status Bar";
643.
644. final String helpHelpTopic="Help Topic";
645. final String helpAboutNotepad="About Javapad";
646.
647. final String aboutText="Your Javapad";
648. }
1. /*********************************************
2. Save this file as MyCalculator.java
3. to compile it use
4. javac MyCalculator.java
5. to use the calcuator do this
6. java MyCalculator
7.
8. **********************************************/
9. import java.awt.*;
10. import java.awt.event.*;
11. /*********************************************/
12.
13. public class MyCalculator extends Frame
14. {
15.
16. public boolean setClear=true;
17. double number, memValue;
18. char op;
19.
20. String digitButtonText[] = {"7", "8", "9", "4", "5", "6", "1", "2", "3", "0", "+/-", "." };
21. String operatorButtonText[] = {"/", "sqrt", "*", "%", "-", "1/X", "+", "=" };
22. String memoryButtonText[] = {"MC", "MR", "MS", "M+" };
23. String specialButtonText[] = {"Backspc", "C", "CE" };
24.
25. MyDigitButton digitButton[]=new MyDigitButton[digitButtonText.length];
26. MyOperatorButton operatorButton[]=new MyOperatorButton[operatorButtonText.leng
th];
27. MyMemoryButton memoryButton[]=new MyMemoryButton[memoryButtonText.length
];
28. MySpecialButton specialButton[]=new MySpecialButton[specialButtonText.length];
29.
30. Label displayLabel=new Label("0",Label.RIGHT);
31. Label memLabel=new Label(" ",Label.RIGHT);
32.
33. final int FRAME_WIDTH=325,FRAME_HEIGHT=325;
34. final int HEIGHT=30, WIDTH=30, H_SPACE=10,V_SPACE=10;
35. final int TOPX=30, TOPY=50;
36. ///////////////////////////
37. MyCalculator(String frameText)//constructor
38. {
39. super(frameText);
40.
41. int tempX=TOPX, y=TOPY;
42. displayLabel.setBounds(tempX,y,240,HEIGHT);
43. displayLabel.setBackground(Color.BLUE);
44. displayLabel.setForeground(Color.WHITE);
45. add(displayLabel);
46.
47. memLabel.setBounds(TOPX, TOPY+HEIGHT+ V_SPACE,WIDTH, HEIGHT);
48. add(memLabel);
49.
50. // set Co-ordinates for Memory Buttons
51. tempX=TOPX;
52. y=TOPY+2*(HEIGHT+V_SPACE);
53. for(int i=0; i<memoryButton.length; i++)
54. {
55. memoryButton[i]=new MyMemoryButton(tempX,y,WIDTH,HEIGHT,memoryButtonText[
i], this);
56. memoryButton[i].setForeground(Color.RED);
57. y+=HEIGHT+V_SPACE;
58. }
59.
60. //set Co-ordinates for Special Buttons
61. tempX=TOPX+1*(WIDTH+H_SPACE); y=TOPY+1*(HEIGHT+V_SPACE);
62. for(int i=0;i<specialButton.length;i++)
63. {
64. specialButton[i]=new MySpecialButton(tempX,y,WIDTH*2,HEIGHT,specialButtonText[i],
this);
65. specialButton[i].setForeground(Color.RED);
66. tempX=tempX+2*WIDTH+H_SPACE;
67. }
68.
69. //set Co-ordinates for Digit Buttons
70. int digitX=TOPX+WIDTH+H_SPACE;
71. int digitY=TOPY+2*(HEIGHT+V_SPACE);
72. tempX=digitX; y=digitY;
73. for(int i=0;i<digitButton.length;i++)
74. {
75. digitButton[i]=new MyDigitButton(tempX,y,WIDTH,HEIGHT,digitButtonText[i], this);
76. digitButton[i].setForeground(Color.BLUE);
77. tempX+=WIDTH+H_SPACE;
78. if((i+1)%3==0){tempX=digitX; y+=HEIGHT+V_SPACE;}
79. }
80.
81. //set Co-ordinates for Operator Buttons
82. int opsX=digitX+2*(WIDTH+H_SPACE)+H_SPACE;
83. int opsY=digitY;
84. tempX=opsX; y=opsY;
85. for(int i=0;i<operatorButton.length;i++)
86. {
87. tempX+=WIDTH+H_SPACE;
88. operatorButton[i]=new MyOperatorButton(tempX,y,WIDTH,HEIGHT,operatorButtonTex
t[i], this);
89. operatorButton[i].setForeground(Color.RED);
90. if((i+1)%2==0){tempX=opsX; y+=HEIGHT+V_SPACE;}
91. }
92.
93. addWindowListener(new WindowAdapter()
94. {
95. public void windowClosing(WindowEvent ev)
96. {System.exit(0);}
97. });
98.
99. setLayout(null);
100. setSize(FRAME_WIDTH,FRAME_HEIGHT);
101. setVisible(true);
102. }
103. //////////////////////////////////
104. static String getFormattedText(double temp)
105. {
106. String resText=""+temp;
107. if(resText.lastIndexOf(".0")>0)
108. resText=resText.substring(0,resText.length()-2);
109. return resText;
110. }
111. ////////////////////////////////////////
112. public static void main(String []args)
113. {
114. new MyCalculator("Calculator - Java");
115. }
116. }
117.
118. /*******************************************/
119.
120. class MyDigitButton extends Button implements ActionListener
121. {
122. MyCalculator cl;
123.
124. //////////////////////////////////////////
125. MyDigitButton(int x,int y, int width,int height,String cap, MyCalculator clc)
126. {
127. super(cap);
128. setBounds(x,y,width,height);
129. this.cl=clc;
130. this.cl.add(this);
131. addActionListener(this);
132. }
133. ////////////////////////////////////////////////
134. static boolean isInString(String s, char ch)
135. {
136. for(int i=0; i<s.length();i++) if(s.charAt(i)==ch) return true;
137. return false;
138. }
139. /////////////////////////////////////////////////
140. public void actionPerformed(ActionEvent ev)
141. {
142. String tempText=((MyDigitButton)ev.getSource()).getLabel();
143.
144. if(tempText.equals("."))
145. {
146. if(cl.setClear)
147. {cl.displayLabel.setText("0.");cl.setClear=false;}
148. else if(!isInString(cl.displayLabel.getText(),'.'))
149. cl.displayLabel.setText(cl.displayLabel.getText()+".");
150. return;
151. }
152.
153. int index=0;
154. try{
155. index=Integer.parseInt(tempText);
156. }catch(NumberFormatException e){return;}
157.
158. if (index==0 && cl.displayLabel.getText().equals("0")) return;
159.
160. if(cl.setClear)
161. {cl.displayLabel.setText(""+index);cl.setClear=false;}
162. else
163. cl.displayLabel.setText(cl.displayLabel.getText()+index);
164. }//actionPerformed
165. }//class defination
166.
167. /********************************************/
168.
169. class MyOperatorButton extends Button implements ActionListener
170. {
171. MyCalculator cl;
172.
173. MyOperatorButton(int x,int y, int width,int height,String cap, MyCalculator clc)
174. {
175. super(cap);
176. setBounds(x,y,width,height);
177. this.cl=clc;
178. this.cl.add(this);
179. addActionListener(this);
180. }
181. ///////////////////////
182. public void actionPerformed(ActionEvent ev)
183. {
184. String opText=((MyOperatorButton)ev.getSource()).getLabel();
185.
186. cl.setClear=true;
187. double temp=Double.parseDouble(cl.displayLabel.getText());
188.
189. if(opText.equals("1/x"))
190. {
191. try
192. {double tempd=1/(double)temp;
193. cl.displayLabel.setText(MyCalculator.getFormattedText(tempd));}
194. catch(ArithmeticException excp)
195. {cl.displayLabel.setText("Divide by 0.");}
196. return;
197. }
198. if(opText.equals("sqrt"))
199. {
200. try
201. {double tempd=Math.sqrt(temp);
202. cl.displayLabel.setText(MyCalculator.getFormattedText(tempd));}
203. catch(ArithmeticException excp)
204. {cl.displayLabel.setText("Divide by 0.");}
205. return;
206. }
207. if(!opText.equals("="))
208. {
209. cl.number=temp;
210. cl.op=opText.charAt(0);
211. return;
212. }
213. // process = button pressed
214. switch(cl.op)
215. {
216. case '+':
217. temp+=cl.number;break;
218. case '-':
219. temp=cl.number-temp;break;
220. case '*':
221. temp*=cl.number;break;
222. case '%':
223. try{temp=cl.number%temp;}
224. catch(ArithmeticException excp)
225. {cl.displayLabel.setText("Divide by 0."); return;}
226. break;
227. case '/':
228. try{temp=cl.number/temp;}
229. catch(ArithmeticException excp)
230. {cl.displayLabel.setText("Divide by 0."); return;}
231. break;
232. }//switch
233.
234. cl.displayLabel.setText(MyCalculator.getFormattedText(temp));
235. //cl.number=temp;
236. }//actionPerformed
237. }//class
238.
239. /****************************************/
240.
241. class MyMemoryButton extends Button implements ActionListener
242. {
243. MyCalculator cl;
244.
245. /////////////////////////////////
246. MyMemoryButton(int x,int y, int width,int height,String cap, MyCalculator clc)
247. {
248. super(cap);
249. setBounds(x,y,width,height);
250. this.cl=clc;
251. this.cl.add(this);
252. addActionListener(this);
253. }
254. ////////////////////////////////////////////////
255. public void actionPerformed(ActionEvent ev)
256. {
257. char memop=((MyMemoryButton)ev.getSource()).getLabel().charAt(1);
258.
259. cl.setClear=true;
260. double temp=Double.parseDouble(cl.displayLabel.getText());
261.
262. switch(memop)
263. {
264. case 'C':
265. cl.memLabel.setText(" ");cl.memValue=0.0;break;
266. case 'R':
267. cl.displayLabel.setText(MyCalculator.getFormattedText(cl.memValue));break;
268. case 'S':
269. cl.memValue=0.0;
270. case '+':
271. cl.memValue+=Double.parseDouble(cl.displayLabel.getText());
272. if(cl.displayLabel.getText().equals("0") || cl.displayLabel.getText().equals("0.0"
) )
273. cl.memLabel.setText(" ");
274. else
275. cl.memLabel.setText("M");
276. break;
277. }//switch
278. }//actionPerformed
279. }//class
280.
281. /*****************************************/
282.
283. class MySpecialButton extends Button implements ActionListener
284. {
285. MyCalculator cl;
286.
287. MySpecialButton(int x,int y, int width,int height,String cap, MyCalculator clc)
288. {
289. super(cap);
290. setBounds(x,y,width,height);
291. this.cl=clc;
292. this.cl.add(this);
293. addActionListener(this);
294. }
295. //////////////////////
296. static String backSpace(String s)
297. {
298. String Res="";
299. for(int i=0; i<s.length()-1; i++) Res+=s.charAt(i);
300. return Res;
301. }
302.
303. //////////////////////////////////////////////////////////
304. public void actionPerformed(ActionEvent ev)
305. {
306. String opText=((MySpecialButton)ev.getSource()).getLabel();
307. //check for backspace button
308. if(opText.equals("Backspc"))
309. {
310. String tempText=backSpace(cl.displayLabel.getText());
311. if(tempText.equals(""))
312. cl.displayLabel.setText("0");
313. else
314. cl.displayLabel.setText(tempText);
315. return;
316. }
317. //check for "C" button i.e. Reset
318. if(opText.equals("C"))
319. {
320. cl.number=0.0; cl.op=' '; cl.memValue=0.0;
321. cl.memLabel.setText(" ");
322. }
323.
324. //it must be CE button pressed
325. cl.displayLabel.setText("0");cl.setClear=true;
326. }//actionPerformed
327. }//class
328.
329. /*********************************************
330. Features not implemented and few bugs
331.
332. i) No coding done for "+/-" button.
333. ii) Menubar is not included.
334. iii)Not for Scientific calculation
335. iv)Some of the computation may lead to unexpected result
336. due to the representation of Floating point numbers in computer
337. is an approximation to the given value that can be stored
338. physically in memory.
339. ***********************************************/
1. String url="www.java.com";
2. InetAddress ia=InetAddress.getByName(url);
3. String ip=ia.getHostAddress();
1. import javax.swing.*;
2. import java.awt.event.*;
3. import java.net.*;
4. public class IPFinder extends JFrame implements ActionListener{
5. JLabel l;
6. JTextField tf;
7. JButton b;
8. IPFinder(){
9. super("IP Finder Tool - Java");
10. l=new JLabel("Enter URL:");
11. l.setBounds(50,70,150,20);;
12. tf=new JTextField();
13. tf.setBounds(50,100,200,20);
14.
15. b=new JButton("Find IP");
16. b.setBounds(50,150,80,30);
17. b.addActionListener(this);
18. add(l);
19. add(tf);
20. add(b);
21. setSize(300,300);
22. setLayout(null);
23. setVisible(true);
24. }
25. public void actionPerformed(ActionEvent e){
26. String url=tf.getText();
27. try {
28. InetAddress ia=InetAddress.getByName(url);
29. String ip=ia.getHostAddress();
30. JOptionPane.showMessageDialog(this,ip);
31. } catch (UnknownHostException e1) {
32. JOptionPane.showMessageDialog(this,e1.toString());
33. }
34. }
35. public static void main(String[] args) {
36. new IPFinder();
37. }
38. }
1. import java.awt.event.*;
2. import javax.swing.*;
3. public class WCC extends JFrame implements ActionListener{
4. JTextArea ta;
5. JButton b1,b2;
6. WCC(){
7. super("Word Character Counter - Java");
8. ta=new JTextArea();
9. ta.setBounds(50,50,300,200);
10.
11. b1=new JButton("Word");
12. b1.setBounds(50,300,100,30);
13.
14. b2=new JButton("Character");
15. b2.setBounds(180,300,100,30);
16.
17. b1.addActionListener(this);
18. b2.addActionListener(this);
19. add(b1);add(b2);add(ta);
20. setSize(400,400);
21. setLayout(null);
22. setVisible(true);
23. }
24. public void actionPerformed(ActionEvent e){
25. String text=ta.getText();
26. if(e.getSource()==b1){
27. String words[]=text.split("\\s");
28. JOptionPane.showMessageDialog(this,"Total words: "+words.length);
29. }
30. if(e.getSource()==b2){
31. JOptionPane.showMessageDialog(this,"Total Characters with space: "+text.length())
;
32. }
33. }
34. public static void main(String[] args) {
35. new WCC();
36. }
37. }
1. import java.awt.*;
2. import java.awt.event.*;
3. import java.io.InputStream;
4. import java.net.*;
5. public class SourceGetter extends Frame implements ActionListener{
6. TextField tf;
7. TextArea ta;
8. Button b;
9. Label l;
10. SourceGetter(){
11. super("Source Getter Tool - Java");
12. l=new Label("Enter URL:");
13. l.setBounds(50,50,50,20);
14.
15. tf=new TextField();
16. tf.setBounds(120,50,250,20);
17.
18. b=new Button("Get Source Code");
19. b.setBounds(120, 100,120,30);
20. b.addActionListener(this);
21.
22. ta=new TextArea();
23. ta.setBounds(120,150,250,150);
24.
25. add(l);add(tf);add(b);add(ta);
26. setSize(400,400);
27. setLayout(null);
28. setVisible(true);
29. }
30. public void actionPerformed(ActionEvent e){
31. String s=tf.getText();
32. if(s==null){}
33. else{
34. try{
35. URL u=new URL(s);
36. URLConnection uc=u.openConnection();
37.
38. InputStream is=uc.getInputStream();
39. int i;
40. StringBuilder sb=new StringBuilder();
41. while((i=is.read())!=-1){
42. sb.append((char)i);
43. }
44. String source=sb.toString();
45. ta.setText(source);
46. }catch(Exception ex){System.out.println(e);}
47. }
48. }
49. public static void main(String[] args) {
50. new SourceGetter();
51. }
52. }
1. import java.io.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. import javax.swing.*;
5. import javax.swing.tree.*;
6. /***********************************/
7. class Explorer extends JPanel implements ActionListener
8. {
9. JTextField jtf;
10. JTextArea jta;
11. JTree tree;
12. JButton refresh;
13. JTable jtb;
14. JScrollPane jsp;
15. JScrollPane jspTable;
16.
17. String currDirectory=null;
18.
19. final String[] colHeads={"File Name","SIZE(in Bytes)","Read Only","Hidden"};
20. String[][]data={{"","","","",""}};
21.
22. /////////////////////////////////
23. Explorer(String path)
24. {
25.
26. jtf=new JTextField();
27. jta=new JTextArea(5,30);
28. refresh=new JButton("Refresh");
29.
30. File temp=new File(path);
31. DefaultMutableTreeNode top=createTree(temp);
32.
33. //if(top!=null)
34.
35. tree=new JTree(top);
36.
37. jsp=new JScrollPane(tree);
38.
39. final String[] colHeads={"File Name","SIZE(in Bytes)","Read Only","Hidden"};
40. String[][]data={{"","","","",""}};
41. jtb=new JTable(data, colHeads);
42. jspTable=new JScrollPane(jtb);
43.
44. setLayout(new BorderLayout());
45. add(jtf,BorderLayout.NORTH);
46. add(jsp,BorderLayout.WEST);
47. add(jspTable,BorderLayout.CENTER);
48. add(refresh,BorderLayout.SOUTH);
49.
50. tree.addMouseListener(
51. new MouseAdapter()
52. {
53. public void mouseClicked(MouseEvent me)
54. {
55. doMouseClicked(me);
56. }
57. });
58. jtf.addActionListener(this);
59. refresh.addActionListener(this);
60. }
61. ///////////////////////////////
62. public void actionPerformed(ActionEvent ev)
63. {
64. File temp=new File(jtf.getText());
65. DefaultMutableTreeNode newtop=createTree(temp);
66. if(newtop!=null)
67. tree=new JTree(newtop);
68. remove(jsp);
69. jsp=new JScrollPane(tree);
70. setVisible(false);
71. add(jsp,BorderLayout.WEST);
72. tree.addMouseListener(
73. new MouseAdapter()
74. {
75. public void mouseClicked(MouseEvent me)
76. {
77. doMouseClicked(me);
78. }
79. });
80.
81. setVisible(true);
82. }
83. //////////////////////////////
84.
85. DefaultMutableTreeNode createTree(File temp)
86. {
87. DefaultMutableTreeNode top=new DefaultMutableTreeNode(temp.getPath());
88. if(!(temp.exists() && temp.isDirectory()))
89. return top;
90.
91. fillTree(top,temp.getPath());
92.
93. return top;
94. }
95. //////////////////////////////
96. void fillTree(DefaultMutableTreeNode root, String filename)
97. {
98. File temp=new File(filename);
99.
100. if(!(temp.exists() && temp.isDirectory()))
101. return;
102. //System.out.println(filename);
103. File[] filelist=temp.listFiles();
104.
105. for(int i=0; i<filelist.length; i++)
106. {
107. if(!filelist[i].isDirectory())
108. continue;
109. final DefaultMutableTreeNode tempDmtn=new DefaultMutableTreeNode(filelist
[i].getName());
110. root.add(tempDmtn);
111. final String newfilename=new String(filename+"\\"+filelist[i].getName());
112. Thread t=new Thread()
113. {
114. public void run()
115. {
116. fillTree(tempDmtn,newfilename);
117. }//run
118. };//thread
119. if(t==null)
120. {System.out.println("no more thread allowed "+newfilename);return;}
121. t.start();
122. }//for
123. }//function
124. //////////////////////////////
125. void doMouseClicked(MouseEvent me)
126. {
127. TreePath tp=tree.getPathForLocation(me.getX(),me.getY());
128. if(tp==null) return;
129. //jtf.setText(tp.toString());
130. String s=tp.toString();
131. s=s.replace("[","");
132. s=s.replace("]","");
133. s=s.replace(", ","\\");
134. //s=s.replace(" ","");
135. //int z=s.lastIndexOf("\"\\\"");
136. //s="\'"+s; s=s+"\'";
137. jtf.setText(s);
138. showFiles(s);
139. //java.util.StringTokenizer st=new java.util.StringTokenizer(s,",");
140. //jtf.setText(jtf.getText()+"="+s);
141.
142. }
143. ////////////////////////////////
144. void showFiles(String filename)
145. {
146. File temp=new File(filename);
147. data=new String[][]{{"","","",""}};
148. remove(jspTable);
149. jtb=new JTable(data, colHeads);
150. jspTable=new JScrollPane(jtb);
151. setVisible(false);
152. add(jspTable,BorderLayout.CENTER);
153. setVisible(true);
154.
155. if(!temp.exists()) return;
156. if(!temp.isDirectory()) return;
157.
158. //System.out.println(filename);
159. File[] filelist=temp.listFiles();
160. int fileCounter=0;
161. data=new String[filelist.length][4];
162. for(int i=0; i<filelist.length; i++)
163. {
164. if(filelist[i].isDirectory())
165. continue;
166. data[fileCounter][0]=new String(filelist[i].getName());
167. data[fileCounter][1]=new String(filelist[i].length()+"");
168. data[fileCounter][2]=new String(!filelist[i].canWrite()+"");
169. data[fileCounter][3]=new String(filelist[i].isHidden()+"");
170. fileCounter++;
171. }//for
172.
173. String dataTemp[][]=new String[fileCounter][4];
174. for(int k=0; k<fileCounter; k++)
175. dataTemp[k]=data[k];
176. data=dataTemp;
177.
178. //System.out.println(data);
179. remove(jspTable);
180. jtb=new JTable(data, colHeads);
181. jspTable=new JScrollPane(jtb);
182. setVisible(false);
183. add(jspTable,BorderLayout.CENTER);
184. setVisible(true);
185. }
186. ////////////////////////////////
187. ///////////////////////////////
188. }
189. /***********************************/
190. class ExplorerTest extends JFrame
191. {
192.
193. ExplorerTest(String path)
194. {
195. super("Windows Exploder - Java");
196. add(new Explorer(path),"Center");
197. setDefaultCloseOperation(EXIT_ON_CLOSE);
198. setSize(400,400);
199. setVisible(true);
200. }
201.
202. public static void main(String[] args)
203. {
204. new ExplorerTest(".");
205. }
206. }
207. /***********************************/
1. import java.awt.*;
2. import javax.swing.*;
3. import java.awt.event.*;
4. public class puzzle extends JFrame implements ActionListener{
5. JButton b1,b2,b3,b4,b5,b6,b7,b8,b9,next;
6. puzzle(){
7. super("Puzzle Game - Java");
8. b1=new JButton("1");
9. b2=new JButton(" ");
10. b3=new JButton("3");
11. b4=new JButton("4");
12. b5=new JButton("5");
13. b6=new JButton("6");
14. b7=new JButton("7");
15. b8=new JButton("8");
16. b9=new JButton("2");
17. next=new JButton("next");
18.
19. b1.setBounds(10,30,50,40);
20. b2.setBounds(70,30,50,40);
21. b3.setBounds(130,30,50,40);
22. b4.setBounds(10,80,50,40);
23. b5.setBounds(70,80,50,40);
24. b6.setBounds(130,80,50,40);
25. b7.setBounds(10,130,50,40);
26. b8.setBounds(70,130,50,40);
27. b9.setBounds(130,130,50,40);
28. next.setBounds(70,200,100,40);
29.
30. add(b1);add(b2);add(b3);add(b4);add(b5);add(b6);add(b7);add(b8);add(b9); add(next);
31. b1.addActionListener(this);
32. b2.addActionListener(this);
33. b3.addActionListener(this);
34. b4.addActionListener(this);
35. b5.addActionListener(this);
36. b6.addActionListener(this);
37. b7.addActionListener(this);
38. b8.addActionListener(this);
39. b9.addActionListener(this);
40. next.addActionListener(this);
41.
42. next.setBackground(Color.black);
43. next.setForeground(Color.green);
44. setSize(250,300);
45. setLayout(null);
46. setVisible(true);
47. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
48. }//end of constructor
49.
50. public void actionPerformed(ActionEvent e){
51. if(e.getSource()==next){
52. String s=b4.getLabel();
53. b4.setLabel(b9.getLabel());
54. b9.setLabel(s);
55. s=b1.getLabel();
56. b1.setLabel(b5.getLabel());
57. b5.setLabel(s);
58. s=b2.getLabel();
59. b2.setLabel(b7.getLabel());
60. b7.setLabel(s);
61. }
62. if(e.getSource()==b1){
63. String s=b1.getLabel();
64. if(b2.getLabel().equals(" ")){ b2.setLabel(s); b1.setLabel(" ");}
65. else if(b4.getLabel().equals(" ")){ b4.setLabel(s); b1.setLabel(" ");}
66. }//end of if
67.
68. if(e.getSource()==b3){
69. String s=b3.getLabel();
70. if(b2.getLabel().equals(" ")){ b2.setLabel(s); b3.setLabel(" ");}
71. else if(b6.getLabel().equals(" ")){ b6.setLabel(s); b3.setLabel(" ");}
72. }//end of if
73.
74. if(e.getSource()==b2){
75. String s=b2.getLabel();
76. if(b1.getLabel().equals(" ")){ b1.setLabel(s); b2.setLabel(" ");}
77. else if(b3.getLabel().equals(" ")){ b3.setLabel(s); b2.setLabel(" ");}
78. else if(b5.getLabel().equals(" ")){ b5.setLabel(s); b2.setLabel(" ");}
79. }//end of if
80.
81. if(e.getSource()==b4){
82. String s=b4.getLabel();
83. if(b1.getLabel().equals(" ")){ b1.setLabel(s); b4.setLabel(" ");}
84. else if(b7.getLabel().equals(" ")){ b7.setLabel(s); b4.setLabel(" ");}
85. else if(b5.getLabel().equals(" ")){ b5.setLabel(s); b4.setLabel(" ");}
86. }//end of if
87.
88. if(e.getSource()==b5){
89. String s=b5.getLabel();
90. if(b2.getLabel().equals(" ")){ b2.setLabel(s); b5.setLabel(" ");}
91. else if(b4.getLabel().equals(" ")){ b4.setLabel(s); b5.setLabel(" ");}
92. else if(b6.getLabel().equals(" ")){ b6.setLabel(s); b5.setLabel(" ");}
93. else if(b8.getLabel().equals(" ")){ b8.setLabel(s); b5.setLabel(" ");}
94. }//end of if
95.
96. if(e.getSource()==b6){
97.
98. String s=b6.getLabel();
99. if(b9.getLabel().equals(" ")){ b9.setLabel(s); b6.setLabel(" ");}
100. else if(b3.getLabel().equals(" ")){ b3.setLabel(s); b6.setLabel(" ");}
101. else if(b5.getLabel().equals(" ")){ b5.setLabel(s); b6.setLabel(" ");}
102.
103. }//end of if
104.
105. if(e.getSource()==b7){
106. String s=b7.getLabel();
107. if(b4.getLabel().equals(" ")){ b4.setLabel(s); b7.setLabel(" ");}
108. else if(b8.getLabel().equals(" ")){ b8.setLabel(s); b7.setLabel(" ");}
109.
110. }//end of if
111.
112. if(e.getSource()==b8){
113. String s=b8.getLabel();
114. if(b7.getLabel().equals(" ")){ b7.setLabel(s); b8.setLabel(" ");}
115. else if(b9.getLabel().equals(" ")){ b9.setLabel(s); b8.setLabel(" ");}
116. else if(b5.getLabel().equals(" ")){ b5.setLabel(s); b8.setLabel(" ");}
117.
118. }//end of if
119.
120. if(e.getSource()==b9){
121. String s=b9.getLabel();
122. if(b6.getLabel().equals(" ")){ b6.setLabel(s); b9.setLabel(" ");}
123. else if(b8.getLabel().equals(" ")){ b8.setLabel(s); b9.setLabel(" ");}
124. if(b1.getLabel().equals("1")&&b2.getLabel().equals("2")&&b3.getLabel()
125. .equals("3")&&b4.getLabel().equals("4")&&b5.getLabel().equals("5")
126. &&b6.getLabel().equals("6")&&b7.getLabel().equals("7")&&b8.getLabel()
127. .equals("8")&&b9.getLabel().equals(" ")){
128. JOptionPane.showMessageDialog(puzzle.this,"!!!you won!!!");
129. }
130. }//end of if
131.
132. }//end of actionPerformed
133.
134.
135. public static void main(String[] args){
136. new puzzle();
137. }//end of main
138.
139. }//end of class
Example of Pic Puzzle Game
1. import java.awt.event.*;
2. import java.awt.*;
3. import javax.swing.*;
4. class picpuzzle2 extends JFrame implements ActionListener{
5. JButton b1,b2,b3,b4,b5,b6,b7,b8,b9,sample,starB;
6. Icon star;
7. Icon ic0=new ImageIcon("pic/starB0.jpg");
8. Icon ic10=new ImageIcon("pic/starB10.jpg");
9. Icon ic20=new ImageIcon("pic/starB20.jpg");
10. Icon samicon1=new ImageIcon("pic/main.jpg");
11. Icon samicon2=new ImageIcon("pic/main2.jpg");
12. Icon samicon3=new ImageIcon("pic/main3.jpg");
13. Icon ic1=new ImageIcon("pic/1.jpg");
14. Icon ic2=new ImageIcon("pic/5.jpg");
15. Icon ic3=new ImageIcon("pic/2.jpg");
16. Icon ic4=new ImageIcon("pic/7.jpg");
17. Icon ic5=new ImageIcon("pic/4.jpg");
18. Icon ic6=new ImageIcon("pic/6.jpg");
19. Icon ic7=new ImageIcon("pic/8.jpg");
20. Icon ic8=new ImageIcon("pic/9.jpg");
21. Icon ic9=new ImageIcon("pic/3.jpg");
22.
23. Icon ic11=new ImageIcon("pic/12.jpg");
24. Icon ic12=new ImageIcon("pic/13.jpg");
25. Icon ic13=new ImageIcon("pic/16.jpg");
26. Icon ic14=new ImageIcon("pic/11.jpg");
27. Icon ic15=new ImageIcon("pic/14.jpg");
28. Icon ic16=new ImageIcon("pic/19.jpg");
29. Icon ic17=new ImageIcon("pic/17.jpg");
30. Icon ic18=new ImageIcon("pic/15.jpg");
31. Icon ic19=new ImageIcon("pic/18.jpg");
32.
33. Icon ic21=new ImageIcon("pic/24.jpg");
34. Icon ic22=new ImageIcon("pic/25.jpg");
35. Icon ic23=new ImageIcon("pic/21.jpg");
36. Icon ic24=new ImageIcon("pic/27.jpg");
37. Icon ic25=new ImageIcon("pic/23.jpg");
38. Icon ic26=new ImageIcon("pic/29.jpg");
39. Icon ic27=new ImageIcon("pic/28.jpg");
40. Icon ic28=new ImageIcon("pic/22.jpg");
41. Icon ic29=new ImageIcon("pic/26.jpg");
42.
43. picpuzzle2(){
44.
45. super("pic puzzle");
46.
47. b1=new JButton(ic1);
48. b1.setBounds(10,80,100,100);
49. b2=new JButton(ic2);
50. b2.setBounds(110,80,100,100);
51. b3=new JButton(ic3);
52. b3.setBounds(210,80,100,100);
53. b4=new JButton(ic4);
54. b4.setBounds(10,180,100,100);
55. b5=new JButton(ic5);
56. b5.setBounds(110,180,100,100);
57. b6=new JButton(ic6);
58. b6.setBounds(210,180,100,100);
59. b7=new JButton(ic7);
60. b7.setBounds(10,280,100,100);
61. b8=new JButton(ic8);
62. b8.setBounds(110,280,100,100);
63. b9=new JButton(ic9);
64. b9.setBounds(210,280,100,100);
65. sample=new JButton(samicon1);
66. sample.setBounds(380,100,200,200);
67.
68. JLabel l1=new JLabel("Sample:");
69. l1.setBounds(330,200,70,20);
70. JLabel l2=new JLabel("NOTE:
71. icon has power to swap with neighbour icon=");
72. l2.setBounds(5,15,500,20);
73. JLabel l3=new JLabel("click sample picture to next puzzle");
74. l3.setBounds(380,320,200,20);
75. l3.setForeground(Color.red);
76.
77. starB=new JButton(ic0);
78. starB.setBounds(330,5,50,50);
79. star=b9.getIcon();
80.
81. add(b1);add(b2);add(b3);add(b4);add(b5);add(b6);add(b7);add(b8);
82. add(b9);add(sample);add(l1);add(l2);add(starB);add(l3);
83. b1.addActionListener(this); b2.addActionListener(this);
84. b3.addActionListener(this); b4.addActionListener(this);
85. b5.addActionListener(this); b6.addActionListener(this);
86. b7.addActionListener(this); b8.addActionListener(this);
87. b9.addActionListener(this);
88.
89. sample.addActionListener(this);
90. setLayout(null);
91. setSize(600,500);
92. setVisible(true);
93. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
94. }
95.
96. public void actionPerformed(ActionEvent e){
97. if(e.getSource()==b1){
98. Icon s1=b1.getIcon();
99. if(b2.getIcon()==star){
100. b2.setIcon(s1);
101. b1.setIcon(star);
102. } else if(b4.getIcon()==star){
103. b4.setIcon(s1);
104. b1.setIcon(star);
105. }
106. }//end of if
107.
108. if(e.getSource()==b2){
109. Icon s1=b2.getIcon();
110. if(b1.getIcon()==star){
111. b1.setIcon(s1);
112. b2.setIcon(star);
113. } else if(b5.getIcon()==star){
114. b5.setIcon(s1);
115. b2.setIcon(star);
116. }
117. else if(b3.getIcon()==star){
118. b3.setIcon(s1);
119. b2.setIcon(star);
120. }
121. }//end of if
122.
123. if(e.getSource()==b3){
124. Icon s1=b3.getIcon();
125. if(b2.getIcon()==star){
126. b2.setIcon(s1);
127. b3.setIcon(star);
128. } else if(b6.getIcon()==star){
129. b6.setIcon(s1);
130. b3.setIcon(star);
131. }
132. }//end of if
133.
134. if(e.getSource()==b4){
135. Icon s1=b4.getIcon();
136. if(b1.getIcon()==star){
137. b1.setIcon(s1);
138. b4.setIcon(star);
139. } else if(b5.getIcon()==star){
140. b5.setIcon(s1);
141. b4.setIcon(star);
142. }
143. else if(b7.getIcon()==star){
144. b7.setIcon(s1);
145. b4.setIcon(star);
146. }
147. }//end of if
148.
149. if(e.getSource()==b5){
150. Icon s1=b5.getIcon();
151. if(b2.getIcon()==star){
152. b2.setIcon(s1);
153. b5.setIcon(star);
154. } else if(b4.getIcon()==star){
155. b4.setIcon(s1);
156. b5.setIcon(star);
157. }
158. else if(b6.getIcon()==star){
159. b6.setIcon(s1);
160. b5.setIcon(star);
161. }
162. else if(b8.getIcon()==star){
163. b8.setIcon(s1);
164. b5.setIcon(star);
165. }
166. }//end of if
167.
168. if(e.getSource()==b6){
169. Icon s1=b6.getIcon();
170. if(b3.getIcon()==star){
171. b3.setIcon(s1);
172. b6.setIcon(star);
173. } else if(b5.getIcon()==star){
174. b5.setIcon(s1);
175. b6.setIcon(star);
176. }
177. else if(b9.getIcon()==star){
178. b9.setIcon(s1);
179. b6.setIcon(star);
180. }
181. }//end of if
182.
183. if(e.getSource()==b7){
184. Icon s1=b7.getIcon();
185. if(b4.getIcon()==star){
186. b4.setIcon(s1);
187. b7.setIcon(star);
188. } else if(b8.getIcon()==star){
189. b8.setIcon(s1);
190. b7.setIcon(star);
191. }
192. }//end of if
193.
194. if(e.getSource()==b8){
195. Icon s1=b8.getIcon();
196. if(b7.getIcon()==star){
197. b7.setIcon(s1);
198. b8.setIcon(star);
199. } else if(b5.getIcon()==star){
200. b5.setIcon(s1);
201. b8.setIcon(star);
202. }
203. else if(b9.getIcon()==star){
204. b9.setIcon(s1);
205. b8.setIcon(star);
206. }
207.
208. }//end of if
209.
210. if(e.getSource()==b9){
211. Icon s1=b9.getIcon();
212. if(b8.getIcon()==star){
213. b8.setIcon(s1);
214. b9.setIcon(star);
215. } else if(b6.getIcon()==star){
216. b6.setIcon(s1);
217. b9.setIcon(star);
218. }
219. }//end of if
220.
221. if(e.getSource()==sample){
222. Icon s1=sample.getIcon();
223. if(s1==samicon3){
224. sample.setIcon(samicon1);
225. b1.setIcon(ic1);
226. b2.setIcon(ic2);
227. b3.setIcon(ic3);
228. b4.setIcon(ic4);
229. b5.setIcon(ic5);
230. b6.setIcon(ic6);
231. b7.setIcon(ic7);
232. b8.setIcon(ic8);
233. b9.setIcon(ic9);
234. star=b9.getIcon();
235. starB.setIcon(ic0);
236. }//eof if
237. else if(s1==samicon1){
238. sample.setIcon(samicon2);
239. b1.setIcon(ic11);
240. b2.setIcon(ic12);
241. b3.setIcon(ic13);
242. b4.setIcon(ic14);
243. b5.setIcon(ic15);
244. b6.setIcon(ic16);
245. b7.setIcon(ic17);
246. b8.setIcon(ic18);
247. b9.setIcon(ic19);
248. star=b6.getIcon();
249. starB.setIcon(ic10);
250. }//eof else
251. else{
252. sample.setIcon(samicon3);
253. b1.setIcon(ic21);
254. b2.setIcon(ic22);
255. b3.setIcon(ic23);
256. b4.setIcon(ic24);
257. b5.setIcon(ic25);
258. b6.setIcon(ic26);
259. b7.setIcon(ic27);
260. b8.setIcon(ic28);
261. b9.setIcon(ic29);
262. star=b6.getIcon();
263. starB.setIcon(ic20);
264. }//eof else
265.
266. }
267. }//end of actionPerformed
268.
269. public static void main(String args[]){
270. new picpuzzle2();
271. }//end of main
272. }//end of class
BorderLayout (LayoutManagers):
LayoutManagers:
The LayoutManagers are used to arrange components in a particular manner. LayoutManager is
an interface that is implemented by all the classes of layout managers. There are following
classes that represents the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.
BorderLayout:
The BorderLayout is used to arrange the components in five regions: north, south, east, west and
center. Each region (area) may contain one component only. It is the default layout of frame or
window. The BorderLayout provides five constants for each region:
● BorderLayout(): creates a border layout but with no gaps between the components.
● JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and
vertical gaps between the components.
Example of BorderLayout class:
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class Border {
5. JFrame f;
6. Border(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("NORTH");;
10. JButton b2=new JButton("SOUTH");;
11. JButton b3=new JButton("EAST");;
12. JButton b4=new JButton("WEST");;
13. JButton b5=new JButton("CENTER");;
14.
15. f.add(b1,BorderLayout.NORTH);
16. f.add(b2,BorderLayout.SOUTH);
17. f.add(b3,BorderLayout.EAST);
18. f.add(b4,BorderLayout.WEST);
19. f.add(b5,BorderLayout.CENTER);
20.
21. f.setSize(300,300);
22. f.setVisible(true);
23. }
24. public static void main(String[] args) {
25. new Border();
26. }
27. }
GridLayout
The GridLayout is used to arrange the components in rectangular grid. One component is
displayed in each rectangle.
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class MyGridLayout{
5. JFrame f;
6. MyGridLayout(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("1");
10. JButton b2=new JButton("2");
11. JButton b3=new JButton("3");
12. JButton b4=new JButton("4");
13. JButton b5=new JButton("5");
14. JButton b6=new JButton("6");
15. JButton b7=new JButton("7");
16. JButton b8=new JButton("8");
17. JButton b9=new JButton("9");
18.
19. f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
20. f.add(b6);f.add(b7);f.add(b8);f.add(b9);
21.
22. f.setLayout(new GridLayout(3,3));
23. //setting grid layout of 3 rows and 3 columns
24.
25. f.setSize(300,300);
26. f.setVisible(true);
27. }
28. public static void main(String[] args) {
29. new MyGridLayout();
30. }
31. }
FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is
the default layout of applet or panel.
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class MyFlowLayout{
5. JFrame f;
6. MyFlowLayout(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("1");
10. JButton b2=new JButton("2");
11. JButton b3=new JButton("3");
12. JButton b4=new JButton("4");
13. JButton b5=new JButton("5");
14.
15. f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
16.
17. f.setLayout(new FlowLayout(FlowLayout.RIGHT));
18. //setting flow layout of right alignment
19.
20. f.setSize(300,300);
21. f.setVisible(true);
22. }
23. public static void main(String[] args) {
24. new MyFlowLayout();
25. }
26. }
BoxLayout class:
The BoxLayout is used to arrange the components either vertically or horizontally. For this
purpose, BoxLayout provides four constants. They are as follows:
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class BoxLayoutExample1 extends Frame {
5. Button buttons[];
6.
7. public BoxLayoutExample1 () {
8. buttons = new Button [5];
9.
10. for (int i = 0;i<5;i++) {
11. buttons[i] = new Button ("Button " + (i + 1));
12. add (buttons[i]);
13. }
14.
15. setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));
16. setSize(400,400);
17. setVisible(true);
18. }
19.
20. public static void main(String args[]){
21. BoxLayoutExample1 b=new BoxLayoutExample1();
22. }
23. }
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class BoxLayoutExample2 extends Frame {
5. Button buttons[];
6.
7. public BoxLayoutExample2() {
8. buttons = new Button [5];
9.
10. for (int i = 0;i<5;i++) {
11. buttons[i] = new Button ("Button " + (i + 1));
12. add (buttons[i]);
13. }
14.
15. setLayout (new BoxLayout(this, BoxLayout.X_AXIS));
16. setSize(400,400);
17. setVisible(true);
18. }
19.
20. public static void main(String args[]){
21. BoxLayoutExample2 b=new BoxLayoutExample2();
22. }
23. }
CardLayout class
The CardLayout class manages the components in such a manner that only one component is
visible at a time. It treats each component as a card that is why it is known as CardLayout.
1. import java.awt.*;
2. import java.awt.event.*;
3.
4. import javax.swing.*;
5.
6. public class CardLayoutExample extends JFrame implements ActionListener{
7. CardLayout card;
8. JButton b1,b2,b3;
9. Container c;
10. CardLayoutExample(){
11.
12. c=getContentPane();
13. card=new CardLayout(40,30);
14. //create CardLayout object with 40 hor space and 30 ver space
15. c.setLayout(card);
16.
17. b1=new JButton("Apple");
18. b2=new JButton("Boy");
19. b3=new JButton("Cat");
20. b1.addActionListener(this);
21. b2.addActionListener(this);
22. b3.addActionListener(this);
23.
24. c.add("a",b1);c.add("b",b2);c.add("c",b3);
25.
26. }
27. public void actionPerformed(ActionEvent e) {
28. card.next(c);
29. }
30.
31. public static void main(String[] args) {
32. CardLayoutExample cl=new CardLayoutExample();
33. cl.setSize(400,400);
34. cl.setVisible(true);
35. cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
36. }
37. }
Java Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
Drawback of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container
which is the subclass of Component.
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used
to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
The Component class provides 1 life cycle method of applet.
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class
object that can be used for drawing oval, rectangle, arc etc.
1. By html file.
2. By appletViewer tool (for testing purpose).
1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome",150,150);
8. }
9.
10. }
Note: class must be public because its object is created by Java Plugin software
that resides on the browser.
myapplet.html
1. <html>
2. <body>
3. <applet code="First.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome to applet",150,150);
8. }
9.
10. }
11. /*
12. <applet code="First.class" width="300" height="300">
13. </applet>
14. */
1. public abstract void drawString(String str, int x, int y): is used to draw the specified
string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the
specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle
with the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to draw oval
with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the
default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between
the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer):
is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used to fill a circular or elliptical arc.
10. public abstract void setColor(Color c): is used to set the graphics current color to the
specified color.
11. public abstract void setFont(Font font): is used to set the graphics current font to the
specified font.
1. import java.applet.Applet;
2. import java.awt.*;
3.
4. public class GraphicsDemo extends Applet{
5.
6. public void paint(Graphics g){
7. g.setColor(Color.red);
8. g.drawString("Welcome",50, 50);
9. g.drawLine(20,30,20,300);
10. g.drawRect(70,100,30,30);
11. g.fillRect(170,100,30,30);
12. g.drawOval(70,200,30,30);
13.
14. g.setColor(Color.pink);
15. g.fillOval(170,200,30,30);
16. g.drawArc(90,150,30,30,30,270);
17. g.fillArc(270,150,30,30,0,180);
18.
19. }
20. }
myapplet.html
1. <html>
2. <body>
3. <applet code="GraphicsDemo.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
1. import java.awt.*;
2. import java.applet.*;
3.
4.
5. public class DisplayImage extends Applet {
6.
7. Image picture;
8.
9. public void init() {
10. picture = getImage(getDocumentBase(),"sonoo.jpg");
11. }
12.
13. public void paint(Graphics g) {
14. g.drawImage(picture, 30,30, this);
15. }
16.
17. }
In the above example, drawImage() method of Graphics class is used to display the image. The
4th argument of drawImage() method of is ImageObserver object. The Component class
implements ImageObserver interface. So current class object would also be treated as
ImageObserver because Applet class indirectly extends the Component class.
myapplet.html
1. <html>
2. <body>
3. <applet code="DisplayImage.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
Animation in Applet
Applet is mostly used in games and animation. For this purpose image is required to be moved.
1. import java.awt.*;
2. import java.applet.*;
3. public class AnimationExample extends Applet {
4.
5. Image picture;
6.
7. public void init() {
8. picture =getImage(getDocumentBase(),"bike_1.gif");
9. }
10.
11. public void paint(Graphics g) {
12. for(int i=0;i<500;i++){
13. g.drawImage(picture, i,30, this);
14.
15. try{Thread.sleep(100);}catch(Exception e){}
16. }
17. }
18. }
In the above example, drawImage() method of Graphics class is used to display the image. The
4th argument of drawImage() method of is ImageObserver object. The Component class
implements ImageObserver interface. So current class object would also be treated as
ImageObserver because Applet class indirectly extends the Component class.
myapplet.html
1. <html>
2. <body>
3. <applet code="DisplayImage.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
EventHandling in Applet
As we perform event handling in AWT or Swing, we can perform it in applet also. Let's see the
simple example of event handling in applet that prints a message by click on the button.
1. import java.applet.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. public class EventApplet extends Applet implements ActionListener{
5. Button b;
6. TextField tf;
7.
8. public void init(){
9. tf=new TextField();
10. tf.setBounds(30,40,150,20);
11.
12. b=new Button("Click");
13. b.setBounds(80,150,60,50);
14.
15. add(b);add(tf);
16. b.addActionListener(this);
17.
18. setLayout(null);
19. }
20.
21. public void actionPerformed(ActionEvent e){
22. tf.setText("Welcome");
23. }
24. }
In the above example, we have created all the controls in init() method because it is invoked
only once.
myapplet.html
1. <html>
2. <body>
3. <applet code="EventApplet.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
In the above example, we have created all the controls in init() method because it is invoked
only once.
myapplet.html
1. <html>
2. <body>
3. <applet code="EventJApplet.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
Painting in Applet
We can perform painting operation in applet by the mouseDragged() method of
MouseMotionListener.
1. import java.awt.*;
2. import java.awt.event.*;
3. import java.applet.*;
4. public class MouseDrag extends Applet implements MouseMotionListener{
5.
6. public void init(){
7. addMouseMotionListener(this);
8. setBackground(Color.red);
9. }
10.
11. public void mouseDragged(MouseEvent me){
12. Graphics g=getGraphics();
13. g.setColor(Color.white);
14. g.fillOval(me.getX(),me.getY(),5,5);
15. }
16. public void mouseMoved(MouseEvent me){}
17.
18. }
In the above example, getX() and getY() method of MouseEvent is used to get the current x-axis
and y-axis. The getGraphics() method of Component class returns the object of Graphics.
myapplet.html
1. <html>
2. <body>
3. <applet code="MouseDrag.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
In the above example, getX() and getY() method of MouseEvent is used to get the current x-axis
and y-axis. The getGraphics() method of Component class returns the object of Graphics.
myapplet.html
1. <html>
2. <body>
3. <applet code="DigitalClock.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
1. import java.applet.*;
2. import java.awt.*;
3. import java.util.*;
4. import java.text.*;
5.
6. public class MyClock extends Applet implements Runnable {
7.
8. int width, height;
9. Thread t = null;
10. boolean threadSuspended;
11. int hours=0, minutes=0, seconds=0;
12. String timeString = "";
13.
14. public void init() {
15. width = getSize().width;
16. height = getSize().height;
17. setBackground( Color.black );
18. }
19.
20. public void start() {
21. if ( t == null ) {
22. t = new Thread( this );
23. t.setPriority( Thread.MIN_PRIORITY );
24. threadSuspended = false;
25. t.start();
26. }
27. else {
28. if ( threadSuspended ) {
29. threadSuspended = false;
30. synchronized( this ) {
31. notify();
32. }
33. }
34. }
35. }
36.
37. public void stop() {
38. threadSuspended = true;
39. }
40.
41. public void run() {
42. try {
43. while (true) {
44.
45. Calendar cal = Calendar.getInstance();
46. hours = cal.get( Calendar.HOUR_OF_DAY );
47. if ( hours > 12 ) hours -= 12;
48. minutes = cal.get( Calendar.MINUTE );
49. seconds = cal.get( Calendar.SECOND );
50.
51. SimpleDateFormat formatter
52. = new SimpleDateFormat( "hh:mm:ss", Locale.getDefault() );
53. Date date = cal.getTime();
54. timeString = formatter.format( date );
55.
56. // Now the thread checks to see if it should suspend itself
57. if ( threadSuspended ) {
58. synchronized( this ) {
59. while ( threadSuspended ) {
60. wait();
61. }
62. }
63. }
64. repaint();
65. t.sleep( 1000 ); // interval specified in milliseconds
66. }
67. }
68. catch (Exception e) { }
69. }
70.
71. void drawHand( double angle, int radius, Graphics g ) {
72. angle -= 0.5 * Math.PI;
73. int x = (int)( radius*Math.cos(angle) );
74. int y = (int)( radius*Math.sin(angle) );
75. g.drawLine( width/2, height/2, width/2 + x, height/2 + y );
76. }
77.
78. void drawWedge( double angle, int radius, Graphics g ) {
79. angle -= 0.5 * Math.PI;
80. int x = (int)( radius*Math.cos(angle) );
81. int y = (int)( radius*Math.sin(angle) );
82. angle += 2*Math.PI/3;
83. int x2 = (int)( 5*Math.cos(angle) );
84. int y2 = (int)( 5*Math.sin(angle) );
85. angle += 2*Math.PI/3;
86. int x3 = (int)( 5*Math.cos(angle) );
87. int y3 = (int)( 5*Math.sin(angle) );
88. g.drawLine( width/2+x2, height/2+y2, width/2 + x, height/2 + y );
89. g.drawLine( width/2+x3, height/2+y3, width/2 + x, height/2 + y );
90. g.drawLine( width/2+x2, height/2+y2, width/2 + x3, height/2 + y3 );
91. }
92.
93. public void paint( Graphics g ) {
94. g.setColor( Color.gray );
95. drawWedge( 2*Math.PI * hours / 12, width/5, g );
96. drawWedge( 2*Math.PI * minutes / 60, width/3, g );
97. drawHand( 2*Math.PI * seconds / 60, width/2, g );
98. g.setColor( Color.white );
99. g.drawString( timeString, 10, height-10 );
100. }
101. }
myapplet.html
1. <html>
2. <body>
3. <applet code="MyClock.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
Parameter in Applet
We can get any information from the HTML file as a parameter. For this purpose, Applet class
provides a method named getParameter(). Syntax:
1. import java.applet.Applet;
2. import java.awt.Graphics;
3.
4. public class UseParam extends Applet{
5.
6. public void paint(Graphics g){
7. String str=getParameter("msg");
8. g.drawString(str,50, 50);
9. }
10.
11. }
myapplet.html
1. <html>
2. <body>
3. <applet code="UseParam.class" width="300" height="300">
4. <param name="msg" value="Welcome to applet">
5. </applet>
6. </body>
7. </html>
Applet Communication
java.applet.AppletContext class provides the facility of communication between applets. We
provide the name of applet through the HTML file. It provides getApplet() method that returns
the object of Applet. Syntax:
1. import java.applet.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. public class ContextApplet extends Applet implements ActionListener{
5. Button b;
6.
7. public void init(){
8. b=new Button("Click");
9. b.setBounds(50,50,60,50);
10.
11. add(b);
12. b.addActionListener(this);
13. }
14.
15. public void actionPerformed(ActionEvent e){
16.
17. AppletContext ctx=getAppletContext();
18. Applet a=ctx.getApplet("app2");
19. a.setBackground(Color.yellow);
20. }
21. }
myapplet.html
1. <html>
2. <body>
3. <applet code="ContextApplet.class" width="150" height="150" name="app1">
4. </applet>
5.
6. <applet code="First.class" width="150" height="150" name="app2">
7. </applet>
8. </body>
9. </html>
Where it is used
The Reflection API is mainly used in:
1. class Simple{}
2.
3. class Test{
4. public static void main(String args[]){
5. Class c=Class.forName("Simple");
6. System.out.println(c.getName());
7. }
8. }
Output:Simple
1. class Simple{}
2.
3. class Test{
4. void printName(Object obj){
5. Class c=obj.getClass();
6. System.out.println(c.getName());
7. }
8. public static void main(String args[]){
9. Simple s=new Simple();
10.
11. Test t=new Test();
12. t.printName(s);
13. }
14. }
15.
Output:Simple
Output:boolean
Test
1. class Simple{}
2. interface My{}
3.
4. class Test{
5. public static void main(String args[]){
6. try{
7. Class c=Class.forName("Simple");
8. System.out.println(c.isInterface());
9.
10. Class c2=Class.forName("My");
11. System.out.println(c2.isInterface());
12.
13. }catch(Exception e){System.out.println(e);}
14.
15. }
16. }
Next Topics of Reflection API Tutorial
newInstance() method
The newInstance() method of Class class and Constructor class is used to create a new
instance of the class.
The newInstance() method of Class class can invoke zero-argument constructor whereas
newInstance() method of Constructor class can invoke any number of arguments. So Constructor
class is preferred over Class class.
1. class Simple{
2. void message(){System.out.println("Hello Java");}
3. }
4.
5. class Test{
6. public static void main(String args[]){
7. try{
8. Class c=Class.forName("Simple");
9. Simple s=(Simple)c.newInstance();
10. s.message();
11.
12. }catch(Exception e){System.out.println(e);}
13.
14. }
15. }
Output:Hello java
Understanding javap tool
The javap command disassembles a class file. The javap command displays information about
the fields,constructors and methods present in a class file.
1. javap fully_class_name
1. javap java.lang.Object
Output:
1. class Simple{
2. public static void main(String args[]){
3. System.out.println("hello java");
4. }
5. }
Now let's use the javap tool to disassemble the class file.
1. javap Simple
Output:
javap -c command
You can use the javap -c command to see disassembled code. The code that reflects the java
bytecode.
1. javap -c Simple
Output:
1. import java.lang.reflect.*;
2.
3. public class MyJavap{
4. public static void main(String[] args)throws Exception {
5. Class c=Class.forName(args[0]);
6.
7. System.out.println("Fields........");
8. Field f[]=c.getDeclaredFields();
9. for(int i=0;i<f.length;i++)
10. System.out.println(f[i]);
11.
12. System.out.println("Constructors........");
13. Constructor con[]=c.getDeclaredConstructors();
14. for(int i=0;i<con.length;i++)
15. System.out.println(con[i]);
16.
17. System.out.println("Methods........");
18. Method m[]=c.getDeclaredMethods();
19. for(int i=0;i<m.length;i++)
20. System.out.println(m[i]);
21. }
22. }
At runtime, you can get the details of any class, it may be user-defined or pre-defined class.
Output:
Creating your own appletviewer
As you know well that appletviewer tool creates a frame and displays the output of applet in the
frame.You can also create your frame and display the applet output.
1. import java.applet.Applet;
2. import java.awt.Frame;
3. import java.awt.Graphics;
4.
5. public class MyViewer extends Frame{
6. public static void main(String[] args) throws Exception{
7. Class c=Class.forName(args[0]);
8.
9. MyViewer v=new MyViewer();
10. v.setSize(400,400);
11. v.setLayout(null);
12. v.setVisible(true);
13.
14. Applet a=(Applet)c.newInstance();
15. a.start();
16. Graphics g=v.getGraphics();
17. a.paint(g);
18. a.stop();
19.
20. }
21.
22. }
1. //simple program of applet
2.
3. import java.applet.Applet;
4. import java.awt.Graphics;
5.
6. public class First extends Applet{
7.
8. public void paint(Graphics g){g.drawString("Welcome",50, 50);}
9. }
Output:
How to call private method from another class in java
You can call the private method from outside the class by changing the runtime behaviour of the
class.
By the help of java.lang.Class class and java.lang.reflect.Method class, we can call private
method from any other class.
1. public class A {
2. private void message(){System.out.println("hello java"); }
3. }
File: MethodCall.java
1. import java.lang.reflect.Method;
2. public class MethodCall{
3. public static void main(String[] args)throws Exception{
4.
5. Class c = Class.forName("A");
6. Object o= c.newInstance();
7. Method m =c.getDeclaredMethod("message", null);
8. m.setAccessible(true);
9. m.invoke(o, null);
10. }
11. }
Output:hello java
1. class A{
2. private void cube(int n){System.out.println(n*n*n);}
3. }
File: M.java
1. import java.lang.reflect.*;
2. class M{
3. public static void main(String args[])throws Exception{
4. Class c=A.class;
5. Object obj=c.newInstance();
6.
7. Method m=c.getDeclaredMethod("cube",new Class[]{int.class});
8. m.setAccessible(true);
9. m.invoke(obj,4);
10. }}
Output:64
Java Date
The java.util, java.sql and java.text packages contains classes for representing date and time.
Following classes are important for dealing with date in java.
● java.util.Date class
● java.sql.Date class
● java.text.DateFormat class
● java.text.SimpleDateFormat class
● java.util.Calendar class
● java.util.GregorianCalendar class
● java.sql.Time class
● java.sql.Timestamp class
● java.util.TimeZone class
Output:
Wed Mar 27 08:22:02 IST 2015
2nd way:
1. long millis=System.currentTimeMillis();
2. java.util.Date date=new java.util.Date(millis);
3. System.out.println(date);
Output:
Wed Mar 27 08:22:02 IST 2015
3rd way:
1. long millis=System.currentTimeMillis();
2. java.sql.Date date=new java.sql.Date(millis);
3. System.out.println(date);
Output:
2015-03-27
4th way:
1. Date date=java.util.Calendar.getInstance().getTime();
2. System.out.println(date);
Output:
Wed Mar 27 08:22:02 IST 2015
java.util.Date
The java.util.Date class represents date and time in java. It provides constructors and methods to
deal with date and time in java.
The java.util.Date class implements Serializable, Cloneable and Comparable<Date> interface. It
is inherited by java.sql.Date, java.sql.Time and java.sql.Timestamp interfaces.
After Calendar class, most of the constructors and methods of java.util.Date class has been
deprecated. Here, we are not giving list of any deprecated constructor and method.
java.util.Date Constructors
No. Constructor Description
1) Date() Creates a date object representing current date and time.
Date(long Creates a date object for the given milliseconds since January 1, 1970,
2)
milliseconds) 00:00:00 GMT.
java.util.Date Methods
No. Method Description
1) boolean after(Date date) tests if current date is after the given date.
2) boolean before(Date date) tests if current date is before the given date.
3) Object clone() returns the clone object of current date.
4) int compareTo(Date date) compares current date with given date.
5) boolean equals(Date date) compares current date with given date for equality.
6) static Date from(Instant instant) returns an instance of Date object from Instant date.
7) long getTime() returns the time represented by this date object.
8) int hashCode() returns the hash code value for this date object.
9) void setTime(long time) changes the current date and time to given time.
10) Instant toInstant() converts current date into Instant object.
11) String toString() converts this date into Instant object.
java.util.Date Example
Let's see the example to print date in java using java.util.Date class.
1st way:
Output:
Wed Mar 27 08:22:02 IST 2015
2nd way:
1. long millis=System.currentTimeMillis();
2. java.util.Date date=new java.util.Date(millis);
3. System.out.println(date);
Output:
Wed Mar 27 08:22:02 IST 2015
java.sql.Date
The java.sql.Date class represents only date in java. It inherits java.util.Date class.
The java.sql.Date instance is widely used in JDBC because it represents the date that can be
stored in database.
Some constructors and methods of java.sql.Date class has been deprecated. Here, we are not
giving list of any deprecated constructor and method.
java.sql.Date Constructor
No. Constructor Description
Date(long Creates a sql date object for the given milliseconds since January 1,
1)
milliseconds) 1970, 00:00:00 GMT.
java.sql.Date Methods
No. Method Description
1) void setTime(long time) changes the current sql date to given time.
2) Instant toInstant() converts current sql date into Instant object.
3) LocalDate toLocalDate() converts current sql date into LocalDate object.
4) String toString() converts this sql date object to a string.
5) static Date valueOf(LocalDate date) returns sql date object for the given LocalDate.
6) static Date valueOf(String date) returns sql date object for the given String.
Output:
2015-03-30
1. import java.sql.Date;
2. public class StringToSQLDateExample {
3. public static void main(String[] args) {
4. String str="2015-03-31";
5. Date date=Date.valueOf(str);//converting string into sql date
6. System.out.println(date);
7. }
8. }
Output:
2015-03-31
java.text.DateFormat Fields
java.text.DateFormat Methods
No. Public Method Description
1) final String format(Date date) converts given Date object into string.
Date parse(String source)throws
2) converts string into Date object.
ParseException
returns time formatter with default formatting
3) static final DateFormat getTimeInstance()
style for the default locale.
static final DateFormat getTimeInstance(int returns time formatter with the given
4)
style) formatting style for the default locale.
static final DateFormat getTimeInstance(int returns time formatter with the given
5)
style, Locale locale) formatting style for the given locale.
returns date formatter with default formatting
6) static final DateFormat getDateInstance()
style for the default locale.
static final DateFormat getDateInstance(int returns date formatter with the given
7)
style) formatting style for the default locale.
static final DateFormat getDateInstance(int returns date formatter with the given
8)
style, Locale locale) formatting style for the given locale.
static final DateFormat returns date/time formatter with default
9)
getDateTimeInstance() formatting style for the default locale.
static final DateFormat returns date/time formatter with the given
10) getDateTimeInstance(int dateStyle,int date formatting style and time formatting style
timeStyle) for the default locale.
11) static final DateFormat returns date/time formatter with the given
getDateTimeInstance(int dateStyle, int date formatting style and time formatting style
timeStyle, Locale locale) for the given locale.
returns date/time formatter with short
12) static final DateFormat getInstance()
formatting style for date and time.
13) static Locale[] getAvailableLocales() returns an array of available locales.
returns an instance of Calendar for this
14) Calendar getCalendar()
DateFormat instance.
returns an instance of NumberFormat for this
15) NumberFormat getNumberFormat()
DateFormat instance.
returns an instance of TimeZone for this
16) TimeZone getTimeZone()
DateFormat instance.
1. import java.text.DateFormat;
2. import java.util.Date;
3. public class DateFormatExample {
4. public static void main(String[] args) {
5. Date currentDate = new Date();
6. System.out.println("Current Date: "+currentDate);
7. String dateToStr = DateFormat.getInstance().format(currentDate);
8. System.out.println("Date Format using getInstance(): "+dateToStr);
9. }
10. }
Output:
Current Date: Tue Mar 31 14:37:23 IST 2015
Date Format using getInstance(): 31/3/15 2:37 PM
Let's see the full example to format date and time in java using java.text.DateFormat class.
1. import java.text.DateFormat;
2. import java.util.Date;
3. public class DateFormatExample2 {
4. public static void main(String[] args) {
5. Date currentDate = new Date();
6. System.out.println("Current Date: "+currentDate);
7.
8. String dateToStr = DateFormat.getInstance().format(currentDate);
9. System.out.println("Date Format using getInstance(): "+dateToStr);
10.
11. dateToStr = DateFormat.getDateInstance().format(currentDate);
12. System.out.println("Date Format using getDateInstance(): "+dateToStr);
13.
14. dateToStr = DateFormat.getTimeInstance().format(currentDate);
15. System.out.println("Date Format using getTimeInstance(): "+dateToStr);
16.
17. dateToStr = DateFormat.getDateTimeInstance().format(currentDate);
18. System.out.println("Date Format using getDateTimeInstance(): "+dateToStr);
19.
20. dateToStr = DateFormat.getTimeInstance(DateFormat.SHORT).format(currentDate);
Output:
Current Date: Tue Mar 31 14:37:23 IST 2015
Date Format using getInstance(): 31/3/15 2:37 PM
Date Format using getDateInstance(): 31 Mar, 2015
Date Format using getTimeInstance(): 2:37:23 PM
Date Format using getDateTimeInstance(): 31 Mar, 2015 2:37:23 PM
Date Format using getTimeInstance(DateFormat.SHORT): 2:37 PM
Date Format using getTimeInstance(DateFormat.MEDIUM): 2:37:23 PM
Date Format using getTimeInstance(DateFormat.LONG): 2:37:23 PM IST
Date Format using getDateTimeInstance(DateFormat.LONG,DateFormat.SHORT): 31
March, 2015 2:37 PM
1. import java.text.DateFormat;
2. import java.util.Date;
3. public class DateFormatExample3 {
4. public static void main(String[] args)throws Exception {
5. Date d = DateFormat.getDateInstance().parse("31 Mar, 2015");
6. System.out.println("Date is: "+d);
7. }
8. }
Output:
Date is: Tue Mar 31 00:00:00 IST 2015
Java SimpleDateFormat
The java.text.SimpleDateFormat class provides methods to format and parse date and time in
java. The SimpleDateFormat is a concrete class for formatting and parsing date which inherits
java.text.DateFormat class.
Notice that formatting means converting date to string and parsing means converting string
to date.
1. import java.text.SimpleDateFormat;
2. import java.util.Date;
3. public class SimpleDateFormatExample {
4. public static void main(String[] args) {
5. Date date = new Date();
6. SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
7. String strDate= formatter.format(date);
8. System.out.println(strDate);
9. }
10. }
Output:
13/04/2015
1. import java.text.ParseException;
2. import java.text.SimpleDateFormat;
3. import java.util.Date;
4. import java.util.Locale;
5. public class SimpleDateFormatExample2 {
6. public static void main(String[] args) {
7. Date date = new Date();
8. SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
9. String strDate = formatter.format(date);
10. System.out.println("Date Format with MM/dd/yyyy : "+strDate);
11.
12. formatter = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
13. strDate = formatter.format(date);
14. System.out.println("Date Format with dd-M-yyyy hh:mm:ss : "+strDate);
15.
16. formatter = new SimpleDateFormat("dd MMMM yyyy");
17. strDate = formatter.format(date);
18. System.out.println("Date Format with dd MMMM yyyy : "+strDate);
19.
20. formatter = new SimpleDateFormat("dd MMMM yyyy zzzz");
21. strDate = formatter.format(date);
22. System.out.println("Date Format with dd MMMM yyyy zzzz : "+strDate);
23.
24. formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
25. strDate = formatter.format(date);
26. System.out.println("Date Format with E, dd MMM yyyy HH:mm:ss z : "+strDate);
27. }
28. }
Output:
Date Format with MM/dd/yyyy : 04/13/2015
Date Format with dd-M-yyyy hh:mm:ss : 13-4-2015 10:59:26
Date Format with dd MMMM yyyy : 13 April 2015
Date Format with dd MMMM yyyy zzzz : 13 April 2015 India Standard Time
Date Format with E, dd MMM yyyy HH:mm:ss z : Mon, 13 Apr 2015 22:59:26 IST
1. import java.text.ParseException;
2. import java.text.SimpleDateFormat;
3. import java.util.Date;
4. public class SimpleDateFormatExample3 {
5. public static void main(String[] args) {
6. SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
7. try {
8. Date date = formatter.parse("31/03/2015");
9. System.out.println("Date is: "+date);
10. } catch (ParseException e) {e.printStackTrace();}
11. }
12. }
Output:
Date is: Tue Mar 31 00:00:00 IST 2015
1. java.util.Date class
2. java.sql.Date class
3. java.util.Calendar class
2nd way:
1. long millis=System.currentTimeMillis();
2. java.util.Date date=new java.util.Date(millis);
3. System.out.println(date);
Output:
Thu Mar 26 08:22:02 IST 2015
1. long millis=System.currentTimeMillis();
2. java.sql.Date date=new java.sql.Date(millis);
3. System.out.println(date);
Output:
2015-03-26
1. Date date=java.util.Calendar.getInstance().getTime();
2. System.out.println(date);
Output:
Thu Mar 26 08:22:02 IST 2015
Note: It is recommended to use Calendar class for getting current date and time.
Scenario
It is generally used if we have to perform mathematical operations on the string that contains
number. Whenever we get data from textfield or textarea, entered data is received as a string. If
entered data is integer, we need to convert string to int. To do so, we use Integer.parseInt()
method.
Signature
The parseInt() is the static method of Integer class. The signature of parseInt() method is given
below:
1. int i=Integer.parseInt("200");
Output:
200100
300
Scenario
It is generally used if we have to display number in textfield because everything is displayed as a
string in form.
1) String.valueOf()
The String.valueOf() method converts int to String. The valueOf() is the static method of String
class. The signature of valueOf() method is given below:
1. int i=10;
2. String s=String.valueOf(i);//Now it will return "10"
2) Integer.toString()
The Integer.toString() method converts int to String. The toString() is the static method of
Integer class. The signature of toString() method is given below:
1. int i=10;
2. String s=Integer.toString(i);//Now it will return "10"
Output:
300
200100
Scenario
It is generally used if we have to perform mathematical operations on the string that contains
long number. Whenever we get data from textfield or textarea, entered data is received as a
string. If entered data is long, we need to convert string to long. To do so, we use
Long.parseLong() method.
Signature
The parseLong() is the static method of Long class. The signature of parseLong() method is
given below:
1. public static long parseLong(String s)
1. long l=Long.parseLong("200");
Output:
9990449935
Scenario
It is generally used if we have to display long number in textfield because everything is
displayed as a string in form.
1) String.valueOf()
The String.valueOf() is an overloaded method. It can be used to convert long to String. The
valueOf() is the static method of String class. The signature of valueOf() method is given below:
Output:
9993939399
2) Long.toString()
The Long.toString() method converts long to String. The toString() is the static method of Long
class. The signature of toString() method is given below:
1. long i=9993939399L;
2. String s=Long.toString(i);//Now it will return "9993939399"
Output:
9993939399
Scenario
It is generally used if we have to perform mathematical operations on the string that contains
float number. Whenever we get data from textfield or textarea, entered data is received as a
string. If entered data is float, we need to convert string to float. To do so, we use
Float.parseFloat() method.
Signature
The parseFloat() is the static method of Float class. The signature of parseFloat() method is
given below:
1. float f=Float.parseFloat("23.6");
Output:
23.6
Scenario
It is generally used if we have to perform mathematical operations on the string that contains
double number. Whenever we get data from textfield or textarea, entered data is received as a
string. If entered data is double, we need to convert string to double. To do so, we use
Double.parseDouble() method.
Signature
The parseDouble() is the static method of Double class. The signature of parseDouble() method
is given below:
1. double d=Double.parseDouble("23.6");
1. import java.text.SimpleDateFormat;
2. import java.util.Date;
3. public class StringToDateExample1 {
4. public static void main(String[] args)throws Exception {
5. String sDate1="31/12/1998";
6. Date date1=new SimpleDateFormat("dd/MM/yyyy").parse(sDate1);
7. System.out.println(sDate1+"\t"+date1);
8. }
9. }
Output:
31/12/1998 Thu Dec 31 00:00:00 IST 1998
Let's see another code to convert different types of string to Date in java.
1. import java.text.SimpleDateFormat;
2. import java.util.Date;
3. public class StringToDateExample1 {
4. public static void main(String[] args)throws Exception {
5. String sDate1="31/12/1998";
6. String sDate2 = "31-Dec-1998";
7. String sDate3 = "12 31, 1998";
8. String sDate4 = "Thu, Dec 31 1998";
9. String sDate5 = "Thu, Dec 31 1998 23:37:50";
10. String sDate6 = "31-Dec-1998 23:37:50";
11. SimpleDateFormat formatter1=new SimpleDateFormat("dd/MM/yyyy");
12. SimpleDateFormat formatter2=new SimpleDateFormat("dd-MMM-yyyy");
13. SimpleDateFormat formatter3=new SimpleDateFormat("MM dd, yyyy");
14. SimpleDateFormat formatter4=new SimpleDateFormat("E, MMM dd yyyy");
15. SimpleDateFormat formatter5=new SimpleDateFormat("E, MMM dd yyyy HH:mm:ss")
;
16. SimpleDateFormat formatter6=new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
17. Date date1=formatter1.parse(sDate1);
18. Date date2=formatter2.parse(sDate2);
19. Date date3=formatter3.parse(sDate3);
20. Date date4=formatter4.parse(sDate4);
21. Date date5=formatter5.parse(sDate5);
22. Date date6=formatter6.parse(sDate6);
23. System.out.println(sDate1+"\t"+date1);
24. System.out.println(sDate2+"\t"+date2);
25. System.out.println(sDate3+"\t"+date3);
26. System.out.println(sDate4+"\t"+date4);
27. System.out.println(sDate5+"\t"+date5);
28. System.out.println(sDate6+"\t"+date6);
29. }
30. }
Output:
31/12/1998 Thu Dec 31 00:00:00 IST 1998
31-Dec-1998 Thu Dec 31 00:00:00 IST 1998
12 31, 1998 Thu Dec 31 00:00:00 IST 1998
Thu, Dec 31 1998 Thu Dec 31 00:00:00 IST 1998
Thu, Dec 31 1998 23:37:50 Thu Dec 31 23:37:50 IST 1998
31-Dec-1998 23:37:50 Thu Dec 31 23:37:50 IST 1998
Collections in Java
Collections in java is a framework that provides an architecture to store and manipulate the
group of objects.
All the operations that you perform on a data such as searching, sorting, insertion, manipulation,
deletion etc. can be performed by Java Collections.
Java Collection simply means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList,
PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).
Do You Know ?
Iterator interface
Iterator interface provides the facility of iterating the elements in forward direction only.
1. ArrayList class
2. LinkedList class
3. ListIterator interface
4. HashSet class
5. LinkedHashSet class
6. TreeSet class
7. PriorityQueue class
8. Map interface
9. HashMap class
10. LinkedHashMap class
11. TreeMap class
12. Hashtable class
13. Sorting
14. Comparable interface
15. Comparator interface
16. Properties class in Java
In generic collection, we specify the type in angular braces. Now ArrayList is forced to have
only specified type of objects in it. If you try to add another type of object, it gives compile time
error.
1. import java.util.*;
2. class TestCollection1{
3. public static void main(String args[]){
4.
5. ArrayList<String> al=new ArrayList<String>();//creating arraylist
6. al.add("Ravi");//adding object in arraylist
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10.
11. Iterator itr=al.iterator();//getting Iterator from arraylist to traverse elements
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Ravi
Vijay
Ravi
Ajay
1. By Iterator interface.
2. By for-each loop.
In the above example, we have seen traversing ArrayList by Iterator. Let's see the example to
traverse ArrayList elements using for-each loop.
1. import java.util.*;
2. class TestCollection2{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ravi");
8. al.add("Ajay");
9. for(String obj:al)
10. System.out.println(obj);
11. }
12. }
Ravi
Vijay
Ravi
Ajay
1. class Student{
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10. }
1. import java.util.*;
2. public class TestCollection3{
3. public static void main(String args[]){
4. //Creating user-defined class objects
5. Student s1=new Student(101,"Sonoo",23);
6. Student s2=new Student(102,"Ravi",21);
7. Student s2=new Student(103,"Hanumat",25);
8.
9. ArrayList<Student> al=new ArrayList<Student>();//creating arraylist
10. al.add(s1);//adding Student class object
11. al.add(s2);
12. al.add(s3);
13.
14. Iterator itr=al.iterator();
15. //traversing elements of ArrayList object
16. while(itr.hasNext()){
17. Student st=(Student)itr.next();
18. System.out.println(st.rollno+" "+st.name+" "+st.age);
19. }
20. }
21. }
101 Sonoo 23
102 Ravi 21
103 Hanumat 25
Example of addAll(Collection c) method
1. import java.util.*;
2. class TestCollection4{
3. public static void main(String args[]){
4.
5. ArrayList<String> al=new ArrayList<String>();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ajay");
9.
10. ArrayList<String> al2=new ArrayList<String>();
11. al2.add("Sonoo");
12. al2.add("Hanumat");
13.
14. al.addAll(al2);
15.
16. Iterator itr=al.iterator();
17. while(itr.hasNext()){
18. System.out.println(itr.next());
19. }
20. }
21. }
Ravi
Vijay
Ajay
Sonoo
Hanumat
1. import java.util.*;
2. class TestCollection5{
3. public static void main(String args[]){
4.
5. ArrayList<String> al=new ArrayList<String>();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ajay");
9.
10. ArrayList<String> al2=new ArrayList<String>();
11. al2.add("Ravi");
12. al2.add("Hanumat");
13.
14. al.removeAll(al2);
15.
16. System.out.println("iterating the elements after removing the elements of al2...");
17. Iterator itr=al.iterator();
18. while(itr.hasNext()){
19. System.out.println(itr.next());
20. }
21.
22. }
23. }
1. import java.util.*;
2. class TestCollection6{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ajay");
8. ArrayList<String> al2=new ArrayList<String>();
9. al2.add("Ravi");
10. al2.add("Hanumat");
11.
12. al.retainAll(al2);
13.
14. System.out.println("iterating the elements after retaining the elements of al2...");
15. Iterator itr=al.iterator();
16. while(itr.hasNext()){
17. System.out.println(itr.next());
18. }
19. }
20. }
1. import java.util.*;
2. public class TestCollection7{
3. public static void main(String args[]){
4.
5. LinkedList<String> al=new LinkedList<String>();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10.
11. Iterator<String> itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Output:Ravi
Vijay
Ravi
Ajay
Difference between ArrayList and LinkedList
ArrayList and LinkedList both implements List interface and maintains insertion order. Both are
non synchronized classes.
But there are many differences between ArrayList and LinkedList classes that are given below.
ArrayList LinkedList
1) ArrayList internally uses dynamic array to store LinkedList internally uses doubly linked list
the elements. to store the elements.
2) Manipulation with ArrayList is slow because it Manipulation with LinkedList is faster than
internally uses array. If any element is removed ArrayList because it uses doubly linked list so
from the array, all the bits are shifted in memory. no bit shifting is required in memory.
LinkedList class can act as a list and queue
3) ArrayList class can act as a list only because it
both because it implements List and Deque
implements List only.
interfaces.
4) ArrayList is better for storing and accessing
LinkedList is better for manipulating data.
data.
1. import java.util.*;
2. class TestArrayLinked{
3. public static void main(String args[]){
4.
5. List<String> al=new ArrayList<String>();//creating arraylist
6. al.add("Ravi");//adding object in arraylist
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10.
11. List<String> al2=new LinkedList<String>();//creating linkedlist
12. al2.add("James");//adding object in linkedlist
13. al2.add("Serena");
14. al2.add("Swati");
15. al2.add("Junaid");
16.
17. System.out.println("arraylist: "+al);
18. System.out.println("linkedlist: "+al2);
19. }
20. }
Output:
arraylist: [Ravi,Vijay,Ravi,Ajay]
linkedlist: [James,Serena,Swati,Junaid]
1. import java.util.*;
2. public class TestCollection8{
3. public static void main(String args[]){
4.
5. ArrayList<String> al=new ArrayList<String>();
6. al.add("Amit");
7. al.add("Vijay");
8. al.add("Kumar");
9. al.add(1,"Sachin");
10.
11. System.out.println("element at 2nd position: "+al.get(2));
12.
13. ListIterator<String> itr=al.listIterator();
14.
15. System.out.println("traversing elements in forward direction...");
16. while(itr.hasNext()){
17. System.out.println(itr.next());
18. }
19.
20.
21. System.out.println("traversing elements in backward direction...");
22. while(itr.hasPrevious()){
23. System.out.println(itr.previous());
24. }
25. }
26. }
1. import java.util.*;
2. class TestCollection9{
3. public static void main(String args[]){
4.
5. HashSet<String> al=new HashSet<String>();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10.
11. Iterator<String> itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Output:Ajay
Vijay
Ravi
1. import java.util.*;
2. class TestCollection10{
3. public static void main(String args[]){
4.
5. LinkedHashSet<String> al=new LinkedHashSet<String>();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10.
11. Iterator<String> itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Output:>Ravi
Vijay
Ajay
1. import java.util.*;
2. class TestCollection11{
3. public static void main(String args[]){
4.
5. TreeSet<String> al=new TreeSet<String>();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10.
11. Iterator<String> itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Output:Ajay
Ravi
Vijay
PriorityQueue class:
The PriorityQueue class provides the facility of using queue. But it does not orders the elements
in FIFO manner.
Example of PriorityQueue:
1. import java.util.*;
2. class TestCollection12{
3. public static void main(String args[]){
4.
5. PriorityQueue<String> queue=new PriorityQueue<String>();
6. queue.add("Amit");
7. queue.add("Vijay");
8. queue.add("Karan");
9. queue.add("Jai");
10. queue.add("Rahul");
11.
12. System.out.println("head:"+queue.element());
13. System.out.println("head:"+queue.peek());
14.
15. System.out.println("iterating the queue elements:");
16. Iterator itr=queue.iterator();
17. while(itr.hasNext()){
18. System.out.println(itr.next());
19. }
20.
21. queue.remove();
22. queue.poll();
23.
24. System.out.println("after removing two elements:");
25. Iterator<String> itr2=queue.iterator();
26. while(itr2.hasNext()){
27. System.out.println(itr2.next());
28. }
29.
30. }
31. }
Output:head:Amit
head:Amit
iterating the queue elements:
Amit
Jai
Karan
Vijay
Rahul
after removing two elements:
Karan
Rahul
Vijay
1. public Object put(object key,Object value): is used to insert an entry in this map.
2. public void putAll(Map map):is used to insert the specified map in this map.
3. public Object remove(object key):is used to delete an entry for the specified key.
4. public Object get(Object key):is used to return the value for the specified key.
5. public boolean containsKey(Object key):is used to search the specified key from this
map.
6. public boolean containsValue(Object value):is used to search the specified value from
this map.
7. public Set keySet():returns the Set view containing all the keys.
8. public Set entrySet():returns the Set view containing all the keys and values.
Entry
Entry is the subinterface of Map.So we will access it by Map.Entry name.It provides methods to
get key and value.
1. import java.util.*;
2. class TestCollection13{
3. public static void main(String args[]){
4.
5. HashMap<Integer,String> hm=new HashMap<Integer,String>();
6.
7. hm.put(100,"Amit");
8. hm.put(101,"Vijay");
9. hm.put(102,"Rahul");
10.
11. for(Map.Entry m:hm.entrySet()){
12. System.out.println(m.getKey()+" "+m.getValue());
13. }
14. }
15. }
Output:102 Rahul
100 Amit
101 Vijay
1. import java.util.*;
2. class TestCollection14{
3. public static void main(String args[]){
4.
5. LinkedHashMap<Integer,String> hm=new LinkedHashMap<Integer,String>();
6.
7. hm.put(100,"Amit");
8. hm.put(101,"Vijay");
9. hm.put(102,"Rahul");
10.
11. for(Map.Entry m:hm.entrySet()){
12. System.out.println(m.getKey()+" "+m.getValue());
13. }
14. }
15. }
Output:100 Amit
101 Vijay
103 Rahul
1. import java.util.*;
2. class TestCollection15{
3. public static void main(String args[]){
4.
5. TreeMap<Integer,String> hm=new TreeMap<Integer,String>();
6.
7. hm.put(100,"Amit");
8. hm.put(102,"Ravi");
9. hm.put(101,"Vijay");
10. hm.put(103,"Rahul");
11.
12. for(Map.Entry m:hm.entrySet()){
13. System.out.println(m.getKey()+" "+m.getValue());
14. }
15. }
16. }
Output:100 Amit
101 Vijay
102 Ravi
103 Rahul
What is difference between HashMap and TreeMap?
1) HashMap is can contain one null key. TreeMap can not contain any null key.
2) HashMap maintains no order. TreeMap maintains ascending order.
Example of Hashtable:
1. import java.util.*;
2. class TestCollection16{
3. public static void main(String args[]){
4.
5. Hashtable<Integer,String> hm=new Hashtable<Integer,String>();
6.
7. hm.put(100,"Amit");
8. hm.put(102,"Ravi");
9. hm.put(101,"Vijay");
10. hm.put(103,"Rahul");
11.
12. for(Map.Entry m:hm.entrySet()){
13. System.out.println(m.getKey()+" "+m.getValue());
14. }
15. }
16. }
Output:103 Rahul
102 Ravi
101 Vijay
100 Amit
Sorting
We can sort the elements of:
1. String objects
2. Wrapper class objects
3. User-defined class objects
Collections class provides static methods for sorting the elements of collection.If collection
elements are of Set type, we can use TreeSet.But We cannot sort the elements of
List.Collections class provides methods for sorting the elements of List type elements.
Note: String class and Wrapper classes implements the Comparable interface.So
if you store the objects of string or wrapper classes, it will be Comparable.
1. import java.util.*;
2. class TestSort1{
3. public static void main(String args[]){
4.
5. ArrayList<String> al=new ArrayList<String>();
6. al.add("Viru");
7. al.add("Saurav");
8. al.add("Mukesh");
9. al.add("Tahir");
10.
11. Collections.sort(al);
12. Iterator itr=al.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. }
17. }
Output:Mukesh
Saurav
Tahir
Viru
Example of Sorting the elements of List that contains Wrapper class objects
1. import java.util.*;
2. class TestSort2{
3. public static void main(String args[]){
4.
5. ArrayList al=new ArrayList();
6. al.add(Integer.valueOf(201));
7. al.add(Integer.valueOf(101));
8. al.add(230);//internally will be converted into objects as Integer.valueOf(230)
9.
10. Collections.sort(al);
11.
12. Iterator itr=al.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. }
17. }
Output:101
201
230
Comparable interface
Comparable interface is used to order the objects of user-defined class.This interface is found in
java.lang package and contains only one method named compareTo(Object).It provide only
single sorting sequence i.e. you can sort the elements on based on single datamember only.For
instance it may be either rollno,name,age or anything else.
Syntax:
public int compareTo(Object obj): is used to compare the current object with the specified
object.
1. String objects
2. Wrapper class objects
3. User-defined class objects
Collections class provides static methods for sorting the elements of collection.If collection
elements are of Set type, we can use TreeSet.But We cannot sort the elements of
List.Collections class provides methods for sorting the elements of List type elements.
Note: String class and Wrapper classes implements the Comparable interface.So
if you store the objects of string or wrapper classes, it will be Comparable.
Example of Sorting the elements of List that contains user-defined class objects
on age basis
Student.java
Simple.java
1. import java.util.*;
2. import java.io.*;
3.
4. class TestSort3{
5. public static void main(String args[]){
6.
7. ArrayList al=new ArrayList();
8. al.add(new Student(101,"Vijay",23));
9. al.add(new Student(106,"Ajay",27));
10. al.add(new Student(105,"Jai",21));
11.
12. Collections.sort(al);
13. Iterator itr=al.iterator();
14. while(itr.hasNext()){
15. Student st=(Student)itr.next();
16. System.out.println(st.rollno+""+st.name+""+st.age);
17. }
18. }
19. }
Output:105 Jai 21
101 Vijay 23
106 Ajay 27
Comparator interface
Comparator interface is used to order the objects of user-defined class.
This interface is found in java.util package and contains 2 methods compare(Object obj1,Object
obj2) and equals(Object element).
It provides multiple sorting sequence i.e. you can sort the elements based on any data member.
For instance it may be on rollno, name, age or anything else.
Collections class provides static methods for sorting the elements of collection. If collection
elements are of Set type, we can use TreeSet. But We cannot sort the elements of List.
Collections class provides methods for sorting the elements of List type elements.
1. Student.java
2. AgeComparator.java
3. NameComparator.java
4. Simple.java
Student.java
This class contains three fields rollno, name and age and a parameterized constructor.
1. class Student{
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10. }
AgeComparator.java
This class defines comparison logic based on the age. If age of first object is greater than the
second, we are returning positive value, it can be any one such as 1, 2 , 10 etc. If age of first
object is less than the second object, we are returning negative value, it can be any negative
value and if age of both objects are equal, we are returning 0.
1. import java.util.*;
2. class AgeComparator implements Comparator{
3. public int Compare(Object o1,Object o2){
4. Student s1=(Student)o1;
5. Student s2=(Student)o2;
6.
7. if(s1.age==s2.age)
8. return 0;
9. else if(s1.age>s2.age)
10. return 1;
11. else
12. return -1;
13. }
14. }
NameComparator.java
This class provides comparison logic based on the name. In such case, we are using the
compareTo() method of String class, which internally provides the comparison logic.
1. import java.util.*;
2. class NameComparator implements Comparator{
3. public int Compare(Object o1,Object o2){
4. Student s1=(Student)o1;
5. Student s2=(Student)o2;
6.
7. return s1.name.compareTo(s2.name);
8. }
9. }
Simple.java
In this class, we are printing the objects values by sorting on the basis of name and age.
1. import java.util.*;
2. import java.io.*;
3.
4. class Simple{
5. public static void main(String args[]){
6.
7. ArrayList al=new ArrayList();
8. al.add(new Student(101,"Vijay",23));
9. al.add(new Student(106,"Ajay",27));
10. al.add(new Student(105,"Jai",21));
11.
12. System.out.println("Sorting by Name...");
13.
14. Collections.sort(al,new NameComparator());
15. Iterator itr=al.iterator();
16. while(itr.hasNext()){
17. Student st=(Student)itr.next();
18. System.out.println(st.rollno+" "+st.name+" "+st.age);
19. }
20.
21. System.out.println("sorting by age...");
22.
23. Collections.sort(al,new AgeComparator());
24. Iterator itr2=al.iterator();
25. while(itr2.hasNext()){
26. Student st=(Student)itr2.next();
27. System.out.println(st.rollno+" "+st.name+" "+st.age);
28. }
29.
30.
31. }
32. }
Output:Sorting by Name...
106 Ajay 27
105 Jai 21
101 Vijay 23
Sorting by age...
105 Jai 21
101 Vijay 23
106 Ajay 27
1. user=system
2. password=oracle
Now, lets create the java class to read the data from the properties file.
Test.java
1. import java.util.*;
2. import java.io.*;
3. public class Test {
4. public static void main(String[] args)throws Exception{
5. FileReader reader=new FileReader("db.properties");
6.
7. Properties p=new Properties();
8. p.load(reader);
9.
10. System.out.println(p.getProperty("user"));
11. System.out.println(p.getProperty("password"));
12. }
13. }
Output:system
oracle
Now if you change the value of the properties file, you don't need to compile the java class
again. That means no maintenance problem.
1. import java.util.*;
2. import java.io.*;
3. public class Test {
4. public static void main(String[] args)throws Exception{
5.
6. Properties p=System.getProperties();
7. Set set=p.entrySet();
8.
9. Iterator itr=set.iterator();
10. while(itr.hasNext()){
11. Map.Entry entry=(Map.Entry)itr.next();
12. System.out.println(entry.getKey()+" = "+entry.getValue());
13. }
14.
15. }
16. }
Output:
java.runtime.name = Java(TM) SE Runtime Environment
sun.boot.library.path = C:\Program Files\Java\jdk1.7.0_01\jre\bin
java.vm.version = 21.1-b02
java.vm.vendor = Oracle Corporation
java.vendor.url = http://java.oracle.com/
path.separator = ;
java.vm.name = Java HotSpot(TM) Client VM
file.encoding.pkg = sun.io
user.country = US
user.script =
sun.java.launcher = SUN_STANDARD
...........
Output:
Sonoo
Michael
James
Andy
1. import java.util.*;
2. class TestVector1{
3. public static void main(String args[]){
4. Vector<String> v=new Vector<String>();//creating vector
5. v.add("umesh");//method of Collection
6. v.addElement("irfan");//method of Vector
7. v.addElement("kumar");
8. //traversing elements using Enumeration
9. Enumeration e=v.elements();
10. while(e.hasMoreElements()){
11. System.out.println(e.nextElement());
12. }
13. }
14. }
Output:
umesh
irfan
kumar
● How to connect Java application with Oracle and Mysql database using JDBC?
● What is the difference between Statement and PreparedStatement interface?
● How to print total numbers of tables and views of a database using JDBC ?
● How to store and retrieve images from Oracle database using JDBC?
● How to store and retrieve files from Oracle database using JDBC?
What is API
API (Application programming interface) is a document that contains description of all the
features of a product or software. It represents classes and interfaces that software programs can
follow to communicate with each other. An API can be created for applications, libraries,
operating systems, etc
Topics in Java JDBC Tutorial
2) JDBC Drivers
In this JDBC tutorial, we will learn 4 types of JDBC drivers, their advantages and disadvantages.
7) DriverManager class
In this JDBC tutorial, we will learn what does the DriverManager class and what are its methods.
8) Connection interface
In this JDBC tutorial, we will learn what is Connection interface and what are its methods.
9) Statement interface
In this JDBC tutorial, we will learn what is Statement interface and what are its methods.
18) CallableStatement
Let's see the code to call stored procedures and functions using CallableStatement.
JDBC Driver
JDBC Driver is a software component that enables java application to interact with the
database.There are 4 types of JDBC drivers:
Advantages:
● easy to use.
● can be easily connected to any database.
Disadvantages:
● Performance degraded because JDBC method call is converted into the ODBC function
calls.
● The ODBC driver needs to be installed on the client machine.
2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts JDBC
method calls into native calls of the database API. It is not written entirely in java.
Advantage:
Disadvantage:
● No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.
Disadvantages:
4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is
why it is known as thin driver. It is fully written in Java language.
Advantage:
Disadvantage:
There are 5 steps to connect any java application with the database in java using JDBC. They are
as follows:
1. Class.forName("oracle.jdbc.driver.OracleDriver");
1. Connection con=DriverManager.getConnection(
2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");
1. Statement stmt=con.createStatement();
4) Execute the query
The executeQuery() method of Statement interface is used to execute queries to the database.
This method returns the object of ResultSet that can be used to get all the records of a table.
1. con.close();
1. Driver class: The driver class for the oracle database is oracle.jdbc.driver.OracleDriver.
2. Connection URL: The connection URL for the oracle10G database is
jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the database, thin is
the driver, localhost is the server name on which oracle is running, we may also use IP
address, 1521 is the port number and XE is the Oracle service name. You may get all
these informations from the tnsnames.ora file.
3. Username: The default username for the oracle database is system.
4. Password: Password is given by the user at the time of installing the oracle database.
Let's first create a table in oracle database.
1. create table emp(id number(10),name varchar2(40),age number(3));
1. import java.sql.*;
2. class OracleCon{
3. public static void main(String args[]){
4. try{
5. //step1 load the driver class
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7.
8. //step2 create the connection object
9. Connection con=DriverManager.getConnection(
10. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
11.
12. //step3 create the statement object
13. Statement stmt=con.createStatement();
14.
15. //step4 execute query
16. ResultSet rs=stmt.executeQuery("select * from emp");
17. while(rs.next())
18. System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
19.
20. //step5 close the connection object
21. con.close();
22.
23. }catch(Exception e){ System.out.println(e);}
24.
25. }
26. }
The above example will fetch all the records of emp table.
To connect java application with the Oracle database ojdbc14.jar file is required to be loaded.
download the jar file ojdbc14.jar
Two ways to load the jar file:
2) set classpath:
There are two ways to set the classpath:
● temporary
● permanent
1. Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
2. Connection URL: The connection URL for the mysql database is
jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database,
localhost is the server name on which mysql is running, we may also use IP address,
3306 is the port number and sonoo is the database name. We may use any database, in
such case, you need to replace the sonoo with your database name.
3. Username: The default username for the mysql database is root.
4. Password: Password is given by the user at the time of installing the mysql database. In
this example, we are going to use root as the password.
Let's first create a table in the mysql database, but before creating table, we need to create
database first.
1. create database sonoo;
2. use sonoo;
3. create table emp(id int(10),name varchar(40),age int(3));
1. import java.sql.*;
2. class MysqlCon{
3. public static void main(String args[]){
4. try{
5. Class.forName("com.mysql.jdbc.Driver");
6.
7. Connection con=DriverManager.getConnection(
8. "jdbc:mysql://localhost:3306/sonoo","root","root");
9.
10. //here sonoo is database name, root is username and password
11.
12. Statement stmt=con.createStatement();
13.
14. ResultSet rs=stmt.executeQuery("select * from emp");
15.
16. while(rs.next())
17. System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
18.
19. con.close();
20.
21. }catch(Exception e){ System.out.println(e);}
22.
23. }
24. }
The above example will fetch all the records of emp table.
To connect java application with the mysql database mysqlconnector.jar file is required to be
loaded.
download the jar file mysql-connector.jar
Two ways to load the jar file:
2) set classpath:
There are two ways to set the classpath:
● temporary
● permament
Java is mostly used with Oracle, mysql, or DB2 database. So you can learn this topic only for
knowledge.
1. import java.sql.*;
2. class Test{
3. public static void main(String ar[]){
4. try{
5. String database="student.mdb";//Here database exists in the current directory
6.
7. String url="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};
8. DBQ=" + database + ";DriverID=22;READONLY=true";
9.
10. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
11. Connection c=DriverManager.getConnection(url);
12. Statement st=c.createStatement();
13. ResultSet rs=st.executeQuery("select * from login");
14.
15. while(rs.next()){
16. System.out.println(rs.getString(1));
17. }
18.
19. }catch(Exception ee){System.out.println(ee);}
20.
21. }}
1. import java.sql.*;
2. class Test{
3. public static void main(String ar[]){
4. try{
5. String url="jdbc:odbc:mydsn";
6. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
7. Connection c=DriverManager.getConnection(url);
8. Statement st=c.createStatement();
9. ResultSet rs=st.executeQuery("select * from login");
10.
11. while(rs.next()){
12. System.out.println(rs.getString(1));
13. }
14.
15. }catch(Exception ee){System.out.println(ee);}
16.
17. }}
DriverManager class:
The DriverManager class acts as an interface between user and drivers. It keeps track of the
drivers that are available and handles establishing a connection between a database and the
appropriate driver. The DriverManager class maintains a list of Driver classes that have
registered themselves by calling the method DriverManager.registerDriver().
Connection interface:
A Connection is the session between java application and database. The Connection interface is a
factory of Statement, PreparedStatement, and DatabaseMetaData i.e. object of Connection can be
used to get the object of Statement and DatabaseMetaData. The Connection interface provide
many methods for transaction management like commit(),rollback() etc.
Statement interface
The Statement interface provides methods to execute queries with the database. The statement
interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet.
1. import java.sql.*;
2. class FetchRecord{
3. public static void main(String args[])throws Exception{
4.
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","
system","oracle");
7. Statement stmt=con.createStatement();
8.
9. //stmt.executeUpdate("insert into emp765 values(33,'Irfan',50000)");
10. //int result=stmt.executeUpdate("update emp765 set name='Vimal',salary=10000 wher
e id=33");
11. int result=stmt.executeUpdate("delete from emp765 where id=33");
12.
13. System.out.println(result+" records affected");
14. con.close();
15. }}
ResultSet interface
The object of ResultSet maintains a cursor pointing to a particular row of data. Initially, cursor
points to before the first row.
By default, ResultSet object can be moved forward only and it is not updatable.
But we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int)
method as well as we can make this object as updatable by:
1. import java.sql.*;
2. class FetchRecord{
3. public static void main(String args[])throws Exception{
4.
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","
system","oracle");
7. Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CO
NCUR_UPDATABLE);
8. ResultSet rs=stmt.executeQuery("select * from emp765");
9.
10. //getting the record of 3rd row
11. rs.absolute(3);
12. System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
13.
14. con.close();
15. }}
PreparedStatement interface
The PreparedStatement interface is a subinterface of Statement. It is used to execute
parameterized query.
Let's see the example of parameterized query:
As you can see, we are passing parameter (?) for the values. Its value will be set by calling the
setter methods of PreparedStatement.
1. import java.sql.*;
2. class InsertPrepared{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6.
7. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","
system","oracle");
8.
9. PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
10. stmt.setInt(1,101);//1 specifies the first parameter in the query
11. stmt.setString(2,"Ratan");
12.
13. int i=stmt.executeUpdate();
14. System.out.println(i+" records inserted");
15.
16. con.close();
17.
18. }catch(Exception e){ System.out.println(e);}
19.
20. }
21. }
1. import java.sql.*;
2. import java.io.*;
3. class RS{
4. public static void main(String args[])throws Exception{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","
system","oracle");
7.
8. PreparedStatement ps=con.prepareStatement("insert into emp130 values(?,?,?)");
9.
10. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
11.
12. do{
13. System.out.println("enter id:");
14. int id=Integer.parseInt(br.readLine());
15. System.out.println("enter name:");
16. String name=br.readLine();
17. System.out.println("enter salary:");
18. float salary=Float.parseFloat(br.readLine());
19.
20. ps.setInt(1,id);
21. ps.setString(2,name);
22. ps.setFloat(3,salary);
23. int i=ps.executeUpdate();
24. System.out.println(i+" records affected");
25.
26. System.out.println("Do you want to continue: y/n");
27. String s=br.readLine();
28. if(s.startsWith("n")){
29. break;
30. }
31. }while(true);
32.
33. con.close();
34. }}
ResultSetMetaData Interface
The metadata means data about data i.e. we can get further information from the data.
If you have to get metadata of a table like total number of column, column name, column type
etc. , ResultSetMetaData interface is useful because it provides methods to get metadata from the
ResultSet object.
1. import java.sql.*;
2. class Rsmd{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6.
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10. PreparedStatement ps=con.prepareStatement("select * from emp");
11. ResultSet rs=ps.executeQuery();
12.
13. ResultSetMetaData rsmd=rs.getMetaData();
14.
15. System.out.println("Total columns: "+rsmd.getColumnCount());
16. System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
17. System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1))
;
18.
19. con.close();
20.
21. }catch(Exception e){ System.out.println(e);}
22.
23. }
24. }
Output:Total columns: 2
Column Name of 1st column: ID
Column Type Name of 1st column: NUMBER
DatabaseMetaData interface:
DatabaseMetaData interface provides methods to get meta data of a database such as database
product name, database product version, driver name, name of total number of tables, name of
total number of views etc.
1. import java.sql.*;
2. class Dbmd{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6.
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10. DatabaseMetaData dbmd=con.getMetaData();
11.
12. System.out.println("Driver Name: "+dbmd.getDriverName());
13. System.out.println("Driver Version: "+dbmd.getDriverVersion());
14. System.out.println("UserName: "+dbmd.getUserName());
15. System.out.println("Database Product Name: "+dbmd.getDatabaseProductName());
16. System.out.println("Database Product Version: "+dbmd.getDatabaseProductVersion());
17.
18. con.close();
19.
20. }catch(Exception e){ System.out.println(e);}
21.
22. }
23. }
1. import java.sql.*;
2. class Dbmd2{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6.
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10. DatabaseMetaData dbmd=con.getMetaData();
11. String table[]={"TABLE"};
12. ResultSet rs=dbmd.getTables(null,null,null,table);
13.
14. while(rs.next()){
15. System.out.println(rs.getString(3));
16. }
17.
18. con.close();
19.
20. }catch(Exception e){ System.out.println(e);}
21.
22. }
23. }
1. import java.sql.*;
2. class Dbmd3{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6.
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10. DatabaseMetaData dbmd=con.getMetaData();
11. String table[]={"VIEW"};
12. ResultSet rs=dbmd.getTables(null,null,null,table);
13.
14. while(rs.next()){
15. System.out.println(rs.getString(3));
16. }
17.
18. con.close();
19.
20. }catch(Exception e){ System.out.println(e);}
21.
22. }
23. }
For storing image into the database, BLOB (Binary Large Object) datatype is used in the table.
For example:
Let's write the jdbc code to store the image in the database. Here we are using d:\\d.jpg for the
location of image. You can change it according to the image location.
1. import java.sql.*;
2. import java.io.*;
3. public class InsertImage {
4. public static void main(String[] args) {
5. try{
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10. PreparedStatement ps=con.prepareStatement("insert into imgtable values(?,?)");
11. ps.setString(1,"sonoo");
12.
13. FileInputStream fin=new FileInputStream("d:\\g.jpg");
14. ps.setBinaryStream(2,fin,fin.available());
15. int i=ps.executeUpdate();
16. System.out.println(i+" records affected");
17.
18. con.close();
19. }catch (Exception e) {e.printStackTrace();}
20. }
21. }
If you see the table, record is stored in the database but image will not be shown. To do so, you
need to retrieve the image from the database which we are covering in the next page.
Now let's write the code to retrieve the image from the database and write it into the directory so
that it can be displayed.
In AWT, it can be displayed by the Toolkit class. In servlet, jsp, or html it can be displayed by
the img tag.
1. import java.sql.*;
2. import java.io.*;
3. public class RetrieveImage {
4. public static void main(String[] args) {
5. try{
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10. PreparedStatement ps=con.prepareStatement("select * from imgtable");
11. ResultSet rs=ps.executeQuery();
12. if(rs.next()){//now on 1st row
13.
14. Blob b=rs.getBlob(2);//2 means 2nd column data
15. byte barr[]=b.getBytes(1,(int)b.length());//1 means first image
16.
17. FileOutputStream fout=new FileOutputStream("d:\\sonoo.jpg");
18. fout.write(barr);
19.
20. fout.close();
21. }//end of if
22. System.out.println("ok");
23.
24. con.close();
25. }catch (Exception e) {e.printStackTrace(); }
26. }
27. }
Syntax:
1) public void setBinaryStream(int paramIndex,InputStream stream)throws SQLException
2) public void setBinaryStream(int paramIndex,InputStream stream,long length)throws
SQLException
For storing file into the database, CLOB (Character Large Object) datatype is used in the table.
For example:
The example to retrieve the file from the Oracle database is given below.
1. import java.io.*;
2. import java.sql.*;
3.
4. public class RetrieveFile {
5. public static void main(String[] args) {
6. try{
7. Class.forName("oracle.jdbc.driver.OracleDriver");
8. Connection con=DriverManager.getConnection(
9. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
10.
11. PreparedStatement ps=con.prepareStatement("select * from filetable");
12. ResultSet rs=ps.executeQuery();
13. rs.next();//now on 1st row
14.
15. Clob c=rs.getClob(2);
16. Reader r=c.getCharacterStream();
17.
18. FileWriter fw=new FileWriter("d:\\retrivefile.txt");
19.
20. int i;
21. while((i=r.read())!=-1)
22. fw.write((char)i);
23.
24. fw.close();
25. con.close();
26.
27. System.out.println("success");
28. }catch (Exception e) {e.printStackTrace(); }
29. }
30. }
CallableStatement Interface
To call the stored procedures and functions, CallableStatement interface is used.
We can have business logic on the database by the use of stored procedures and functions that
will make the performance better because these are precompiled.
Suppose you need the get the age of the employee based on the date of birth, you may create a
function that receives date as the input and returns age of the employee as the output.
In this example, we are going to call the stored procedure INSERTR that receives id and name as
the parameter and inserts it into the table user420. Note that you need to create the user420 table
as well to run this application.
1. import java.sql.*;
2. public class Proc {
3. public static void main(String[] args) throws Exception{
4.
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection con=DriverManager.getConnection(
7. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
8.
9. CallableStatement stmt=con.prepareCall("{call insertR(?,?)}");
10. stmt.setInt(1,1011);
11. stmt.setString(2,"Amit");
12. stmt.execute();
13.
14. System.out.println("success");
15. }
16. }
Now check the table in the database, value is inserted in the user420 table.
1. import java.sql.*;
2.
3. public class FuncSum {
4. public static void main(String[] args) throws Exception{
5.
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10. CallableStatement stmt=con.prepareCall("{?= call sum4(?,?)}");
11. stmt.setInt(2,10);
12. stmt.setInt(3,43);
13. stmt.registerOutParameter(1,Types.INTEGER);
14. stmt.execute();
15.
16. System.out.println(stmt.getInt(1));
17.
18. }
19. }
Output: 53
1. import java.sql.*;
2. class FetchRecords{
3. public static void main(String args[])throws Exception{
4. Class.forName("oracle.jdbc.driver.OracleDriver");
5. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","
system","oracle");
6. con.setAutoCommit(false);
7.
8. Statement stmt=con.createStatement();
9. stmt.executeUpdate("insert into user420 values(190,'abhi',40000)");
10. stmt.executeUpdate("insert into user420 values(191,'umesh',50000)");
11.
12. con.commit();
13. con.close();
14. }}
If you see the table emp400, you will see that 2 records has been added.
1. import java.sql.*;
2. import java.io.*;
3. class TM{
4. public static void main(String args[]){
5. try{
6.
7. Class.forName("oracle.jdbc.driver.OracleDriver");
8. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","
system","oracle");
9. con.setAutoCommit(false);
10.
11. PreparedStatement ps=con.prepareStatement("insert into user420 values(?,?,?)");
12.
13. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
14. while(true){
15.
16. System.out.println("enter id");
17. String s1=br.readLine();
18. int id=Integer.parseInt(s1);
19.
20. System.out.println("enter name");
21. String name=br.readLine();
22.
23. System.out.println("enter salary");
24. String s3=br.readLine();
25. int salary=Integer.parseInt(s3);
26.
27. ps.setInt(1,id);
28. ps.setString(2,name);
29. ps.setInt(3,salary);
30. ps.executeUpdate();
31.
32. System.out.println("commit/rollback");
33. String answer=br.readLine();
34. if(answer.equals("commit")){
35. con.commit();
36. }
37. if(answer.equals("rollback")){
38. con.rollback();
39. }
40.
41.
42. System.out.println("Want to add more records y/n");
43. String ans=br.readLine();
44. if(ans.equals("n")){
45. break;
46. }
47.
48. }
49. con.commit();
50. System.out.println("record successfully saved");
51.
52. con.close();//before closing connection commit() is called
53. }catch(Exception e){System.out.println(e);}
54.
55. }}
It will ask to add more records until you press n. If you press n, transaction is committed.
If you see the table user420, two records has been added.
1. import java.sql.*;
2. import java.io.*;
3. class BP{
4. public static void main(String args[]){
5. try{
6.
7. Class.forName("oracle.jdbc.driver.OracleDriver");
8. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","
system","oracle");
9.
10. PreparedStatement ps=con.prepareStatement("insert into user420 values(?,?,?)");
11.
12. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
13. while(true){
14.
15. System.out.println("enter id");
16. String s1=br.readLine();
17. int id=Integer.parseInt(s1);
18.
19. System.out.println("enter name");
20. String name=br.readLine();
21.
22. System.out.println("enter salary");
23. String s3=br.readLine();
24. int salary=Integer.parseInt(s3);
25.
26. ps.setInt(1,id);
27. ps.setString(2,name);
28. ps.setInt(3,salary);
29.
30. ps.addBatch();
31. System.out.println("Want to add more records y/n");
32. String ans=br.readLine();
33. if(ans.equals("n")){
34. break;
35. }
36.
37. }
38. ps.executeBatch();
39.
40. System.out.println("record successfully saved");
41.
42. con.close();
43. }catch(Exception e){System.out.println(e);}
44.
45. }}
It will add the queries into the batch until user press n. Finally it executes the batch. Thus all the
added queries will be fired.
JDBC RowSet
The instance of RowSet is the java bean component because it has properties and java bean
notification mechanism. It is introduced since JDK 5.
It is the wrapper of ResultSet. It holds tabular data like ResultSet but it is easy and flexible to
use.
The implementation classes of RowSet interface are as follows:
● JdbcRowSet
● CachedRowSet
● WebRowSet
● JoinRowSet
● FilteredRowSet
Advantage of RowSet
The advantages of using RowSet are given below:
1. import java.sql.Connection;
2. import java.sql.DriverManager;
3. import java.sql.ResultSet;
4. import java.sql.Statement;
5. import javax.sql.RowSetEvent;
6. import javax.sql.RowSetListener;
7. import javax.sql.rowset.JdbcRowSet;
8. import javax.sql.rowset.RowSetProvider;
9.
10. public class RowSetExample {
11. public static void main(String[] args) throws Exception {
12. Class.forName("oracle.jdbc.driver.OracleDriver");
13.
14. //Creating and Executing RowSet
15. JdbcRowSet rowSet = RowSetProvider.newFactory().createJdbcRowSet();
16. rowSet.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
17. rowSet.setUsername("system");
18. rowSet.setPassword("oracle");
19.
20. rowSet.setCommand("select * from emp400");
21. rowSet.execute();
22.
23. while (rowSet.next()) {
24. // Generating cursor Moved event
25. System.out.println("Id: " + rowSet.getString(1));
26. System.out.println("Name: " + rowSet.getString(2));
27. System.out.println("Salary: " + rowSet.getString(3));
28. }
29.
30. }
31. }
1. import java.sql.Connection;
2. import java.sql.DriverManager;
3. import java.sql.ResultSet;
4. import java.sql.Statement;
5. import javax.sql.RowSetEvent;
6. import javax.sql.RowSetListener;
7. import javax.sql.rowset.JdbcRowSet;
8. import javax.sql.rowset.RowSetProvider;
9.
10. public class RowSetExample {
11. public static void main(String[] args) throws Exception {
12. Class.forName("oracle.jdbc.driver.OracleDriver");
13.
14. //Creating and Executing RowSet
15. JdbcRowSet rowSet = RowSetProvider.newFactory().createJdbcRowSet();
16. rowSet.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
17. rowSet.setUsername("system");
18. rowSet.setPassword("oracle");
19.
20. rowSet.setCommand("select * from emp400");
21. rowSet.execute();
22.
23. //Adding Listener and moving RowSet
24. rowSet.addRowSetListener(new MyListener());
25.
26. while (rowSet.next()) {
27. // Generating cursor Moved event
28. System.out.println("Id: " + rowSet.getString(1));
29. System.out.println("Name: " + rowSet.getString(2));
30. System.out.println("Salary: " + rowSet.getString(3));
31. }
32.
33. }
34. }
35.
36. class MyListener implements RowSetListener {
37. public void cursorMoved(RowSetEvent event) {
38. System.out.println("Cursor Moved...");
39. }
40. public void rowChanged(RowSetEvent event) {
41. System.out.println("Cursor Changed...");
42. }
43. public void rowSetChanged(RowSetEvent event) {
44. System.out.println("RowSet changed...");
45. }
46. }
● Jdbc RowSet We have done the great discussion on JdbcRowSet in the previous page.
● Savepoint in transaction management Now you are able to create, rollback and release
the savepoint by Connection.setSavepoint(), Connection.rollback(Savepoint svpt) and
Connection.releaseSavepoint(Savepoint svpt) methods.
● Statement and ResultSet Caching for Connection Pooling Now you are able to reuse the
statement and result set because jdbc 3 provides you the facility of statement caching
and result set caching.
● Switching between Global and Local Transactions
● Retrieval of auto generated keys Now you are able to get the auto generated keys by
the method getGeneratedKeys().
● Automatic Loading of Driver class You don't need to write Class.forName() now because
it is loaded bydefault since jdbc4.
● Subclasses of SQLException Jdbc 4 provides new subclasses of SQLException class for
better readability and handling.
● New methods There are many new methods introduced in Connection,
PreparedStatement, CallableStatement, ResultSet etc.
● Improved DataSource Now data source implementation is improved.
● Event Handling support in Statement for Connection Pooling Now Connection Pooling
can listen statement error and statement closing events.
Do You Know ?
1. How to create generic class and generic method in java ?
2. What is annotation and how to create custom annotation ?
3. What is the advantage of assertion and where we should not use it ?
4. What is variable argument and what rules are defined for variable argument ?
5. What is the difference between import and static import ?
6. How autoboxing is applied in method overloading. Which concept beats autoboxing ?
7. What is enum type and how to specify specific value to the enum constants ?
J2SE 4 Features
The important feature of J2SE 4 is assertions. It is used for testing.
● Assertion (Java 4)
J2SE 5 Features
The important features of J2SE 5 are generics and assertions. Others are auto-boxing, enum, var-
args, static import, for-each loop (enhanced for loop etc.
JavaSE 7 Features
The important features of JavaSE 7 are try with resource, catching multiple exceptions etc.
Assertion:
Assertion is a statement in java. It can be used to test your assumptions about the program.
While executing assertion, it is believed to be true. If it fails, JVM will throw an error named
AssertionError. It is mainly used for testing purpose.
Advantage of Assertion:
It provides an effective way to detect and correct programming errors.
1. assert expression;
1. import java.util.Scanner;
2.
3. class AssertionExample{
4. public static void main( String args[] ){
5.
6. Scanner scanner = new Scanner( System.in );
7. System.out.print("Enter ur age ");
8.
9. int value = scanner.nextInt();
10. assert value>=18:" Not valid";
11.
12. System.out.println("value is "+value);
13. }
14. }
15.
16.
If you use assertion, It will not run simply because assertion is disabled by default. To enable the
assertion, -ea or -enableassertions switch of java must be used.
Compile it by: javac AssertionExample.java
Run it by: java -ea AssertionExample
Output: Enter ur age 11
Exception in thread "main" java.lang.AssertionError: Not valid
1. According to Sun Specification, assertion should not be used to check arguments in the
public methods because it should result in appropriate runtime exception e.g.
IllegalArgumentException, NullPointerException etc.
2. Do not use assertion, if you don't want any error in any situation.
1.
2. class ForEachExample1{
3. public static void main(String args[]){
4. int arr[]={12,13,14,44};
5.
6. for(int i:arr){
7. System.out.println(i);
8. }
9.
10. }
11. }
12.
Output:12
13
14
44
1. import java.util.*;
2. class ForEachExample2{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();
5. list.add("vimal");
6. list.add("sonoo");
7. list.add("ratan");
8.
9. for(String s:list){
10. System.out.println(s);
11. }
12.
13. }
14. }
15.
Output:vimal
sonoo
ratan
Advantage of Varargs:
We don't have to provide overloaded methods so less code.
Syntax of varargs:
The varargs uses ellipsis i.e. three dots after the data type. Syntax is as follows:
1.
2. class VarargsExample1{
3.
4. static void display(String... values){
5. System.out.println("display method invoked ");
6. }
7.
8. public static void main(String args[]){
9.
10. display();//zero argument
11. display("my","name","is","varargs");//four arguments
12. }
13. }
14.
1.
2. class VarargsExample2{
3.
4. static void display(String... values){
5. System.out.println("display method invoked ");
6. for(String s:values){
7. System.out.println(s);
8. }
9. }
10.
11. public static void main(String args[]){
12.
13. display();//zero argument
14. display("hello");//one argument
15. display("my","name","is","varargs");//four arguments
16. }
17. }
18.
1.
2. void method(String... a, int... b){}//Compile time error
3.
4. void method(int... a, String b){}//Compile time error
5.
1.
2. class VarargsExample3{
3.
4. static void display(int num, String... values){
5. System.out.println("number is "+num);
6. for(String s:values){
7. System.out.println(s);
8. }
9. }
10.
11. public static void main(String args[]){
12.
13. display(500,"hello");//one argument
14. display(1000,"my","name","is","varargs");//four arguments
15. }
16. }
17.
Output:number is 500
hello
number is 1000
my
name
is
varargs
Static Import:
The static import feature of Java 5 facilitate the java programmer to access any static member of
a class directly. There is no need to qualify it by the class name.
● Less coding is required if you have access any static member of a class oftenly.
● If you overuse the static import feature, it makes the program unreadable and
unmaintainable.
Simple Example of static import
Output:Hello
Java
1.
2. class BoxingExample1{
3. public static void main(String args[]){
4. int a=50;
5. Integer a2=new Integer(a);//Boxing
6.
7. Integer a3=5;//Boxing
8.
9. System.out.println(a2+" "+a3);
10. }
11. }
12.
Output:50 5
1.
2. class UnboxingExample1{
3. public static void main(String args[]){
4. Integer i=new Integer(50);
5. int a=i;
6.
7. System.out.println(a);
8. }
9. }
10.
Output:50
Output:int
Output:Integer
Java Enum
Enum in java is a data type that contains fixed set of constants.
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST)
etc. The java enum constants are static and final implicitly. It is available from JDK 1.5.
Java Enums can be thought of as classes that have fixed set of constants.
1. class EnumExample1{
2. public enum Season { WINTER, SPRING, SUMMER, FALL }
3.
4. public static void main(String[] args) {
5. for (Season s : Season.values())
6. System.out.println(s);
7.
8. }}
Output:WINTER
SPRING
SUMMER
FALL
Internal code generated by the compiler for the above example of enum type
The java compiler internally creates a static and final class that extends the Enum class as shown
in the below example:
1. class EnumExample3{
2. enum Season { WINTER, SPRING, SUMMER, FALL; }//semicolon(;) is optional here
3. public static void main(String[] args) {
4. Season s=Season.WINTER;//enum type is required to access WINTER
5. System.out.println(s);
6. }}
Output:WINTER
1. class EnumExample4{
2. enum Season{
3. WINTER(5), SPRING(10), SUMMER(15), FALL(20);
4.
5. private int value;
6. private Season(int value){
7. this.value=value;
8. }
9. }
10. public static void main(String args[]){
11. for (Season s : Season.values())
12. System.out.println(s+" "+s.value);
13.
14. }}
15.
Output:WINTER 5
SPRING 10
SUMMER 15
FALL 20
Constructor of enum type is private. If you don't declare private compiler
internally creates private constructor.
1. enum Season{
2. WINTER(10),SUMMER(20);
3. private int value;
4. Season(int value){
5. this.value=value;
6. }
7. }
Internal code generated by the compiler for the above example of enum type
1. class EnumExample5{
2. enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY}
Output:monday
Java Annotations
Java Annotation is a tag that represents the metadata i.e. attached with class, interface, methods
or fields to indicate some additional information which can be used by java compiler and JVM.
Annotations in java are used to provide additional information, so it is an alternative option for
XML and java marker interfaces.
First, we will learn some built-in annotations then we will move on creating and using custom
annotations.
Built-In Java Annotations
There are several built-in annotations in java. Some annotations are applied to java code and
some to other annotations.
● @Override
● @SuppressWarnings
● @Deprecated
● @Target
● @Retention
● @Inherited
● @Documented
@Override
@Override annotation assures that the subclass method is overriding the parent class method. If
it is not so, compile time error occurs.
Sometimes, we does the silly mistake such as spelling mistakes etc. So, it is better to mark
@Override annotation that provides assurity that method is overridden.
1. class Animal{
2. void eatSomething(){System.out.println("eating something");}
3. }
4.
5. class Dog extends Animal{
6. @Override
7. void eatsomething(){System.out.println("eating foods");}//should be eatSomething
8. }
9.
10. class TestAnnotation1{
11. public static void main(String args[]){
12. Animal a=new Dog();
13. a.eatSomething();
14. }}
@SuppressWarnings
@SuppressWarnings annotation: is used to suppress warnings issued by the compiler.
1. import java.util.*;
2. class TestAnnotation2{
3. @SuppressWarnings("unchecked")
4. public static void main(String args[]){
5. ArrayList list=new ArrayList();
6. list.add("sonoo");
7. list.add("vimal");
8. list.add("ratan");
9.
10. for(Object obj:list)
11. System.out.println(obj);
12.
13. }}
@Deprecated
@Deprecated annoation marks that this method is deprecated so compiler prints warning. It
informs user that it may be removed in the future versions. So, it is better not to use such
methods.
1. class A{
2. void m(){System.out.println("hello m");}
3.
4. @Deprecated
5. void n(){System.out.println("hello n");}
6. }
7.
8. class TestAnnotation3{
9. public static void main(String args[]){
10.
11. A a=new A();
12. a.n();
13. }}
At Compile Time:
Note: Test.java uses or overrides a deprecated API.
At Runtime:
hello n
Custom Annotation
To create and use custom java annotation, visit the next page.
1. @interface MyAnnotation{}
Types of Annotation
There are three types of annotations.
1. Marker Annotation
2. Single-Value Annotation
3. Multi-Value Annotation
1) Marker Annotation
An annotation that has no method, is called marker annotation. For example:
1. @interface MyAnnotation{}
2) Single-Value Annotation
An annotation that has one method, is called single-value annotation. For example:
1. @interface MyAnnotation{
2. int value();
3. }
1. @interface MyAnnotation{
2. int value() default 0;
3. }
1. @MyAnnotation(value=10)
3) Mulit-Value Annotation
An annotation that has more than one method, is called Multi-Value annotation. For example:
1. @interface MyAnnotation{
2. int value1();
3. String value2();
4. String value3();
5. }
6. }
1. @interface MyAnnotation{
2. int value1() default 1;
3. String value2() default "";
4. String value3() default "xyz";
5. }
1. @MyAnnotation(value1=10,value2="Arun Kumar",value3="Ghaziabad")
● @Target
● @Retention
● @Inherited
● @Documented
@Target
@Target tag is used to specify at which type, the annotation is used.
The java.lang.annotation.ElementType enum declares many constants to specify the type of
element where annotation is to be applied such as TYPE, METHOD, FIELD etc. Let's see the
constants of ElementType enum:
Element Types Where the annotation can be applied
TYPE class, interface or enumeration
FIELD fields
METHOD methods
CONSTRUCTOR constructors
LOCAL_VARIABLE local variables
ANNOTATION_TYPE annotation type
PARAMETER parameter
1. @Target(ElementType.TYPE)
2. @interface MyAnnotation{
3. int value1();
4. String value2();
5. }
Example to specify annoation for a class, methods or fields
@Retention
@Retention annotation is used to specify to what level annotation will be available.
RetentionPolicy Availability
refers to the source code, discarded during compilation. It will not be
RetentionPolicy.SOURCE
available in the compiled class.
refers to the .class file, available to java compiler but not to JVM . It is
RetentionPolicy.CLASS
included in the class file.
RetentionPolicy.RUNTIME refers to the runtime, available to java compiler and JVM .
1. @Retention(RetentionPolicy.RUNTIME)
2. @Target(ElementType.TYPE)
3. @interface MyAnnotation{
4. int value1();
5. String value2();
6. }
1. //Creating annotation
2. import java.lang.annotation.*;
3. import java.lang.reflect.*;
4.
5. @Retention(RetentionPolicy.RUNTIME)
6. @Target(ElementType.METHOD)
7. @interface MyAnnotation{
8. int value();
9. }
10.
11. //Applying annotation
12. class Hello{
13. @MyAnnotation(value=10)
14. public void sayHello(){System.out.println("hello annotation");}
15. }
16.
17. //Accessing annotation
18. class TestCustomAnnotation1{
19. public static void main(String args[])throws Exception{
20.
21. Hello h=new Hello();
22. Method m=h.getClass().getMethod("sayHello");
23.
24. MyAnnotation manno=m.getAnnotation(MyAnnotation.class);
25. System.out.println("value is: "+manno.value());
26. }}
Output:value is: 10
@Inherited
By default, annotations are not inherited to subclasses. The @Inherited annotation marks the
annotation to be inherited to subclasses.
1. @Inherited
2. @interface ForEveryone { }//Now it will be available to subclass also
3.
4. @interface ForEveryone { }
5. class Superclass{}
6.
7. class Subclass extends Superclass{}
@Documented
The @Documented Marks the annotation for inclusion in the documentation.
Generics in Java
The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects.
Before generics, we can store any type of objects in collection i.e. non-generic. Now generics,
forces the java programmer to store specific type of objects.
3) Compile-Time Checking: It is checked at compile time so problem will not occur at runtime.
The good programming strategy says it is far better to handle the problem at compile time than
runtime.
1. ClassOrInterface<Type>
Example to use Generics in java
1. ArrayList<String>
1. import java.util.*;
2. class TestGenerics1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();
5. list.add("rahul");
6. list.add("jai");
7. //list.add(32);//compile time error
8.
9. String s=list.get(1);//type casting is not required
10. System.out.println("element is: "+s);
11.
12. Iterator<String> itr=list.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. }
17. }
1. import java.util.*;
2. class TestGenerics2{
3. public static void main(String args[]){
4. Map<Integer,String> map=new HashMap<Integer,String>();
5. map.put(1,"vijay");
6. map.put(4,"umesh");
7. map.put(2,"ankit");
8.
9. //Now use Map.Entry for Set and Iterator
10. Set<Map.Entry<Integer,String>> set=map.entrySet();
11.
12. Iterator<Map.Entry<Integer,String>> itr=set.iterator();
13. while(itr.hasNext()){
14. Map.Entry e=itr.next();//no need to typecast
15. System.out.println(e.getKey()+" "+e.getValue());
16. }
17.
18. }}
Output:1 vijay
2 ankit
4 umesh
Generic class
A class that can refer to any type is known as generic class. Here, we are using T type parameter
to create the generic class of specific type.
Let’s see the simple example to create and use the generic class.
Creating generic class:
1. class MyGen<T>{
2. T obj;
3. void add(T obj){this.obj=obj;}
4. T get(){return obj;}
5. }
The T type indicates that it can refer to any type (like String, Integer, Employee etc.). The type
you specify for the class, will be used to store and retrieve the data.
Using generic class:
Let’s see the code to use the generic class.
1. class TestGenerics3{
2. public static void main(String args[]){
3. MyGen<Integer> m=new MyGen<Integer>();
4. m.add(2);
5. //m.add("vivek");//Compile time error
6. System.out.println(m.get());
7. }}
Output:2
Type Parameters
The type parameters naming conventions are important to learn generics thoroughly. The
commonly type parameters are as follows:
1. T - Type
2. E - Element
3. K - Key
4. N - Number
5. V - Value
Generic Method
Like generic class, we can create generic method that can accept any type of argument.
Let’s see a simple example of java generic method to print array elements. We are using here E
to denote the element.
1. import java.util.*;
2. abstract class Shape{
3. abstract void draw();
4. }
5. class Rectangle extends Shape{
6. void draw(){System.out.println("drawing rectangle");}
7. }
8. class Circle extends Shape{
9. void draw(){System.out.println("drawing circle");}
10. }
11.
12.
13. class GenericTest{
14. //creating a method that accepts only child class of Shape
15. public static void drawShapes(List<? extends Shape> lists){
16. for(Shape s:lists){
17. s.draw();//calling method of Shape class by child class instance
18. }
19. }
20. public static void main(String args[]){
21. List<Rectangle> list1=new ArrayList<Rectangle>();
22. list1.add(new Rectangle());
23.
24. List<Circle> list2=new ArrayList<Circle>();
25. list2.add(new Circle());
26. list2.add(new Circle());
27.
28. drawShapes(list1);
29. drawShapes(list2);
30. }}
drawing rectangle
drawing circle
drawing circle
The RMI (Remote Method Invocation) is an API that provides a mechanism to create distributed
application in java. The RMI allows an object to invoke methods on an object running in another
JVM.
The RMI provides remote communication between the applications using two objects stub and
skeleton.
stub
The stub is an object, acts as a gateway for the client side. All the outgoing requests are routed
through it. It resides at the client side and represents the remote object. When the caller invokes
method on the stub object, it does the following tasks:
In the Java 2 SDK, an stub protocol was introduced that eliminates the need for skeletons.
The RMI application have all these features, so it is called the distributed application.
RMI Example
In this example, we have followed all the 6 steps to create and run the rmi application. The client
application need only two files, remote interface and client application. In the rmi application,
both client and server interacts with the remote interface. The client application invokes methods
on the proxy object, RMI sends the request to the remote JVM. The return value is sent back to
the proxy object and then to the client application.
1. import java.rmi.*;
2. public interface Adder extends Remote{
3. public int add(int x,int y)throws RemoteException;
4. }
In case, you extend the UnicastRemoteObject class, you must define a constructor that declares
RemoteException.
1. import java.rmi.*;
2. import java.rmi.server.*;
3. public class AdderRemote extends UnicastRemoteObject implements Adder{
4. AdderRemote()throws RemoteException{
5. super();
6. }
7. public int add(int x,int y){return x+y;}
8. }
3) create the stub and skeleton objects using the rmic tool.
Next step is to create stub and skeleton objects using the rmi compiler. The rmic tool invokes the
RMI compiler and creates stub and skeleton objects.
1. rmic AdderRemote
1. rmiregistry 5000
5) Create and run the server application
Now rmi services need to be hosted in a server process. The Naming class provides methods to
get and store the remote object. The Naming class provides 5 methods.
In this example, we are binding the remote object by the name sonoo.
1. import java.rmi.*;
2. import java.rmi.registry.*;
3. public class MyServer{
4. public static void main(String args[]){
5. try{
6. Adder stub=new AdderRemote();
7. Naming.rebind("rmi://localhost:5000/sonoo",stub);
8. }catch(Exception e){System.out.println(e);}
9. }
10. }
1. import java.rmi.*;
2. public class MyClient{
3. public static void main(String args[]){
4. try{
5. Adder stub=(Adder)Naming.lookup("rmi://localhost:5000/sonoo");
6. System.out.println(stub.add(34,4));
7. }catch(Exception e){}
8. }
9. }
1. package com.java;
2. public class Customer implements java.io.Serializable{
3. private int acc_no;
4. private String firstname,lastname,email;
5. private float amount;
6. //getters and setters
7. }
1. package com.java;
2. import java.rmi.*;
3. import java.util.*;
4. interface Bank extends Remote{
5. public List<Customer> getCustomers()throws RemoteException;
6. }
1. package com.java;
2. import java.rmi.*;
3. import java.rmi.server.*;
4. import java.sql.*;
5. import java.util.*;
6. class BankImpl extends UnicastRemoteObject implements Bank{
7. BankImpl()throws RemoteException{}
8.
9. public List<Customer> getCustomers(){
10. List<Customer> list=new ArrayList<Customer>();
11. try{
12. Class.forName("oracle.jdbc.driver.OracleDriver");
13. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","
system","oracle");
14. PreparedStatement ps=con.prepareStatement("select * from customer400");
15. ResultSet rs=ps.executeQuery();
16.
17. while(rs.next()){
18. Customer c=new Customer();
19. c.setAcc_no(rs.getInt(1));
20. c.setFirstname(rs.getString(2));
21. c.setLastname(rs.getString(3));
22. c.setEmail(rs.getString(4));
23. c.setAmount(rs.getFloat(5));
24. list.add(c);
25. }
26.
27. con.close();
28. }catch(Exception e){System.out.println(e);}
29. return list;
30. }//end of getCustomers()
31. }
4) Compile the class rmic tool and start the registry service by rmiregistry tool
1. package com.java;
2. import java.rmi.*;
3. public class MyServer{
4. public static void main(String args[])throws Exception{
5. Remote r=new BankImpl();
6. Naming.rebind("rmi://localhost:6666/java",r);
7. }}
1. package com.java;
2. import java.util.*;
3. import java.rmi.*;
4. public class MyClient{
5. public static void main(String args[])throws Exception{
6. Bank b=(Bank)Naming.lookup("rmi://localhost:6666/java");
7.
8. List<Customer> list=b.getCustomers();
9. for(Customer c:list){
10. System.out.println(c.getAcc_no()+" "+c.getFirstname()+" "+c.getLastname()
11. +" "+c.getEmail()+" "+c.getAmount());
12. }
13.
14. }}
Internationalization and Localization in Java
1. Internationalization and Localization
2. Understanding the culturally dependent data
3. Locale class
4. Example of Local class that prints the informations of the default locale
5. Example of Local class that prints english in different languages
6. Example of Local class that print display language of many locales
Internationalization is also abbreviated as I18N because there are total 18 characters between
the first letter 'I' and the last letter 'N'.
Internationalization is a mechanism to create such an application that can be adapted to different
languages and regions.
Internationalization is one of the powerful concept of java if you are developing an application
and want to display messages, currencies, date, time etc. according to the specific region or
language.
Localization is also abbreviated as I10N because there are total 10 characters between the first
letter 'L' and last letter 'N'. Localization is the mechanism to create such an application that can
be adapted to a specific language and region by adding locale-specific text and component.
Do You Know ?
● Messages
● Dates
● Times
● Numbers
● Currencies
● Measurements
● Phone Numbers
● Postal Addresses
● Labels on GUI components etc.
1. Locale(String language)
2. Locale(String language, String country)
3. Locale(String language, String country, String variant)
Example of Local class that prints the informations of the default locale
In this example, we are displaying the informations of the default locale. If you want to get the
informations about any specific locale, comment the first line statement and uncomment the
second line statement in the main method.
1. import java.util.*;
2. public class LocaleExample {
3. public static void main(String[] args) {
4. Locale locale=Locale.getDefault();
5. //Locale locale=new Locale("fr","fr");//for the specific locale
6.
7. System.out.println(locale.getDisplayCountry());
8. System.out.println(locale.getDisplayLanguage());
9. System.out.println(locale.getDisplayName());
10. System.out.println(locale.getISO3Country());
11. System.out.println(locale.getISO3Language());
12. System.out.println(locale.getLanguage());
13. System.out.println(locale.getCountry());
14.
15. }
16. }
Output:United States
English
English (United States)
USA
eng
en
US
1. import java.util.*;
2. public class LocaleExample2 {
3. public static void main(String[] args) {
4. Locale enLocale = new Locale("en", "US");
5. Locale frLocale = new Locale("fr", "FR");
6. Locale esLocale = new Locale("es", "ES");
7. System.out.println("English language name (default): " +
8. enLocale.getDisplayLanguage());
9.
10. System.out.println("English language name in French: " +
11. enLocale.getDisplayLanguage(frLocale));
12. System.out.println("English language name in spanish: " +
13. enLocale.getDisplayLanguage(esLocale));
14. }
15.
16. }
Output:en_US: English
es_ES: espa?ol
it_IT: italiano
The ResourceBundle class is used to internationalize the messages. In other words, we can say
that it provides a mechanism to globalize the messages.
The hardcoded message is not considered good in terms of programming, because it differs from
one country to another. So we use the ResourceBundle class to globalize the massages. The
ResourceBundle class loads these informations from the properties file that contains the
messages.
Conventionally, the name of the properties file should be filename_languagecode_country code
for example MyMessage_en_US.properties.
Commonly used methods of ResourceBundle class
There are many methods in the ResourceBundle class. Let's see the commonly used methods of
the ResourceBundle class.
MessageBundle_en_US.properties
MessageBundle_in_ID.properties
InternationalizationDemo.java
1. import java.util.Locale;
2. import java.util.ResourceBundle;
3. public class InternationalizationDemo {
4. public static void main(String[] args) {
5.
6. ResourceBundle bundle = ResourceBundle.getBundle("MessageBundle", Locale.US);
7. System.out.println("Message in "+Locale.US +":"+bundle.getString("greeting"));
8.
9. //changing the default locale to indonasian
10. Locale.setDefault(new Locale("in", "ID"));
11. bundle = ResourceBundle.getBundle("MessageBundle");
12. System.out.println("Message in "+Locale.getDefault()+":"+bundle.getString("greeting")
);
13.
14. }
15. }
The format of the dates differ from one region to another that is why we internationalize the
dates.
We can internationalize the date by using the getDateInstance() method of the DateFormat
class. It receives the locale object as a parameter and returns the instance of the DateFormat
class.
● public static DateFormat getDateInstance(int style, Locale locale) returns the instance
of the DateFormat class for the specified style and locale. The style can be DEFAULT,
SHORT, LONG etc.
● public String format(Date date) returns the formatted and localized date as a string.
Output:01-Mar-2012 en_GB
Mar 1, 2012 en_US
1 mars 2012 fr_FR
The display format of the time differs from one region to another, so we need to internationalize
the time.
For internationalizing the time, the DateFormat class provides some useful methods.
The getTimeInstance() method of the DateFormat class returns the instance of the DateFormat
class for the specified style and locale.
Syntax of the getTimeInstance() method is given below:
Example of Internationalizing Time
In this example, we are displaying the current time for the specified locale. The format() method
of the DateFormat class receives date object and returns the formatted and localized time as a
string. Notice that the object of Date class prints date and time both.
1. import java.text.DateFormat;
2. import java.util.*;
3.
4. public class InternationalizingTime {
5.
6. static void printTime(Locale locale){
7. DateFormat formatter=DateFormat.getTimeInstance(DateFormat.DEFAULT,locale);
8. Date currentDate=new Date();
9. String time=formatter.format(currentDate);
10. System.out.println(time+" in locale "+locale);
11. }
12.
13. public static void main(String[] args) {
14. printTime(Locale.UK);
15. printTime(Locale.US);
16. printTime(Locale.FRANCE);
17. }
18. }
The representation of the numbers differ from one locale to another. Internationalizing the
numbers is good approach for the application that displays the informations according to the
locales.
The NumberFormat class is used to format the number according to the specific locale. To get
the instance of the NumberFormat class, we need to call either getInstance() or
getNumberInstance() methods.
Syntax of these methods is given below: