Java
Java
Java Tutorial
1. Java - What, Where and Why?
2. What is Java
3. Where Java is used
4. Java Applications
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.
1.
2.
3.
4.
5.
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
Test it Now
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:
1. Desktop Applications such as acrobat reader, media player, antivirus etc.
2. Web Applications such as irctc.co.in, javatpoint.com etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Game00s etc.
1) Standalone Application
It is also known as desktop application or window-based application. An application that
we need to install on every machine such as media player,antivirus etc. AWT and Swing
are used in java for creating standalone applications.
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.
Do You Know ?
History of Java
Features of Java
Program Internal
Unicode System
Operators
History of java
James Gosling
Currently, Java is used in internet programming, mobile devices, games, e-business
solutions etc. There are given the major points that describes the history of java.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java
language project in June 1991. The small team of sun engineers called Green Team.
2) Originally designed for small, embedded systems in electronic appliances like settop boxes.
3) Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
There are many java versions that has been released. Current stable release of Java
is Java SE 8.
1. JDK Alpha and Beta (1995)
2. JDK 1.0 (23rd Jan, 1996)
3. JDK 1.1 (19th Feb, 1997)
4. J2SE 1.2 (8th Dec, 1998)
5. J2SE 1.3 (8th May, 2000)
6. J2SE 1.4 (6th Feb, 2002)
7. J2SE 5.0 (30th Sep, 2004)
8. Java SE 6 (11th Dec, 2006)
9. Java SE 7 (28th July, 2011)
10. Java SE 8 (18th March, 2014)
Next TopicFeatures of Java
Features of Java
1. Features of Java
1.
Simple
2.
Object-Oriented
3.
Platform Independent
4.
secured
5.
Robust
6.
Architecture Neutral
7.
Portable
8.
High Performance
9.
Distributed
Multi-threaded
10.
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.
1. Simple
2. Object-Oriented
3. Platform independent
4. Secured
5. Robust
6. Architecture neutral
7. Portable
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed
OPSS-APRM-IHDD
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:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. 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:
1. Runtime Environment
2. 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
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.
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.
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++)
Architecture-neutral
There is no implementationdependent features e.g. size of primitive types is set.
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 multimedia, Web applications etc.
Next TopicSimple program of java
install the JDK if you don't have installed it, download the JDK and install it.
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
Test it Now
save this file as Simple.java
To compile:
javac Simple.java
To execute:
java Simple
Output:Hello Java
void is the return type of the method, it means it doesn't return any value.
String[] args is used for command line argument. We will learn it later.
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:
To compile:
javac Simple.java
To execute:
java Simple
1.
1.
2.
3.
1.
1.
2.
3.
4.
5.
1.
2.
3.
4.
5.
6.
7.
8.
class A{
static public void main(String... args){
System.out.println("hello java4");
}
};
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:
To compile:
javac Hard.java
To execute:
java Simple
2.
For Example:
set path=C:\Program Files\Java\jdk1.6.0_23\bin
Let's see it in the figure given below:
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
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.
page. Firstly, let's see the basic differences between the JDK, JRE and JVM.
JVM
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides
runtime environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms. JVM, JRE and JDK are
platform dependent because configuration of each OS differs. But, Java is platform
independent.
The JVM performs following main tasks:
Loads code
JRE
Verifies code
Executes code
JDK
JDK is an acronym for Java Development Kit. It physically exists. It contains JRE +
development tools.
What is JVM?
It is:
1. 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.
2. An implementation Its implementation is known as JRE (Java Runtime
Environment).
3. 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
Memory area
Register set
Garbage-collected heap
1) Classloader:
Classloader is a subsystem of JVM that is used to load class files.
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.
Next TopicVariable Datatype
Variable
Variable is name of reserved area allocated in memory.
1.
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.
We will have detailed learning of these variables in next chapters.
1.
2.
3.
4.
5.
6.
7.
}
}//end of class
Data Type
Default Value
Default size
Boolean
false
1 bit
Char
'\u0000'
2 byte
Byte
1 byte
Short
2 byte
Int
4 byte
Long
0L
8 byte
Float
0.0f
4 byte
Double
0.0d
8 byte
Unicode System
Unicode is a universal international standard character encoding that is capable of
representing most of the world's written languages.
ASCII (American Standard Code for Information Interchange) for the United
States.
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
Multiplicative
* / %
Additive
+ -
Shift
Relational
Equality
== !=
bitwise AND
&
bitwise exclusive OR
bitwise inclusive OR
logical AND
&&
logical OR
||
Ternary
? :
Assignment
Java Programs
Java programs are frequently asked in the interview. These programs can be asked from
control statements, array, string, oops etc. Let's see the list of java programs.
1) Fibonacci series
Write a java program to print fibonacci series without using recursion and using
recursion.
Input: 10
Output: 0 1 1 2 3 5 8 13 21 34
class FibonacciExample1{
public static void main(String args[])
{
int n1=0,n2=1,n3,i,count=10;
System.out.print(n1+" "+n2);//printing
for(i=2;i<count;++i)//loop
0 and 1
printed
8.
9.
10.
11.
12.
13.
14.
15.
{
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}
}}
Output:
0 1 1 2 3 5 8 13 21 34
class FibonacciExample2{
static int n1=0,n2=1,n3=0;
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
Output:
0 1 1 2 3 5 8 13 21 34
2) Prime number
Write a java program to check prime number.
Input: 44
Output: not prime number
Input: 7
Output: prime number
Note: 0 and 1 are not prime numbers. 2 is the only even prime number because all the
numbers can be divided by 2.
Let's see the prime number program in java. In this java program, we will take a number
variable and check whether the number is prime or not.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
class PrimeExample{
public static void main(String args[]){
int i, m=0,flag=0;
int n=17;//it is the number to be checked
m=n/2;
for(i=2;i<=m; i++){
if(n%i==0){
System.out.println("Number is not prime");
flag=1;
break;
}
}
if(flag==0)
System.out.println("Number is prime");
}
}
Output:
Number is prime
3) Palindrome number
Write a java program to check palindrome number.
Input: 329
Output: not palindrome number
Input: 12321
Output: palindrome number
Let's see the palindrome program in java. In this java program, we will get a number
variable and check whether number is palindrome or not.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
class PalindromeExample{
public static void main(String args[]){
int r,sum=0,temp;
int n=454;//It is the number variable to be checked for palindrome
temp=n;
while(n>0){
r=n%10; //getting remainder
sum=(sum*10)+r;
n=n/10;
}
if(temp==sum)
System.out.println("palindrome number ");
else
System.out.println("not palindrome");
}
}
Output:
palindrome
number
4) Factorial number
Write a java program to print factorial of a number.
Input: 5
Output: 120
Input: 6
Output: 720
1.
2.
4! = 4*3*2*1 = 24
5! = 5*4*3*2*1 = 120
Here, 4! is pronounced as "4 factorial", it is also called "4 bang" or "4 shriek".
The factorial is normally used in Combinations and Permutations (mathematics).
There are many ways to write the factorial program in java language. Let's see the 2
ways to write the factorial program in java.
o
class FactorialExample{
public static void main(String args[]){
int i,fact=1;
int number=5;//It is the number to calculate factorial
for(i=1;i<=number;i++){
fact=fact*i;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}
Output:
Factorial of 5 is: 120
class FactorialExample2{
static int factorial(int n){
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String args[]){
int i,fact=1;
int number=4;//It is the number to calculate factorial
fact = factorial(number);
System.out.println("Factorial of "+number+" is: "+fact);
13.
14.
}
}
Output:
Factorial of 4 is: 24
5) Armstrong number
Write a java program to check Armstrong number.
Input: 153
Output: Armstrong number
Input: 22
Output: not Armstrong number
153 = (1*1*1)+(5*5*5)+(3*3*3)
where:
(1*1*1)=1
(5*5*5)=125
(3*3*3)=27
So:
1+125+27=153
Let's try to understand why 371 is an Armstrong number.
1.
2.
3.
4.
5.
6.
7.
371 = (3*3*3)+(7*7*7)+(1*1*1)
where:
(3*3*3)= 27
(7*7*7)=343
(1*1*1)= 1
So:
27+343+1=371
Let's see the java program to check Armstrong Number.
1.
class ArmstrongExample{
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
Output:
armstrong number
2.
3.
Object means a real word entity such as pen, chair, table etc.
Object-Oriented Programming is a methodology or paradigm to design a program
using classes and objects. It simplifies the software development and maintenance by
providing some concepts:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
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
the fully encapsulated class because all the data
are private here.
bean is
members
3) OOPs provides ability to simulate real-world event much more effectively. We can
provide the solution of real word problem if we are using the Object-Oriented
Programming language.
Do You Know ?
Can we overload main method ?
Constructor returns a value but, what ?
Can we create a program without main method ?
What are the 6 ways to use this keyword ?
Why multiple inheritance is not supported in java ?
Why use aggregation ?
Can we override the static method ?
What is covariant return type ?
What are the three usage of super keyword?
Why use instance initializer block?
What is the usage of blank final variable ?
What is marker or tagged interface ?
What is runtime polymorphism or dynamic method dispatch ?
Encapsulation
Object Cloning
Next TopicNaming Convention in Java
By using standard Java naming conventions, you make your code easier to read for
yourself and for other programmers. Readability of Java program is very important. It
indicates that less time is spent to figure out what the code does.
Name
Convention
class name
should start with uppercase letter and be a noun e.g. String, Color, Button,
System, Thread etc.
interface
name
should start with uppercase letter and be an adjective e.g. Runnable, Remote,
ActionListener etc.
method name should start with lowercase letter and be a verb e.g. actionPerformed(), main(),
print(), println() etc.
variable name should start with lowercase letter e.g. firstName, orderNumber etc.
package
name
constants
name
Object in Java
2.
Class in Java
3.
4.
Method in Java
5.
6.
Annonymous Object
In this page, we will learn about java objects and classes. In object-oriented
programming technique, we design a program using objects and classes.
Object is the physical as well as logical entity where as class is the logical entity only.
Object in Java
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:
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 <class_name>{
data member;
method;
}
class Student1{
int id;//data member (also instance variable)
String name;//data member(also instance variable)
public static void main(String args[]){
Student1 s1=new Student1();//creating an object of Student
System.out.println(s1.id);
System.out.println(s1.name);
}
9.
}
Test it Now
Output: 0 null
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.
18.
19.
20.
21.
22.
23.
24.
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
Test it Now
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.
22.
}
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.
1.
class Calculation{
2.
3.
void fact(int n){
4.
int fact=1;
5.
for(int i=1;i<=n;i++){
6.
fact=fact*i;
7.
}
8.
System.out.println("factorial is "+fact);
9.
}
10.
11.
public static void main(String args[]){
12.
new Calculation().fact(5);//calling method with annonymous object
13.
}
14.
}
Output:Factorial is 120
/;4
682\1
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
int width;
void insert(int l,int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
public static void main(String args[]){
Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
r1.insert(11,5);
r2.insert(3,15);
}
}
r1.calculateArea();
r2.calculateArea();
Output:55
45
Next TopicMethod Overloading in java
2.
3.
4.
5.
6.
In java, Methood Overloading is not possible by changing the return type of the method.
class Calculation{
void sum(int a,int b){System.out.println(a+b);}
void sum(int a,int b,int c){System.out.println(a+b+c);}
public static void main(String args[]){
Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);
}
Test it Now
Output:30
40
class Calculation2{
void sum(int a,int b){System.out.println(a+b);}
void sum(double a,double b){System.out.println(a+b);}
4.
5.
6.
7.
8.
9.
10.
11.
Test it Now
Output:21.0
40
class Calculation3{
int sum(int a,int b){System.out.println(a+b);}
double sum(int a,int b){System.out.println(a+b);}
public static void main(String args[]){
Calculation3 obj=new Calculation3();
int result=obj.sum(20,20); //Compile Time Error
}
Test it Now
int result=obj.sum(20,20); //Here how can java determine which sum() method should
be called
class Overloading1{
public static void main(int a){
System.out.println(a);
}
public static void main(String args[]){
System.out.println("main() method invoked");
main(10);
}
10.
}
Test it Now
Output: main()method invoked
10
As displayed in the above diagram, byte can be promoted to short, int, long, float or
double. The short datatype can be promoted to int, long, float or double. The char
datatype can be promoted to int, long, float or double and so on.
class OverloadingCalculation1{
void sum(int a, long b){System.out.println(a+b);}
void sum(int a, int b ,int c){System.out.println(a+b+c);}
public static void main(String args[]){
OverloadingCalculation1 obj=new OverloadingCalculation1();
obj.sum(20,20);//now second int literal will be promoted to long
obj.sum(20,20,20);
}
}
Test it Now
Output:40
60
class OverloadingCalculation2{
void sum(int a,int b){System.out.println("int arg method invoked");}
void sum(long a,long b){System.out.println("long arg method invoked");}
Test it Now
class OverloadingCalculation3{
void sum(int a,long b){System.out.println("a method invoked");}
void sum(long a,int b){System.out.println("b method invoked");}
Test it Now
Output:Compile Time Error
One type is not de-promoted implicitly for example double cannot be depromoted
to any type implicitely.
Next Topicstatic keyword in java
Static variable
1.
Static variable
2.
Static variable
3.
Static variable
4.
5.
6.
Static method
7.
8.
9.
Static block
10.
1.
2.
3.
block
4.
nested class
The static variable can be used to refer the common property of all objects (that
is not unique for each object) e.g. company name of employees, college name of
students etc.
The static variable gets memory only once in class area at the time of class
loading.
class Student{
int rollno;
String name;
String college="ITS";
}
Suppose there are 500 students in my college, now all instance data members will get
memory each time when object is created. All student have its unique roll no and name
so instance data member is good. Here, college refers to the common property of all
objects. If we make it static, this field will get memory only once.
incremented, it won't reflect to other objects. So each objects will have the value 1 in
the count variable.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
class Counter{
int count=0;//will get memory when instance is created
Counter(){
count++;
System.out.println(count);
}
public static void main(String args[]){
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}
Test it Now
Output:1
1
1
If you apply static keyword with any method, it is known as static method.
o
A static method can be invoked without the need for creating an instance of a
class.
static method can access static data member and can change the value of it.
4.
5.
6.
7.
8.
9.
10.
11.
12.
class A{
int a=40;//non static
public static void main(String args[]){
System.out.println(a);
}
}
Test it Now
Output:Compile Time Error
class A2{
static{System.out.println("static block is invoked");}
public static void main(String args[]){
4.
5.
6.
System.out.println("Hello main");
}
}
Test it Now
Output:static block is invoked
Hello main
class A3{
static{
System.out.println("static block is invoked");
System.exit(0);
}
}
Test it Now
Output:static block is invoked (if not JDK7)
In JDK7 and above, output will be:
Output:Error: Main method not found in class A3, please define the main
method as:
public static void main(String[] args)
Next Topicthis keyword in java
this keyword
2.
1.
2.
3.
4.
5.
6.
3.
There can be a lot of usage of java this keyword. In java, this is a reference
variable that refers to the current object.
2.
3.
4.
5.
6.
this keyword can also be used to return the current class instance.
Suggestion: If you are beginner to java, lookup only two usage of this keyword.
Let's understand the problem if we don't use this keyword by the example given below:
class Student10{
int id;
String name;
Student10(int id, String name){
id = id;
name = name;
}
9.
10.
11.
12.
13.
14.
15.
16.
17.
}
}
Test it Now
Output111 Karan
222 Aryan
class Student12{
int id;
String name;
}
}
Test it Now
Output:111 Karan
222 Aryan
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
The this() constructor call should be used to reuse the constructor in the constructor. It
maintains the chain between the constructors i.e. it is used for constructor chaining.
Let's see the example given below that displays the actual use of this keyword.
class Student14{
int id;
String name;
String city;
Student14(int id,String name){
this.id = id;
this.name = name;
}
Student14(int id, String name, String city){
this(id, name);//now no need to initialize id and name
this.city=city;
}
void display(){System.out.println(id+" "+name+" "+city);}
public static void main(String args[]){
Student14 e1 = new Student14(111,"karan");
Student14 e2 = new Student14(222,"Aryan","delhi");
e1.display();
e2.display();
}
}
Test it Now
Output:111 Karan null
222 Aryan delhi
class Student15{
int id;
String name;
Student15(){System.out.println("default constructor is invoked");}
Student15(int id,String name){
id = id;
name = name;
this ();//must be the first statement
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student15 e1 = new Student15(111,"karan");
Student15 e2 = new Student15(222,"Aryan");
e1.display();
e2.display();
18.
19.
Test it Now
Output:Compile Time Error
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
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();
}
}
Test it Now
Output:method is invoked
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
}
void p(){
m(this);
}
Test it Now
Output:method is invoked
We can pass the this keyword in the constructor also. It is useful if we have to use one
object in multiple classes. Let's see the example:
class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}
class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
Test it Now
Output:10
class A5{
void m(){
System.out.println(this);//prints same reference ID
}
public static void main(String args[]){
A5 obj=new A5();
System.out.println(obj);//prints the reference ID
obj.m();
}
}
Test it Now
Output:A5@22b3ea59
A5@22b3ea59
Next TopicInheritance in java
Constructor in Java
1.
Types of constructors
1.
Default Constructor
2.
Parameterized Constructor
2.
Constructor Overloading
3.
4.
5.
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e.
provides
data for the object that is why it is known as constructor.
2.
Parameterized constructor
}
Test it Now
Output:
Bike is created
10.
11.
12.
13.
Test it Now
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.
Test it Now
Output:
111 Karan
222 Aryan
10.
11.
12.
13.
class Student5{
int id;
String name;
int age;
Student5(int i,String n){
id = i;
name = n;
}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
14.
15.
16.
17.
18.
19.
20.
21.
22.
Test it Now
Output:
111 Karan 0
222 Aryan 25
Java Constructor
Java Method
Constructor name must be same as the Method name may or may not be same as
class name.
class name.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
class Student6{
int id;
String name;
Student6(int i,String n){
id = i;
name = n;
}
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}
Test it Now
Output:
111 Karan
111 Karan
class Student7{
int id;
String name;
Student7(int i,String n){
id = i;
name = n;
}
Student7(){}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student7 s1 = new Student7(111,"Karan");
Student7 s2 = new Student7();
s2.id=s1.id;
s2.name=s1.name;
16.
17.
18.
19.
s1.display();
s2.display();
}
Test it Now
Output:
111 Karan
111 Karan
Inheritance in Java
1.
Inheritance
2.
Types of Inheritance
3.
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.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
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);
}
}
Test it Now
Programmer salary is:40000.0
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were
Public Static void main(String args[]){
C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Test it Now
Compile Time Error
Next TopicAggregation in java (HAS-A)
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,
email ID etc. It contains one more object named address, which contains its own
information such as city, state, country, zip code etc. as given below.
1.
2.
3.
4.
5.
6.
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.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
class Operation{
int square(int n){
return n*n;
}
}
class Circle{
Operation op;//aggregation
double pi=3.14;
}
double area(int radius){
op=new Operation();
int rsquare=op.square(radius);//code reusability (i.e. delegates the method call
).
return pi*rsquare;
}
public static void main(String args[]){
Circle c=new Circle();
double result=c.area(5);
System.out.println(result);
}
}
Test it Now
Output:78.5
Address.java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
}
}
Emp.java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
2.
3.
If subclass (child class) has the same method as declared in the parent class, it
is known as method overriding in java.
In other words, If subclass provides the specific implementation of the method that has
been provided by one of its parent class, it is known as method overriding.
2.
3.
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike extends Vehicle{
public static void main(String args[]){
Bike obj = new Bike();
obj.run();
}
}
Test it Now
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.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike2 extends Vehicle{
void run(){System.out.println("Bike is running safely");}
public static void main(String args[]){
Bike2 obj = new Bike2();
obj.run();
}
Test it Now
Output:Bike is running safely
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
class Bank{
int getRateOfInterest(){return 0;}
}
15.
class Test2{
16.
17.
18.
19.
20.
21.
22.
23.
24.
No.
Method Overloading
Method Overriding
1)
2)
3)
4)
5)
1.
2.
3.
4.
1.
2.
3.
4.
5.
6.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
}
Next TopicJava Stringc
Note: If you are beginner to java, skip this topic and return to it after OOPs concepts.
class A{
A get(){return this;}
}
class B1 extends A{
B1 get(){return this;}
void message(){System.out.println("welcome to covariant return type");}
public static void main(String args[]){
new B1().get().message();
}
}
Test it Now
Output:welcome to covariant return type
As you can see in the above example, the return type of the get() method of A class is A
but the return type of the get() method of B class is B. Both methods have different
return type but it is method overriding. This is known as covariant return type.
Next Topicsuper keyword in java
Whenever you create the instance of subclass, an instance of parent class is created
implicitly i.e. referred by super reference variable.
2.
3.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
}
}
Test it Now
Output:50
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.
class Vehicle{
Vehicle(){System.out.println("Vehicle
}
is created");}
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
class Person{
void message(){System.out.println("welcome");}
}
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
2.
3.
4.
5.
Que) What is the use of instance initializer block while we can directly
assign a value in instance data member? For example:
1.
2.
3.
class Bike{
int speed=100;
}
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
Let's see the simple example of instance initializer block the performs initialization.
class Bike7{
int speed;
Bike7(){System.out.println("speed is "+speed);}
{speed=100;}
public static void main(String args[]){
Bike7 b1=new Bike7();
Bike7 b2=new Bike7();
}
}
Test it Now
Output:speed is 100
speed is 100
There are three places in java where you can perform operations:
method
constructor
block
class Bike8{
int speed;
Bike8(){System.out.println("constructor is invoked");}
{System.out.println("instance initializer block invoked");}
public static void main(String args[]){
Bike8 b1=new Bike8();
Bike8 b2=new Bike8();
}
}
Test it Now
Output:instance initializer block invoked
constructor is invoked
instance initializer block invoked
constructor is invoked
In the above example, it seems that instance initializer block is firstly invoked but NO.
Instance intializer block is invoked at the time of object creation. The java compiler
copies the instance initializer block in the constructor after the first statement super().
So firstly, constructor is invoked. Let's understand it by the figure given below:
Note: The java compiler copies the code of instance initializer block in
every constructor.
3.
The instance initializer block is created when instance of the class is created.
The instance initializer block is invoked after the parent class constructor is
invoked (i.e. after super() constructor call).
The instance initializer block comes in the order in which they appear.
class A{
A(){
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
class A{
A(){
System.out.println("parent class constructor 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);
}
{System.out.println("instance initializer block is invoked");}
public static void main(String args[]){
B3 b1=new B3();
B3 b2=new B3(10);
}
}
Test it Now
Output:parent class constructor invoked
instance initializer block is invoked
child class constructor invoked
parent class constructor invoked
instance initializer block is invoked
child class constructor invoked 10
Final variable
2.
Final method
3.
Final class
4.
5.
6.
7.
Final parameter
8.
1.
variable
2.
method
3.
class
The final keyword can be applied with the variables, a final variable that have no value it
is called blank final variable or uninitialized final variable. It can be initialized in the
constructor only. The blank final variable can be static also which will be initialized in the
static block only. We will have detailed learning of these. Let's first learn the basics of
final keyword.
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
Test it Now
Output:Compile Time Error
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
Test it Now
Output:Compile Time Error
2.
3.
4.
5.
6.
7.
8.
9.
10.
class Bike{
final void run(){System.out.println("running...");}
}
class Honda2 extends Bike{
public static void main(String args[]){
new Honda2().run();
}
}
Test it Now
Output:running...
class Student{
int id;
String name;
final String PAN_CARD_NUMBER;
...
}
class Bike10{
final int speedlimit;//blank final variable
Bike10(){
speedlimit=70;
System.out.println(speedlimit);
}
public static void main(String args[]){
new Bike10();
}
}
Test it Now
Output:70
class A{
static final int data;//static blank final variable
static{ data=50;}
public static void main(String args[]){
System.out.println(A.data);
}
}
class Bike11{
int cube(final int n){
n=n+2;//can't be changed as n is final
n*n*n;
}
public static void main(String args[]){
Bike11 b=new Bike11();
b.cube(5);
}
}
Test it Now
Output:Compile Time Error
Polymorphism in Java
Polymorphism in java is a concept by which we can perform a single action by
different ways. Polymorphism is derived from 2 greek words: poly and morphs. The word
"poly" means many and "morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in java: compile time polymorphism and
runtime polymorphism. We can perform polymorphism in java by method overloading
and method overriding.
If you overload static method in java, it is the example of compile time polymorphism.
Here, we will focus on runtime polymorphism in java.
Upcasting
When reference variable of Parent class refers to the object of Child class, it is known as
upcasting. For example:
1.
2.
class A{}
class B extends A{}
1.
A a=new B();//upcasting
class Bike{
void run(){System.out.println("running");}
}
class Splender extends Bike{
void run(){System.out.println("running safely with 60km");}
Test it Now
Output:running safely with 60km.
class Bank{
int getRateOfInterest(){return 0;}
}
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
class ICICI extends Bank{
int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
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());
}
}
Test it Now
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
class Bike{
int speedlimit=90;
}
class Honda3 extends Bike{
int speedlimit=150;
public static void main(String args[]){
Bike obj=new Honda3();
9.
10.
System.out.println(obj.speedlimit);//90
Test it Now
Output:90
class Animal{
void eat(){System.out.println("eating");}
}
class Dog extends Animal{
void eat(){System.out.println("eating fruits");}
}
class BabyDog extends Dog{
void eat(){System.out.println("drinking milk");}
public static void main(String args[]){
Animal a1,a2,a3;
a1=new Animal();
a2=new Dog();
a3=new BabyDog();
a1.eat();
a2.eat();
a3.eat();
}
}
Test it Now
Output: eating
eating fruits
drinking Milk
class Animal{
void eat(){System.out.println("animal is eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("dog is eating...");}
}
class BabyDog1 extends Dog{
public static void main(String args[]){
Animal a=new BabyDog1();
a.eat();
}}
Test it Now
Output: Dog is eating
Since, BabyDog is not overriding the eat() method, so eat() method of Dog class is
invoked.
Next TopicStatic Binding and Dynamic Binding
2.
Understanding Type
Let's understand the type of instance.
int data=30;
Here data variable is a type of int.
class Dog{
public static void main(String args[]){
Dog d1;//Here d1 is a type of Dog
}
}
3.
4.
5.
6.
7.
static binding
When type of the object is determined at compiled time(by the compiler), it is known as
static binding.
If there is any private, final or static method in a class, there is static binding.
class Dog{
private void eat(){System.out.println("dog is eating...");}
public static void main(String args[]){
Dog d1=new Dog();
d1.eat();
}
}
Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.
class Animal{
void eat(){System.out.println("animal is eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("dog is eating...");}
public static void main(String args[]){
Animal a=new Dog();
a.eat();
}
}
Test it Now
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.
Next Topic Downcasting and instanceof operator
Java instanceof
1.
java instanceof
2.
3.
Applying the instanceof operator with a variable the have null value
4.
5.
class Simple1{
public static void main(String args[]){
Simple1 s=new Simple1();
System.out.println(s instanceof Simple);//true
}
}
Test it Now
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.
class Animal{}
class Dog1 extends Animal{//Dog inherits Animal
public static void main(String args[]){
Dog1 d=new Dog1();
System.out.println(d instanceof Animal);//true
}
}
Test it Now
Output:true
class Dog2{
public static void main(String args[]){
Dog2 d=null;
System.out.println(d instanceof Dog2);//false
}
}
Test it Now
Output: false
1.
2.
class Animal { }
class Dog3 extends Animal {
static void method(Animal a) {
if(a instanceof Dog3){
Dog3 d=(Dog3)a;//downcasting
System.out.println("ok downcasting performed");
}
}
public static void main (String [] args) {
Animal a=new Dog3();
Dog3.method(a);
14.
15.
16.
}
}
Test it Now
Output:ok downcasting performed
class Animal { }
class Dog4 extends Animal {
static void method(Animal a) {
Dog4 d=(Dog4)a;//downcasting
System.out.println("ok downcasting performed");
}
public static void main (String [] args) {
Animal a=new Dog4();
Dog4.method(a);
}
}
Test it Now
Output:ok downcasting performed
Let's take closer look at this, actual object that is referred by a, is an object of Dog class.
So if we downcast it, it is fine. But what will happen if we write:
1.
2.
3.
interface Printable{}
class A implements Printable{
public void a(){System.out.println("a method");}
}
class B implements Printable{
public void b(){System.out.println("b method");}
}
class Call{
void invoke(Printable p){//upcasting
if(p instanceof A){
A a=(A)p;//Downcasting
a.a();
}
if(p instanceof B){
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
B b=(B)p;//Downcasting
b.b();
}
}
}//end of Call class
class Test4{
public static void main(String args[]){
Printable p=new B();
Call c=new Call();
c.invoke(p);
}
}
Test it Now
Output: b method
Next TopicAbstract class in java
2.
Interface (100%)
abstract method
A method that is declared as abstract and does not have implementation is known as
abstract method.
In this example, if you create the instance of Rectangle class, draw() method of
Rectangle class will be invoked.
File: TestAbstraction1.java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
File: TestAbstraction2.java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
Rule: If there is any abstract method in a class, that class must be abstract.
1.
2.
3.
class Bike12{
abstract void run();
}
Test it Now
compile time error
Rule: If you are extending any abstract class that have abstract method, you must either
provide the implementation of the method or make this class abstract.
The abstract class can also be used to provide some implementation of the interface. In
such case, the end user may not be forced to override all the methods of the interface.
Note: If you are beginner to java, learn interface first and skip this example.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
interface A{
void a();
void b();
void c();
void d();
}
abstract class B implements A{
public void c(){System.out.println("I am C");}
}
class M extends B{
public void a(){System.out.println("I am a");}
public void b(){System.out.println("I am b");}
public void d(){System.out.println("I am d");}
}
class Test5{
public static void main(String args[]){
A a=new M();
a.a();
a.b();
a.c();
a.d();
}}
Test it Now
Output:I am
I am
I am
I am
a
b
c
d
Interface in Java
1.
Interface
2.
Example of Interface
3.
4.
5.
Marker Interface
6.
Nested Interface
There are mainly three reasons to use interface. They are given below.
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.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
13.
14.
15.
16.
17.
18.
19.
Interface inheritance
A class implements interface but one interface extends another interface .
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class Testinterface2 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
12.
13.
14.
15.
16.
17.
An interface that have no member is known as marker or tagged interface. For example:
Serializable, Cloneable, Remote etc. They are used to provide some essential information
to the JVM so that JVM may perform some useful operation.
1.
2.
3.
Note: An interface can have another interface i.e. known as nested interface. We will
learn it in detail in the nested classes chapter. For example:
1.
2.
3.
4.
5.
6.
interface printable{
void print();
interface MessagePrintable{
void msg();
}
}
More about Nested Interface
Next TopicDifference between Abstract class and interface
Abstract class
Interface
variables.
7) Example:
public class Shape{
public abstract void draw();
}
Example:
public interface Drawable {
void draw();
}
But there are many differences between abstract class and interface that are given
below.
Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface
achieves fully abstraction (100%).
//Creating abstract class that provides the implementation of one method of A int
abstract class B implements A{
public void c(){System.out.println("I am C");}
}
29.
}}
Test it Now
Output:
I am a
I am b
I am c
I am d
Next TopicPackage in Java
Java Package
1.
Java Package
2.
Example of package
3.
Accessing package
1.
By import packagename.*
2.
By import packagename.classname
3.
4.
Subpackage
5.
6.
-classpath switch
7.
8.
9.
Static Import
10.
Package class
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.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
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) 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.
2.
3.
4.
5.
6.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be
accessible.
1.
2.
3.
4.
5.
6.
1.
2.
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
3.
4.
5.
6.
7.
8.
9.
10.
11.
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
1.
2.
3.
4.
5.
6.
1.
2.
3.
4.
5.
6.
7.
8.
9.
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello
Note: Sequence of the program must be package then import then class.
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.
Example of Subpackage
1.
2.
3.
4.
5.
6.
package com.javatpoint.core;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}
To Compile: javac -d . Simple.java
To Run: java com.javatpoint.core.Simple
Output:Hello subpackage
1.
2.
3.
4.
5.
6.
7.
8.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
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
Temporary
By -classpath switch
o
o
Permanent
By setting the classpath in the environment variables
By creating the jar file, that contains all the class files, and copying the jar
file in the jre/lib/ext folder.
Rule: There can be only one public class in a java source file and it must be saved by the public
class name.
1.
2.
3.
4.
5.
2.
3.
4.
5.
6.
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 this example, we have created two classes A and Simple. A class contains private
data member and private method. We are accessing these private members from
outside the class, so there is compile time error.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
1.
2.
3.
4.
5.
6.
7.
8.
9.
In this example, we have created two packages pack and mypack. We are accessing the
A class from outside its package, since A class is not public, so it cannot be accessed
from outside the package.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot
be accessed from outside the package.
of this package is declared as protected, so it can be accessed from outside the class
only through inheritance.
1.
2.
3.
4.
5.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
Access
Modifier
within class
within package
outside package by
subclass only
outside
package
Private
Default
Protected
Public
class A{
protected void msg(){System.out.println("Hello java");}
}
public class Simple extends A{
void msg(){System.out.println("Hello java");}//C.T.Error
public static void main(String args[]){
Simple obj=new Simple();
obj.msg();
}
}
The default modifier is more restrictive than protected. That is why there is compile time
error.
Next TopicEncapsulation in java
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.
//save as Student.java
package com.javatpoint;
public class Student{
private String name;
public String getName(){
return name;
}
public void setName(String name){
this.name=name
} aa
}
//save as Test.java
package com.javatpoint;
class Test{
public static void main(String[] args){
Student s=new Student();
s.setname("vijay");
System.out.println(s.getName());
}
}
Compile By: javac -d . Test.java
Run By: java com.javatpoint.Test
Output: vijay
Next TopicObject class in java
The Object class is the parent class of all the classes in java bydefault. In other words,
it is the topmost class of java.
The Object class is beneficial if you want to refer any object whose type you don't know.
Notice that parent class reference variable can refer the child class object, know as
upcasting.
Let's take an example, there is getObject() method that returns an object but it can be
of any type like Employee,Student etc, we can use Object class reference to refer that
object. For example:
1.
Object obj=getObject();//we don't what object would be returned from this meth
od
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 Class class
can further be used to get the metadata of this class.
Throwable
garbage collected.
The object cloning is a way to create exact copy of an object. For this purpose, clone()
method of Object class is used to clone an object.
The java.lang.Cloneable interface must be implemented by the class whose object
clone we want to create. If we don't implement Cloneable interface, clone() method
generates CloneNotSupportedException.
The clone() method is defined in the Object class. Syntax of the clone() method is as
follows:
1.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
this.name=name;
}
public Object clone()throws CloneNotSupportedException{
return super.clone();
}
public static void main(String args[]){
try{
Student18 s1=new Student18(101,"amit");
Student18 s2=(Student18)s1.clone();
System.out.println(s1.rollno+" "+s1.name);
System.out.println(s2.rollno+" "+s2.name);
}catch(CloneNotSupportedException c){}
}
}
Test it Now
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.
Next TopicArray in java
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.
Multidimensional Array
arrayRefVar=new datatype[size];
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
7.
8.
9.
10.
11.
12.
13.
14.
15.
a[2]=70;
a[3]=40;
a[4]=50;
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Test it Now
Output: 10
20
70
40
50
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
class Testarray2{
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
8.
9.
10.
11.
12.
13.
14.
15.
16.
System.out.println(min);
}
public static void main(String args[]){
int a[]={33,3,4,5};
min(a);//passing array to method
}}
Test it Now
Output:3
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
14.
15.
}}
Test it Now
Output:1 2 3
2 4 5
4 4 5
class Testarray4{
public static void main(String args[]){
int arr[]={4,4,5};
Class c=arr.getClass();
String name=c.getName();
System.out.println(name);
}}
Test it Now
Output:I
class TestArrayCopyDemo {
public static void main(String[] args) {
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
'i', 'n', 'a', 't', 'e', 'd' };
char[] copyTo = new char[7];
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
System.out.println(new String(copyTo));
}
}
Test it Now
Output:caffein
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
class Testarray5{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
//creating another matrix to store the sum of two matrices
int c[][]=new int[2][3];
//adding and printing addition of 2 matrices
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}}
Test it Now
Output:2 6 8
6 8 10
Next Topic Call by value and Call by reference in Java
In case of call by value original value is not changed. Let's take a simple example:
class Operation{
int data=50;
void change(int data){
data=data+100;//changes will be in the local variable only
}
public static void main(String args[]){
Operation op=new Operation();
System.out.println("before change "+op.data);
op.change(500);
System.out.println("after change "+op.data);
}
}
class Operation2{
int data=50;
void change(Operation2 op){
op.data=op.data+100;//changes will be in the instance variable
}
public static void main(String args[]){
Operation2 op=new Operation2();
System.out.println("before change "+op.data);
op.change(op);//passing object
System.out.println("after change "+op.data);
}
}
strictfp keyword
The strictfp keyword ensures that you will get the same result on every platform if you
perform operations in the floating-point variable. The precision may differ from platform
to platform that is why java programming language have provided the strictfp keyword,
so that you get same result on every platform. So, now you have better control over the
floating-point arithmetic.
1.
2.
3.
1.
2.
3.
class B{
strictfp int data=10;//modifier strictfp not allowed here
}
class B{
strictfp B(){}//modifier strictfp not allowed here
}
Next TopicCreating API Document
We can create document api in java by the help of javadoc tool. In the java file, we
must use the documentation comment /**... */ to post information for the class,
method, constructor, fields etc.
Let's see the simple class that contains documentation comment.
1.
2.
3.
4.
5.
6.
7.
package com.abc;
/** This class is a user-defined class that contains one methods cube.*/
public class M{
/** The cube method prints cube of the given number */
public static void cube(int n){System.out.println(n*n*n);}
}
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.
Next TopicCommand Line Argument in java
No Object
.
Class
1)
2)
3)
4)
5)
6)
7)
2.
3.
In this example, we are receiving only one argument and printing it. To run this java
program, you must pass at least one argument from the command prompt.
class CommandLineExample{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
}
}
compile by > javac CommandLineExample.java
run by > java CommandLineExample sonoo
Output: Your first argument is: sonoo
6.
7.
8.
1.
2.
}
}
compile by > javac A.java
run by > java A sonoo jaiswal 1 3 abc
Output: sonoo
jaiswal
1
3
abc
Next TopicObject vs Class
1.
2.
3.
4.
1.
2.
3.
4.
5.
6.
No.
Method Overloading
Method Overriding
1)
2)
Method overloading is performed within class. Method overriding occurs in two classes
that have IS-A (inheritance) relationship.
3)
4)
Method overloading is the example of compile Method overriding is the example of run
time polymorphism.
time polymorphism.
5)
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
}
Next TopicJava String
Java String
1. Java String Handling
2. How to create string object
1.
String literal
2.
new keyword
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.
2.
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
1.
String s="javatpoint";
The java.lang.String class implements
Serializable, Comparable and CharSequence interfaces.
The java String is immutable i.e. it cannot be changed but a new instance is created. For
mutable class, you can use StringBuffer and StringBuilder class.
We will discuss about immutable string later. Let's first understand what is string in java
and how to create the string object.
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.
2.
String s1="Welcome";
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
1.
In such case, JVM will create a new string object in normal(non pool) heap memory and
the literal "Welcome" will be placed in the string constant pool. The variable s will refer to
the object in heap(non pool).
No. Method
1
Description
returns char value for the particular index
int length()
static
String
format(String
format, Object... args)
boolean
s)
returns true
sequence of
char value
10
11
boolean isEmpty()
12
13
String
new)
14
String
replace(CharSequence
old, CharSequence new)
replaces
all
CharSequence
15
String trim()
l,
contains(CharSequence
replace(char
old,
char
or
false
after
matching
the
occurrences
of
specified
16
17
String
limit)
18
String intern()
19
20
21
22
23
String toLowerCase()
24
String toLowerCase(Locale l)
25
String toUpperCase()
26
String toUpperCase(Locale l)
returns
locale.
split(String
regex,
int
string
in
uppercase
using
specified
Do You Know ?
What code is written by the compiler if you concat any string by + (string
concatenation operator)?
Concept of String
Immutable String
String Comparison
String Concatenation
Concept of Substring
StringBuffer class
StringBuilder class
toString() method
StringTokenizer class
class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects
}
}
Test it Now
Output:Sachin
Now it can be understood by the diagram given below. Here Sachin is not changed but a
new object is created with Sachin Tendulkar. 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 explicitly assign it to the reference variable, it will refer to "Sachin Tendulkar"
object. For example:
1.
2.
3.
4.
5.
6.
7.
class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
Test it Now
Output:Sachin Tendulkar
In such case, s points to the "Sachin Tendulkar". Please notice that still Sachin object is
not modified.
value of the object, it will be affected to all the reference variables. That is why string
objects are immutable in java.
Next Topic String Comparison in java
is
used
in authentication (by
equals()
compareTo()
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
class Teststringcomparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
}
}
Test it Now
Output:true
true
1.
2.
3.
4.
5.
6.
7.
8.
9.
false
class Teststringcomparison2{
public static void main(String args[]){
String s1="Sachin";
String s2="SACHIN";
System.out.println(s1.equals(s2));//false
System.out.println(s1.equalsIgnoreCase(s3));//true
}
}
Test it Now
Output:false
true
Click me for more about equals() method
class Teststringcomparison3{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2);//true (because both refer to same instance)
System.out.println(s1==s3);//false(because s3 refers to instance created in no
npool)
}
}
Test it Now
Output:true
false
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
s1 == s2 :0
s1 > s2
:positive value
s1 < s2
:negative value
class Teststringcomparison4{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
}
}
Test it Now
Output:0
1
-1
Click me for more about compareTo() method
Next TopicString Concatenation in java
class TestStringConcatenation1{
public static void main(String args[]){
String s="Sachin"+" Tendulkar";
4.
5.
6.
System.out.println(s);//Sachin Tendulkar
}
}
Test it Now
Output: Sachin Tendulkar
The Java compiler transforms above code to this:
1.
class TestStringConcatenation2{
public static void main(String args[]){
String s=50+30+"Sachin"+40+40;
System.out.println(s);//80Sachin4040
}
}
Test it Now
80Sachin4040
Note: After a string literal, all the + will be treated as string concatenation operator.
1.
2.
3.
4.
5.
6.
7.
8.
class TestStringConcatenation3{
public static void main(String args[]){
String s1="Sachin ";
String s2="Tendulkar";
String s3=s1.concat(s2);
System.out.println(s3);//Sachin Tendulkar
}
}
Test it Now
Sachin Tendulkar
Next TopicSubstring in java
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.
startIndex: inclusive
endIndex: exclusive
Let's understand the startIndex and endIndex by the code given below.
1.
2.
String s="hello";
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).
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.
String s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin
System.out.println(s);//Sachin(no change in original)
Test it Now
SACHIN
sachin
Sachin
String s="Sachin";
System.out.println(s.startsWith("Sa"));//true
System.out.println(s.endsWith("n"));//true
Test it Now
true
true
String s="Sachin";
System.out.println(s.charAt(0));//S
System.out.println(s.charAt(3));//h
Test it Now
S
h
String s="Sachin";
System.out.println(s.length());//6
Test it Now
6
int a=10;
String s=String.valueOf(a);
System.out.println(s+10);
Output:
1010
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.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
The insert() method inserts the given string with this string at the given position.
1.
2.
3.
4.
5.
6.
7.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
The capacity() method of StringBuffer class returns the current capacity of the buffer.
The default capacity of the buffer is 16. If the number of character increases from its
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.
2.
3.
4.
5.
6.
7.
8.
9.
10.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
}
Method
public
Description
StringBuilder
append(String s)
append(boolean),
append(int),
offset, String s)
like
insert(int,
insert(int,
int),
char),
insert(int,
insert(int,
float),
public
StringBuilder
replace(int
startIndex,
int
is
used
to
replace
the
string
from
specified
string
from
specified
is
public
void
ensureCapacity(int
used
to
delete
the
minimumCapacity)
public char charAt(int index)
public
String
substring(int
beginIndex)
public
String
beginIndex.
substring(int
}
Next TopicStringBuilder class
class A{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
class A{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
class A{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
class A{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.delete(1,3);
5.
6.
7.
System.out.println(sb);//prints Hlo
}
}
class A{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
class A{
public static void main(String args[]){
StringBuilder sb=new StringBuilder();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}
class A{
public static void main(String args[]){
StringBuilder sb=new StringBuilder();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
13.
14.
}
}
Next TopicDifference between String and StringBuffer
No
String
StringBuffer
1)
2)
Object
class.
So
you
can
compare
the
StringBuffer: 0ms
}
Hashcode test of String:
3254818
229541438
Hashcode test of StringBuffer:
118352462
118352462
Next TopicDifference between StringBuffer and StringBuilder
Difference
between
StringBuilder
StringBuffer
and
There are many differences between StringBuffer and StringBuilder. A list of differences
between StringBuffer and StringBuilder are given below:
No.
StringBuffer
StringBuilder
StringBuffer
is synchronized i.e.
can't
the
call
the
methods
StringBuffer simultaneously.
of
methods
simultaneously.
of
StringBuilder
StringBuilder
StringBuilder.
StringBuffer.
is more
efficient than
StringBuffer Example
1.
2.
3.
4.
5.
6.
7.
StringBuilder Example
1.
2.
3.
4.
5.
6.
7.
There is no setter methods i.e. we have no option to change the value of the
instance variable.
class Student{
int rollno;
String name;
String city;
Student(int rollno, String name, String city){
this.rollno=rollno;
this.name=name;
this.city=city;
}
public static void main(String args[]){
Student s1=new Student(101,"Raj","lucknow");
Student s2=new Student(102,"Vijay","ghaziabad");
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
}
}
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:
class Student{
int rollno;
String name;
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
String city;
Student(int rollno, String name, String city){
this.rollno=rollno;
this.name=name;
this.city=city;
}
public String toString(){//overriding the toString() method
return rollno+" "+name+" "+city;
}
public static void main(String args[]){
Student s1=new Student(101,"Raj","lucknow");
Student s2=new Student(102,"Vijay","ghaziabad");
}
}
StringTokenizer in Java
1. StringTokenizer
2. Methods of StringTokenizer
3. Example of StringTokenizer
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.
Constructor
Description
StringTokenizer(String
str)
StringTokenizer(String
str,
String
delim,
boolean returnValue)
Public method
Description
boolean hasMoreTokens()
String nextToken()
boolean hasMoreElements()
Object nextElement()
int countTokens()
import java.util.StringTokenizer;
public class Simple{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name is khan"," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
Output:my
name
is
khan
Example of nextToken(String
StringTokenizer class
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
delim)
method
of
import java.util.*;
public class Test {
public static void main(String[] args) {
StringTokenizer st = new StringTokenizer("my,name,is,khan");
// printing next token
System.out.println("Next token is : " + st.nextToken(","));
}
Output:Next token is : my
Signature
The signature of string charAt() method is given below:
1.
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.
1.
2.
3.
4.
5.
6.
Signature
1.
Parameters
anotherString: represents string that is to be compared with current string
Returns
an integer value
Signature
The signature of string concat() method is given below:
1.
Parameter
anotherString : another string i.e. to be combined at the end of this string.
Returns
combined string
Signature
The signature of string contains() method is given below:
1.
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.
class ContainsExample{
public static void main(String args[]){
String name="what do you know about me";
System.out.println(name.contains("do you know"));
System.out.println(name.contains("about"));
System.out.println(name.contains("hello"));
}}
Test it Now
true
true
false
Next TopicJava String endsWith()
Signature
The syntax or signature of endsWith() method is given below.
1.
Parameter
suffix : Sequence of character
Returns
true or false
Signature
1.
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.
format()
method
of
java
language
is
in
Signature
There are two type of string format() method:
1.
2.
3.
Parameters
locale : specifies the locale to be applied on the format() method.
format : format of the string.
language
Returns
formatted string
Throws
NullPointerException : if format is null.
IllegalFormatException : if format is illegal or incompatible.
Signature
There are 3 variant of getBytes() method. The signature or syntax of string getBytes()
method is given below:
1.
2.
3.
ion
Returns
sequence of bytes.
Signature
There are 4 types of indexOf method in java. The signature of indexOf methods are
given below:
No. Method
1
Description
int
indexOf(int
ch,
int
fromIndex)
int fromIndex)
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
16.
}}
Test it Now
2
5
3
Next TopicJava String intern
Signature
The signature of intern method is given below:
1.
Returns
interned string
Signature
The signature or syntax of string isEmpty() method is given below:
1.
Returns
true if length is 0 otherwise false.
Since
1.6
In case of null element, "null" is added. The join() method is included in java string since
JDK 1.8.
There are two types of join() methods in java string.
Signature
The signature or syntax of string join method is given below:
1.
2.
3.
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.
Since1.8
1.
2.
3.
4.
5.
Signature
No. Method
1
Description
int
lastIndexOf(int
ch,
int
fromIndex)
int fromIndex)
There are 4 types of lastIndexOf method in java. The signature of lastIndexOf methods
are given below:
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
5.
6.
System.out.println(index1);//6
}}
Output:
6
Next TopicJava String length()
Signature
The signature of the string length() method is given below:
1.
Specified by
CharSequence interface
Returns
length of characters
1.
2.
3.
4.
5.
Signature
There are two type of replace methods in java string.
1.
2.
3.
Parameters
oldChar : old character
newChar : new character
target : target sequence of characters
replacement : replacement sequence of characters
Returns
replaced string
was"
System.out.println(replaceString);
}}
Test it Now
my name was khan my name was java
Next TopicJava String replaceAll()
Signature
1.
Parameters
regex : regular expression
replacement : replacement sequence of characters
Returns
replaced string
5.
6.
System.out.println(replaceString);
}}
jevetpoint is e very good website
"was"
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
Method
Description
boolean matches()
boolean find()
finds the next expression that matches the pattern from the given start num
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
String pattern()
Character Class
Description
[abc]
a, b, or c (simple class)
[^abc]
[a-zA-Z]
[a-d[m-p]]
[a-z&&[def]]
d, e, or f (intersection)
[a-z&&[^bc]]
[a-z&&[^m-p]]
Description
X?
X+
X*
X{n}
X{n,}
X{y,z}
Description
\d
\D
\s
\S
\w
\W
\b
A word boundary
\B
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
statement
statement
statement
statement
statement
statement
statement
statement
statement
statement
1;
2;
3;
4;
5;//exception occurs
6;
7;
8;
9;
10;
we perform exception handling, rest of the exception will be executed. That is why we
use exception handling in java.
Do You Know ?
What are the 4 rules for using exception handling with method overriding ?
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
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.
int a=50/0;//ArithmeticException
String s=null;
System.out.println(s.length());//NullPointerException
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
Java try-catch
Java try block
Java try block is used to enclose the code that might throw an exception. It must be
used within the method.
Java try block must be followed by either catch or finally block.
try{
//code that may throw exception
}catch(Exception_class_Name ref){}
try{
//code that may throw exception
}finally{}
Java catch block is used to handle the Exception. It must be used after the try block
only.
You can use multiple catch block with a single try.
Now, as displayed in the above example, rest of the code is executed i.e. rest of the
code... statement is printed.
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:
Prints the stack trace (Hierarchy of methods where the exception occurred).
But if exception is handled by the application programmer, normal flow of the application
is maintained i.e. rest of the code is executed.
Next TopicMultiple catch block in java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
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.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
ed");}
class TestMultipleCatchBlock1{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(Exception e){System.out.println("common task completed");}
catch(ArithmeticException e){System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 complet
Sometimes a situation may arise where a part of a block may cause one error and the
entire block itself may cause another error. In such cases, exception handlers have to be
nested.
Syntax:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
....
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
....
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
}
}
Next TopicFinally Block in Exception Handling
Note: If you don't handle exception, before terminating the program, JVM executes finally block(if
any).
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.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Test it Now
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.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
class TestFinallyBlock1{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Test it Now
Output: finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero
Case 3
Let's see the java finally example where exception occurs and handled.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
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).
Next TopicJava Throw Keyword
throw exception;
Let's see the example of throw IOException.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
proper-tion
An exception is first thrown from the top of the stack and if it is not caught, it drops
down the call stack to the previous method, If not caught there, the exception again
drops down to the previous method, and so on until they are caught or until they
reach the very bottom of the call stack. This is called exception propagation.
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.
Rule: By default, Checked Exceptions are not forwarded in calling chain (propagated).
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
error: beyond your control e.g. you are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
Test it Now
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.
1.
2.
3.
4.
5.
6.
7.
8.
9.
In case you handle the exception, the code will be executed fine whether
exception occurs during the program or not.
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
public class Testthrows2{
public static void main(String args[]){
try{
10.
11.
12.
13.
14.
15.
16.
M m=new M();
m.method();
}catch(Exception e){System.out.println("exception handled");}
}
System.out.println("normal flow...");
}
Test it Now
Output:exception handled
normal flow...
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
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.
System.out.println("normal flow...");
}
Test it Now
Output:device operation performed
normal flow...
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
m.method();
}
System.out.println("normal flow...");
}
Test it Now
Output:Runtime Exception
No.
Throw
Throws
exception.
Throw is followed by an
instance.
method.
exceptions.
throws.
Throws is followed by class.
SQLException.
void m(){
throw new ArithmeticException("sorry");
}
No.
1)
Final
Finally
finalize
restrictions on class,
executed whether
exception is handled or
collected.
not.
Final is a keyword.
Finally is a block.
Finalize is a method.
1.
2.
3.
4.
5.
class FinalExample{
public static void main(String[] args){
final int x=100;
x=200;//Compile Time Error
}}
class FinallyExample{
public static void main(String[] args){
try{
int x=300;
}catch(Exception e){System.out.println(e);}
finally{System.out.println("finally block is executed");}
}}
class FinalizeExample{
public void finalize(){System.out.println("finalize called");}
public static void main(String[] args){
FinalizeExample f1=new FinalizeExample();
FinalizeExample f2=new FinalizeExample();
f1=null;
f2=null;
System.gc();
}}
Next TopicException Handling With Method Overriding
import java.io.*;
class Parent{
void msg(){System.out.println("parent");}
}
class TestExceptionChild extends Parent{
void msg()throws IOException{
System.out.println("TestExceptionChild");
}
public static void main(String args[]){
Parent p=new TestExceptionChild();
p.msg();
}
}
Test it Now
Output:Compile Time Error
2) Rule: If the superclass method does not declare an exception, subclass overridden method
cannot declare the checked exception but can declare unchecked exception.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
import java.io.*;
class Parent{
void msg(){System.out.println("parent");}
}
class TestExceptionChild1 extends Parent{
void msg()throws ArithmeticException{
System.out.println("child");
}
public static void main(String args[]){
Parent p=new TestExceptionChild1();
p.msg();
}
}
Test it Now
Output:child
import java.io.*;
class Parent{
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
import java.io.*;
class Parent{
void msg()throws Exception{System.out.println("parent");}
}
class TestExceptionChild3 extends Parent{
void msg()throws Exception{System.out.println("child");}
public static void main(String args[]){
Parent p=new TestExceptionChild3();
try{
p.msg();
}catch(Exception e){}
}
}
Test it Now
Output:child
import java.io.*;
class Parent{
void msg()throws Exception{System.out.println("parent");}
}
class TestExceptionChild4 extends Parent{
void msg()throws ArithmeticException{System.out.println("child");}
public static void main(String args[]){
Parent p=new TestExceptionChild4();
try{
p.msg();
}catch(Exception e){}
14.
15.
}
}
Test it Now
Output:child
import java.io.*;
class Parent{
void msg()throws Exception{System.out.println("parent");}
}
class TestExceptionChild5 extends Parent{
void msg(){System.out.println("child");}
public static void main(String args[]){
Parent p=new TestExceptionChild5();
try{
p.msg();
}catch(Exception e){}
}
}
Test it Now
Output:child
Next TopicCustom Exception
1.
2.
3.
4.
5.
6.
class TestCustomException1{
static void validate(int age)throws InvalidAgeException{
if(age<18)
throw new InvalidAgeException("not valid");
else
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
System.out.println("welcome to vote");
}
Test it Now
Output:Exception occured: InvalidAgeException:not valid
rest of the code...
Next TopicJava Inner class
Multithreading in Java
1. Multithreading
2. Multitasking
3. Process-based multitasking
4. Thread-based multitasking
5. What is Thread
Multithreading in java is a process of executing multiple threads
simultaneously.
Thread is basically a lightweight sub-process, a smallest unit of processing.
Mltuiprocessing 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 contextswitching between the threads takes less time than process.
Java Multithreading is mostly used in games, animation etc.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking
to utilize the CPU. Multitasking can be achieved by two ways:
o
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.
Switching from one process to another require some time for saving and loading
registers, memory maps, updating lists etc.
Thread is lightweight.
Threads are independent, if there occurs exception in one thread, it doesn't affect other
threads. It shares a common memory area.
As shown in the above figure, thread is executed inside the process. There is contextswitching between the threads. There can be multiple processes inside the OS and one
process can have multiple threads.
Do You Know
o
What is the Thread Schedular and what is the difference between preemptive
scheduling and time slicing ?
Why JVM terminates the daemon thread if there is no user threads remaining ?
Multithreading
Thread Schedular
Sleeping a thread
Joining a thread
Naming a thread
Priority of a thread
Daemon Thread
Shutdown Hook
Garbage collection
Synchronized block
Static synchronization
Deadlock
Inter-thread communication
The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.
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.
Next TopicCreating Thread
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.
Thread()
Thread(String name)
Thread(Runnable r)
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().
1. public void run(): is used to perform action for a thread.
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs
following tasks:
A new thread starts(with new call stack).
When the thread gets a chance to execute, its target run() method will run.
The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the
threads.
1.
2.
3.
4.
15.
}
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.
Next TopicCan we start a Thread Twice
1.
2.
3.
4.
5.
6.
7.
8.
9.
Invoking the run() method from main thread, the run() method goes onto the
current call stack rather than at the beginning of a new call stack.
Output:running...
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
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.
Next TopicJoining A Thread
Syntax:
public void join()throws InterruptedException
public void join(long milliseconds)throws InterruptedException
Example of join() method
1.
1class TestJoinMethod1 extends Thread{
2.
public void run(){
3.
for(int i=1;i<=5;i++){
4.
try{
5.
Thread.sleep(500);
6.
}catch(Exception e){System.out.println(e);}
7.
System.out.println(i);
8.
}
9.
}
10.
public static void main(String args[]){
11.
TestJoinMethod1 t1=new TestJoinMethod1();
12.
TestJoinMethod1 t2=new TestJoinMethod1();
13.
TestJoinMethod1 t3=new TestJoinMethod1();
14.
t1.start();
15.
try{
16.
t1.join();
17.
}catch(Exception e){System.out.println(e);}
18.
19.
t2.start();
20.
t3.start();
21.
}
22.
}
Test it Now
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
1.
class TestJoinMethod2 extends Thread{
2.
public void run(){
3.
for(int i=1;i<=5;i++){
4.
try{
5.
Thread.sleep(500);
6.
}catch(Exception e){System.out.println(e);}
7.
System.out.println(i);
8.
}
9.
}
10.
public static void main(String args[]){
11.
TestJoinMethod2 t1=new TestJoinMethod2();
12.
TestJoinMethod2 t2=new TestJoinMethod2();
13.
TestJoinMethod2 t3=new TestJoinMethod2();
14.
t1.start();
15.
try{
16.
t1.join(1500);
17.
}catch(Exception e){System.out.println(e);}
18.
19.
t2.start();
20.
t3.start();
21.
}
22.
}
Test it Now
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.
Syntax:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
Naming a thread:
The Thread class provides methods to change and get the name of a thread.
1. public String getName(): is used to return the name of a thread.
2. public void setName(String name): is used to change the name of a
thread.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
System.out.println("Name of t1:"+t1.getName());
System.out.println("Name of t2:"+t2.getName());
t1.start();
t2.start();
t1.setName("Sonoo Jaiswal");
System.out.println("After changing name of t1:"+t1.getName());
}
}
Test it Now
Output:Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
running...
After changeling name of t1:Sonoo Jaiswal
running...
e());
rity());
}
}
Test it Now
Output:running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
No.
1)
2)
Method
Description
public void
setDaemon(boolean
status)
user thread.
t1 is daemon thread
threads
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.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
File: WorkerThrad.java
1.
2.
3.
4.
5.
6.
7.
8.
9.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class WorkerThread implements Runnable {
private String message;
public WorkerThread(String s){
this.message=s;
}
public void run() {
System.out.println(Thread.currentThread().getName()+" (Start) message =
"+message);
10.
processmessage();//call processmessage method that sleeps the thre
ad for 2 seconds
11.
System.out.println(Thread.currentThread().getName()+" (End)");//prints
thre
ad name
12.
13.
14.
15.
16.
}
private void processmessage() {
try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStack
Trace(); }
File: JavaThreadPoolExample.java
1.
2.
3.
a pool of 5 threads
4.
5.
6.
rvice
7.
8.
9.
10.
11.
12.
13.
}
executor.shutdown();
while (!executor.isTerminated()) {
}
Test it Now
of ExecutorSe
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.
user logoff
Factory method
The method that returns the instance of a class is known as factory method.
Note: The shutdown sequence can be stopped by invoking the halt(int) method of
Runtime class.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
example:
Program of performing single task by multiple threads
class TestMultitasking1 extends Thread{
public void run(){
System.out.println("task one");
}
public static void main(String args[]){
TestMultitasking1 t1=new TestMultitasking1();
TestMultitasking1 t2=new TestMultitasking1();
TestMultitasking1 t3=new TestMultitasking1();
t1.start();
t2.start();
t3.start();
}
}
Test it Now
Output:task one
task one
1.
2.
3.
4.
5.
6.
7.
task one
Program of performing single task by multiple threads
class TestMultitasking2 implements Runnable{
public void run(){
System.out.println("task one");
}
public static void main(String args[]){
Thread t1 =new Thread(new TestMultitasking2());//passing
annonymous o
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
methods.For example:
Program of performing two tasks by two threads
class Simple1 extends Thread{
public void run(){
System.out.println("task one");
}
}
class Simple2 extends Thread{
public void run(){
System.out.println("task two");
}
}
class TestMultitasking3{
public static void main(String args[]){
Simple1 t1=new Simple1();
Simple2 t2=new Simple2();
t1.start();
t2.start();
}
}
Test it Now
Output:task one
task two
1) By nulling a reference:
1.
2.
ollection
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:
1.
Note: The Garbage collector of JVM collects only those objects that are created by new keyword.
So if you have created any object without new, you can use finalize method to perform cleanup
processing (destroying remaining objects).
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.
1.
Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC). This
thread calls the finalize() method before object is garbage collected.
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.
Types of Synchronization
There are two types of synchronization
1. Process Synchronization
2. Thread Synchronization
Here, we will discuss only 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
Class Table{
void printTable(int n){//method not synchronized
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
class TestSynchronization1{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output: 5
100
10
200
15
300
20
400
25
500
37.
38.
39.
40.
41.
42.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
1.
2.
3.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
20
25
100
200
300
400
500
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.
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.
class Table{
synchronized static void printTable(int n){
for(int i=1;i<=10;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){}
}
}
}
class MyThread1 extends Thread{
public void run(){
Table.printTable(1);
}
}
class MyThread2 extends Thread{
public void run(){
Table.printTable(10);
}
}
class MyThread3 extends Thread{
public void run(){
Table.printTable(100);
}
}
47.
48.
49.
50.
51.
t2.start();
t3.start();
t4.start();
}
}
Test it Now
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
class Table{
synchronized static void printTable(int n){
for(int i=1;i<=10;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){}
}
}
}
public class TestSynchronization5 {
public static void main(String[] args) {
Thread t1=new Thread(){
public void run(){
Table.printTable(1);
}
};
Thread t2=new Thread(){
public void run(){
Table.printTable(10);
}
};
Thread t3=new Thread(){
public void run(){
Table.printTable(100);
}
};
Thread t4=new Thread(){
public void run(){
Table.printTable(1000);
}
};
t1.start();
40.
41.
42.
43.
44.
45.
t2.start();
t3.start();
t4.start();
}
}
Test it Now
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.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
}
}
};
// t2 tries to lock resource2 then resource1
Thread t2 = new Thread() {
public void run() {
synchronized (resource2) {
System.out.println("Thread 2: locked resource 2");
try { Thread.sleep(100);} catch (Exception e) {}
synchronized (resource1) {
System.out.println("Thread 2: locked resource 1");
}
}
};
t1.start();
t2.start();
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
public final void wait()throws
Description
waits until object is notified.
InterruptedException
public final void wait(long
timeout)throws InterruptedException
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()
wait()
sleep()
class Customer{
int amount=10000;
synchronized void withdraw(int amount){
System.out.println("going to withdraw...");
if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount){
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}.start();
new Thread(){
public void run(){c.deposit(10000);}
}.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.
exception.
class TestInterruptingThread1 extends Thread{
public void run(){
try{
Thread.sleep(1000);
System.out.println("task");
}catch(InterruptedException e){
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
interrupted..."+e);
}
public static void main(String args[]){
TestInterruptingThread1 t1=new TestInterruptingThread1();
t1.start();
try{
t1.interrupt();
}catch(Exception e){System.out.println("Exception handled "+e);}
}
}
Test it Now
later.
class TestInterruptingThread3 extends Thread{
public void run(){
for(int i=1;i<=5;i++)
System.out.println(i);
}
public static void main(String args[]){
TestInterruptingThread3 t1=new TestInterruptingThread3();
t1.start();
t1.interrupt();
}
}
Test it Now
Output:1
2
3
4
5
is true.
public class TestInterruptingThread4 extends Thread{
public void run(){
for(int i=1;i<=2;i++){
if(Thread.interrupted()){
System.out.println("code
}
else{
System.out.println("code
}
}//end of for loop
}
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
Let's understand the java reentrant monitor by the example given below:
1.
2.
3.
4.
5.
6.
7.
8.
9.
class Reentrant {
public synchronized void m() {
n();
System.out.println("this is m() method");
}
public synchronized void n() {
System.out.println("this is n() method");
}
}
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.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
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.
2.
System.out.println("simple message");
System.err.println("error message");
Let's see the code to get input from console.
1.
2.
Do You Know ?
How to write a common data to multiple files using single stream only?
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.
Description
IOException:
stream.
IOException:
output stream.
IOException:
4) public void close()throws
IOException:
InputStream class
InputStream class is an abstract class. It is the superclass of all classes representing an
input stream of bytes.
Description
read()throws IOException:
2) public int
available()throws
IOException:
3) public void
close()throws IOException:
File Writer. But you can write byte-oriented as well as character-oriented data.
import java.io.*;
class Test{
public static void main(String args[]){
try{
FileOutputstream fout=new FileOutputStream("abc.txt");
String s="Sachin Tendulkar is my favourite player";
7.
8.
9.
10.
11.
12.
13.
import java.io.*;
class SimpleRead{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("abc.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.println((char)i);
}
fin.close();
}catch(Exception e){system.out.println(e);}
}
}
Output: Sachin is my favourite player.
import java.io.*;
class C{
public static void main(String args[])throws Exception{
FileInputStream fin=new FileInputStream("C.java");
FileOutputStream fout=new FileOutputStream("M.java");
int i=0;
while((i=fin.read())!=-1){
fout.write((byte)i);
}
fin.close();
}
}
Description
creates a new byte array output stream with the initial capacity of
32 bytes, though its size increases if necessary.
ByteArrayOutputStream(int
size)
Description
IOException
4) public void flush()
import java.io.*;
class S{
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
Description
1) SequenceInputStream(InputStream s1,
InputStream s2)
2) SequenceInputStream(Enumeration e)
import java.io.*;
class Simple{
public static void main(String args[])throws Exception{
FileinputStream fin1=new FileinputStream("f1.txt");
FileinputStream fin2=new FileinputStream("f2.txt");
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
while((i.sisread())!=-1)
{
fout.write(i);
}
sis.close();
fout.close();
fin.close();
fin.close();
}
}
34.
35.
}
}
import java.io.*;
class Test{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("f1.txt");
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Sachin is my favourite player";
byte b[]=s.getBytes();
bout.write(b);
bout.flush();
bout.close();
fout.close();
System.out.println("success");
}
}
Output:
success...
import java.io.*;
class SimpleRead{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("f1.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=bin.read())!=-1){
System.out.println((char)i);
}
bin.close();
fin.close();
}catch(Exception e){system.out.println(e);}
}
}
Output:
Sachin is my favourite player
Next TopicFileReader And FileWriter
Description
FileWriter(String file)
FileWriter(File file)
closes FileWriter.
Description
import java.io.*;
class Simple{
public static void main(String args[]){
try{
FileWriter fw=new FileWriter("abc.txt");
fw.write("my name is sachin");
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("success");
}
}
Output:
success...
Description
FileReader(String
It gets filename in string. It opens the given file in read mode. If file doesn'
file)
FileNotFoundException.
FileReader(File file)
It gets filename in file instance. It opens the given file in read mode. If file
throws FileNotFoundException.
Description
closes FileReader.
import java.io.*;
class Simple{
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("abc.txt");
int i;
while((i=fr.read())!=-1)
System.out.println((char)i);
fr.close();
}
}
Output:
my name is sachin
Next TopicCharArrayWriter class
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.
import java.io.*;
class Simple{
public static void main(String args[])throws Exception{
CharArrayWriter out=new CharArrayWriter();
out.write("my name is");
FileWriter
FileWriter
FileWriter
FileWriter
f1=new
f2=new
f3=new
f4=new
FileWriter("a.txt");
FileWriter("b.txt");
FileWriter("c.txt");
FileWriter("d.txt");
out.writeTo(f1);
out.writeTo(f2);
out.writeTo(f3);
out.writeTo(f4);
f1.close();
f2.close();
f3.close();
f4.close();
}
}
Next TopicInput From keyboard By InputStreamReader
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.
5.
6.
7.
8.
9.
10.
11.
import java.io.*;
class G5{
public static void main(String args[])throws Exception{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
String name="";
while(name.equals("stop")){
System.out.println("Enter data: ");
name=br.readLine();
System.out.println("data is: "+name);
}
br.close();
r.close();
}
}
Output:Enter data: Amit
data is: Amit
Enter data: 10
data is: 10
Enter data: stop
data is: stop
Next TopicConsole class
String text=System.console().readLine();
System.out.println("Text is: "+text);
Method
Description
fmt,Object... args)
fmt,Object... args)
1.
Console c=System.console();
import java.io.*;
class ReadStringTest{
public static void main(String args[]){
Console c=System.console();
System.out.println("Enter your name: ");
String n=c.readLine();
System.out.println("Welcome "+n);
}
}
Output:
Enter your name: james gosling
Welcome james gosling
import java.io.*;
class ReadPasswordTest{
public static void main(String args[]){
Console c=System.console();
System.out.println("Enter password: ");
char[] ch=c.readPassword();
String pass=String.valueOf(ch);//converting char array into string
System.out.println("Password is: "+pass);
}
}
11.
Output:
Enter password:
Password is: sonoo
Next TopicScanner-class
There are various ways to read input from the keyboard, the java.util.Scanner class is
one of them.
The Java Scanner class breaks the input into tokens using a delimiter that is
whitespace bydefault. It provides many methods to read and parse various primitive
values.
Java Scanner class is widely used to parse text for string and primitive types using
regular expression.
Java Scanner class extends Object class and implements Iterator and Closeable
interfaces.
Method
Description
import java.util.Scanner;
class ScannerTest{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
import java.util.*;
public class ScannerTest2{
public static void main(String args[]){
String input = "10 tea 20 coffee 30 tea buiscuits";
Scanner s = new Scanner(input).useDelimiter("\\s");
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.nextInt());
System.out.println(s.next());
s.close();
}}
Output:
10
tea
20
coffee
Next TopicPrintStream class
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.
public void print(char[] c): it prints the specified character array values.
public void println(boolean b): it prints the specified boolean value and
terminates the line.
public void println(char c): it prints the specified char value and terminates
the line.
public void println(char[] c): it prints the specified character array values
and terminates the line.
public void println(int i): it prints the specified int value and terminates the
line.
public void println(long l): it prints the specified long value and terminates
the line.
public void println(float f): it prints the specified float value and terminates
the line.
public void println(double d): it prints the specified double value and
terminates the line.
public void println(String s): it prints the specified string value and
terminates the line./li>
public void println(Object obj): it prints the specified object value and
terminates the line.
Let's see the simple example of printing integer value by format specifier.
class PrintStreamTest{
2.
3.
4.
5.
6.
7.
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.
import java.io.*;
import java.util.zip.*;
class Compress{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("Deflater.java");
FileOutputStream fout=new FileOutputStream("def.txt");
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
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.
import java.io.*;
import java.util.zip.*;
class UnCompress{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("def.txt");
InflaterInputStream in=new InflaterInputStream(fin);
FileOutputStream fout=new FileOutputStream("D.java");
int i;
while((i=in.read())!=-1){
fout.write((byte)i);
fout.flush();
}
fin.close();
fout.close();
in.close();
22.
23.
24.
25.
26.
}catch(Exception e){System.out.println(e);}
System.out.println("rest of the code");
}
}
PipeedinputStream and
PipedOutputStream classes
The PipedInputStream and PipedOutputStream classes can be used to read and write
data simultaneously. Both streams are connected with each other using the connect()
method of the PipedOutputStream class.
import java.io.*;
class PipedWR{
public static void main(String args[])throws Exception{
final PipedOutputStream pout=new PipedOutputStream();
final PipedInputStream pin=new PipedInputStream();
pout.connect(pin);//connecting the streams
//creating one thread t1 which writes the data
Thread t1=new Thread(){
public void run(){
for(int i=65;i<=90;i++){
try{
pout.write(i);
Thread.sleep(1000);
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
}catch(Exception e){}
}
}
};
//creating another thread t2 which reads the data
Thread t2=new Thread(){
public void run(){
try{
for(int i=65;i<=90;i++)
System.out.println(pin.read());
}catch(Exception e){}
}
};
//starting both threads
t1.start();
t2.start();
}}
Serialization in Java
1. Serialization
2. Serializable Interface
3. Example of Serialization
4. Deserialization
5. Example of Deserialization
6. Serialization with Inheritance
7. Externalizable interface
8. Serialization and static datamember
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.
2.
3.
4.
5.
6.
7.
8.
9.
import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}
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
public ObjectOutputStream(OutputStream out) throws IOException{}creates an
ObjectOutputStream that writes to the specified OutputStream.
Important Methods
Method
Description
ObjectOutputStream.
{}
3) public void close() throws IOException
{}
import java.io.*;
class Persist{
public static void main(String args[])throws Exception{
Student s1 =new Student(211,"ravi");
FileOutputStream fout=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(s1);
out.flush();
System.out.println("success");
}
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
creates an ObjectInputStream
ObjectInputStream(InputStream in)
throws IOException {}
InputStream.
Important Methods
Method
1) public final Object readObject()
Description
reads an object from the input stream.
throws IOException,
ClassNotFoundException{}
2) public void close() throws
closes ObjectInputStream.
IOException {}
import java.io.*;
class Depersist{
public static void main(String args[])throws Exception{
ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
Student s=(Student)in.readObject();
System.out.println(s.id+" "+s.name);
8.
9.
10.
11.
in.close();
}
}
211 ravi
import java.io.Serializable;
class Person implements Serializable{
int id;
String name;
Person(int id, String name) {
this.id = id;
this.name = name;
}
}
1.
2.
3.
4.
5.
6.
7.
8.
9.
class Address{
String addressLine,city,state;
public Address(String addressLine, String city, String state) {
this.addressLine=addressLine;
this.city=city;
this.state=state;
}
}
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
Address address;//HAS-A
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}
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:
If you deserialize the object, you will get the default value for transient variable.
Let's create a class with transient variable.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
transient int age;//Now it will not be serialized
public Student(int id, String name,int age) {
this.id = id;
this.name = name;
this.age=age;
}
}
Now write the code to serialize the object.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
import java.io.*;
class PersistExample{
public static void main(String args[])throws Exception{
Student s1 =new Student(211,"ravi",22);//creating object
//writing object into file
FileOutputStream f=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(f);
out.writeObject(s1);
out.flush();
out.close();
f.close();
System.out.println("success");
}
}
Output:
success
Now write the code for deserialization.
1.
2.
3.
4.
5.
6.
7.
8.
9.
import java.io.*;
class DePersist{
public static void main(String args[])throws Exception{
ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
Student s=(Student)in.readObject();
System.out.println(s.id+" "+s.name+" "+s.age);
in.close();
}
}
211 ravi 0
As you can see, printing age of the student returns 0 because value of age was not
serialized.
Next TopicJava Networking
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.
Do You Know ?
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
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.
URL class
InetAddress class
Java Socket programming is used for communication between the applications running
on different JRE.
Java Socket programming can be connection-oriented or connection-less.
Socket and ServerSocket classes are used for connection-oriented socket programming
and DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.
The client in socket programming must know two information:
1. IP Address of Server, and
2. Port number.
Socket class
A socket is simply an endpoint for communications between the machines. The Socket
class can be used to create a socket.
Important methods
Method
Description
1) public InputStream
getInputStream()
socket.
2) public OutputStream
getOutputStream()
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
1) public Socket accept()
Description
returns the socket and establish a connection
between server and client.
close()
File: MyServer.java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}
File: MyClient.java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}
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.
File: MyServer.java
1.
2.
3.
4.
5.
6.
import java.net.*;
import java.io.*;
class MyServer{
public static void main(String args[])throws Exception{
ServerSocket ss=new ServerSocket(3333);
Socket s=ss.accept();
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
File: MyClient.java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
import java.net.*;
import java.io.*;
class MyClient{
public static void main(String args[])throws Exception{
Socket s=new Socket("localhost",3333);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop")){
str=br.readLine();
dout.writeUTF(str);
dout.flush();
str2=din.readUTF();
System.out.println("Server says: "+str2);
}
dout.close();
s.close();
}}
Next TopicURL class
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.javatpoint.com/java-tutorial
A URL contains many information:
1. Protocol: In this case, http is the protocol.
2. Server name or IP Address: In this case, www.javatpoint.com is the server
name.
3. Port Number: It is an optional attribute. If we write
http//ww.javatpoint.com:80/sonoojaiswal/ , 80 is the port number. If port number
is not mentioned in the URL, it returns -1.
4. File Name or directory name: In this case, index.jsp is the file name.
Method
Description
public URLConnection
penConnection()
//URLDemo.java
import java.io.*;
import java.net.*;
public class URLDemo{
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/java-tutorial");
System.out.println("Protocol: "+url.getProtocol());
System.out.println("Host Name: "+url.getHost());
System.out.println("Port Number: "+url.getPort());
System.out.println("File Name: "+url.getFile());
13.
14.
15.
16.
}catch(Exception e){System.out.println(e);}
}
}
Test it Now
Output:
Protocol: http
Host Name: www.javatpoint.com
Port Number: -1
File Name: /java-tutorial
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
import java.io.*;
import java.net.*;
public class URLConnectionExample {
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/java-tutorial");
URLConnection urlcon=url.openConnection();
InputStream stream=urlcon.getInputStream();
int i;
while((i=stream.read())!=-1){
System.out.print((char)i);
}
}catch(Exception e){System.out.println(e);}
}
}
1.
2.
import java.io.*;
import java.net.*;
public class HttpURLConnectionDemo{
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/java-tutorial");
HttpURLConnection huc=(HttpURLConnection)url.openConnection();
for(int i=1;i<=8;i++){
System.out.println(huc.getHeaderFieldKey(i)+" = "+huc.getHeaderField(i));
}
huc.disconnect();
}catch(Exception e){System.out.println(e);}
}
}
Test it Now
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
Next TopicInetAddress class
Description
UnknownHostException
public static InetAddress
getLocalHost() throws
UnknownHostException
public String getHostName()
import java.io.*;
import java.net.*;
public class InetDemo{
public static void main(String[] args){
try{
InetAddress ip=InetAddress.getByName("www.javatpoint.com");
System.out.println("Host Name: "+ip.getHostName());
System.out.println("IP Address: "+ip.getHostAddress());
}catch(Exception e){System.out.println(e);}
}
}
Test it Now
Output:
Host Name: www.javatpoint.com
IP Address: 206.51.231.148
//DSender.java
import java.net.*;
3.
4.
5.
6.
7.
8.
9.
00);
10.
11.
12.
13.
ds.send(dp);
ds.close();
}
//DReceiver.java
import java.net.*;
public class DReceiver{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp);
String str = new String(dp.getData(), 0, dp.getLength());
System.out.println(str);
ds.close();
}
}
The java.awt package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
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.
Description
public void setLayout(LayoutManager m) defines the layout manager for the component.
public void setVisible(boolean status)
import java.awt.*;
class First extends Frame{
First(){
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
}
public static void main(String args[]){
First f=new First();
}}
import java.awt.*;
class First2{
First2(){
Frame f=new Frame();
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
Event Classes
Listener Interfaces
ActionEvent
ActionListener
MouseEvent
MouseWheelEvent
MouseWheelListener
KeyEvent
KeyListener
ItemEvent
ItemListener
TextEvent
TextListener
AdjustmentEvent
AdjustmentListener
WindowEvent
WindowListener
ComponentEvent
ComponentListener
ContainerEvent
ContainerListener
FocusEvent
FocusListener
2.
For registering the component with the Listener, many classes provide the registration
methods. For example:
o
Button
public void addActionListener(ActionListener a){}
o
o
MenuItem
public void addActionListener(ActionListener a){}
o
o
TextField
TextArea
public void addTextListener(TextListener a){}
o
o
Checkbox
public void addItemListener(ItemListener a){}
o
o
Choice
public void addItemListener(ItemListener a){}
o
o
List
EventHandling Codes:
We can put the event handling code into one of the following places:
Same class
Other class
Annonymous class
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
b.addActionListener(this);
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
}
}
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.
import java.awt.*;
import java.awt.event.*;
class AEvent2 extends Frame{
TextField tf;
AEvent2(){
1.
2.
3.
4.
5.
6.
import java.awt.event.*;
class Outer implements ActionListener{
AEvent2 obj;
Outer(AEvent2 obj){
this.obj=obj;
}
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
Outer o=new Outer(this);
b.addActionListener(o);//passing outer class instance
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent2();
}
}
7.
8.
9.
10.
import java.awt.*;
import java.awt.event.*;
class AEvent3 extends Frame{
TextField tf;
AEvent3(){
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(50,120,80,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(){
tf.setText("hello");
}
});
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent3();
}
}
No
.
Java AWT
Java Swing
Java swing components are platformindependent.
and feel.
4) AWT provides less components than
Swing.
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.
Do You Know
o
Method
Description
public void setLayout(LayoutManager m) sets the layout manager for the component.
public void setVisible(boolean b)
File: FirstSwingExample.java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButton
b.setBounds(130,100,100, 40);//x axis, y axis, width, height
f.add(b);//adding button in JFrame
f.setSize(400,500);//400 width and 500 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
}
File: Simple.java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
import javax.swing.*;
public class Simple {
JFrame f;
Simple(){
f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButton
b.setBounds(130,100,100, 40);
f.add(b);//adding button in JFrame
f.setSize(400,500);//400 width and 500 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
public static void main(String[] args) {
new Simple();
}
}
The setBounds(int xaxis, int yaxis, int width, int height)is used in the above example that
sets the position of the button.
File: Simple2.java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
import javax.swing.*;
public class Simple2 extends JFrame{//inheriting JFrame
JFrame f;
Simple2(){
JButton b=new JButton("click");//create button
b.setBounds(130,100,100, 40);
add(b);//adding button on frame
setSize(400,500);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
14.
15.
new Simple2();
}}
JButton class
JRadioButton class
JTextArea class
JComboBox class
JTable class
JColorChooser class
JProgressBar class
JSlider class
Digital Watch
Graphics in swing
Displaying image
OpenDialog Box
Notepad
Puzzle Game
BorderLayout
GridLayout
FlowLayout
CardLayout
Next TopicJButton Class
JButton class:
The JButton class is used to create a button that have plateform-independent
implementation.
import java.awt.event.*;
import javax.swing.*;
public class ImageButton{
ImageButton(){
JFrame f=new JFrame();
JButton b=new JButton(new ImageIcon("b.jpg"));
b.setBounds(130,100,100, 40);
f.add(b);
f.setSize(300,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
20.
21.
22.
23.
24.
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.
import javax.swing.*;
public class Radio {
JFrame f;
Radio(){
f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) FeMale");
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
r1.setBounds(50,100,70,30);
r2.setBounds(50,150,70,30);
ButtonGroup bg=new ButtonGroup();
bg.add(r1);bg.add(r2);
f.add(r1);f.add(r2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new Radio();
}
}
ButtonGroup class:
The ButtonGroup class can be used to group multiple buttons so that at a time only one
button can be selected.
import javax.swing.*;
import java.awt.event.*;
class RadioExample extends JFrame implements ActionListener{
JRadioButton rb1,rb2;
JButton b;
RadioExample(){
rb1=new JRadioButton("Male");
rb1.setBounds(100,50,100,30);
rb2=new JRadioButton("Female");
rb2.setBounds(100,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(rb1);bg.add(rb2);
b=new JButton("click");
b.setBounds(100,150,80,30);
b.addActionListener(this);
add(rb1);add(rb2);add(b);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(rb1.isSelected()){
JOptionPane.showMessageDialog(this,"You are male");
30.
31.
32.
33.
34.
35.
36.
37.
}
if(rb2.isSelected()){
JOptionPane.showMessageDialog(this,"You are female");
}
}
public static void main(String args[]){
new RadioExample();
}}
Next TopicJTextArea-class
JTextArea(String s): creates a text area that displays specified text initially.
JTextArea(int row, int column): creates a text area with the specified number
of rows and columns that displays no text initially..
JTextArea(String s, int row, int column): creates a text area with the
specified number of rows and columns that displays specified text.
import java.awt.Color;
import javax.swing.*;
public class TArea {
JTextArea area;
JFrame f;
TArea(){
f=new JFrame();
area=new JTextArea(300,300);
area.setBounds(10,30,300,300);
area.setBackground(Color.black);
area.setForeground(Color.white);
f.add(area);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
public static void main(String[] args) {
new TArea();
}
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.
import javax.swing.*;
public class Combo {
JFrame f;
Combo(){
f=new JFrame("Combo ex");
String country[]={"India","Aus","U.S.A","England","Newzeland"};
JComboBox cb=new JComboBox(country);
cb.setBounds(50, 50,90,20);
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
}
public static void main(String[] args) {
new Combo();
20.
21.
22.
}
}
import javax.swing.*;
public class MyTable {
JFrame f;
MyTable(){
f=new JFrame();
String data[][]={ {"101","Amit","670000"},
{"102","Jai","780000"},
{"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"};
JTable jt=new JTable(data,column);
jt.setBounds(30,40,200,300);
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
// f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new MyTable();
}
}
JColorChooser class:
The JColorChooser class is used to create a color chooser dialog box so that user can
select any color.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class JColorChooserExample extends JFrame implements ActionListener
{
JButton b;
Container c;
JColorChooserExample(){
c=getContentPane();
c.setLayout(new FlowLayout());
b=new JButton("color");
b.addActionListener(this);
c.add(b);
}
public void actionPerformed(ActionEvent e) {
Color initialcolor=Color.RED;
Color color=JColorChooser.showDialog(this,"Select a color",initialcolor);
c.setBackground(color);
}
25.
26.
27.
28.
29.
30.
31.
JProgressBar class:
The JProgressBar class is used to display the progress of the task.
JProgressBar(int orient, int min, int max): is used to create a progress bar
with the specified orientation, minimum and maximum value.
import javax.swing.*;
public class MyProgress extends JFrame{
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
JProgressBar jb;
int i=0,num=0;
MyProgress(){
jb=new JProgressBar(0,2000);
jb.setBounds(40,40,200,30);
jb.setValue(0);
jb.setStringPainted(true);
add(jb);
setSize(400,400);
setLayout(null);
}
public void iterate(){
while(i<=2000){
jb.setValue(i);
i=i+20;
try{Thread.sleep(150);}catch(Exception e){}
}
}
public static void main(String[] args) {
MyProgress m=new MyProgress();
m.setVisible(true);
m.iterate();
}
}
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.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
import javax.swing.*;
public class SliderExample1 extends JFrame{
public SliderExample1() {
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25);
JPanel panel=new JPanel();
panel.add(slider);
add(panel);
}
public static void main(String s[]) {
SliderExample1 frame=new SliderExample1();
frame.pack();
frame.setVisible(true);
}
}
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
import javax.swing.*;
public class SliderExample extends JFrame{
public SliderExample() {
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25);
slider.setMinorTickSpacing(2);
slider.setMajorTickSpacing(10);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
JPanel panel=new JPanel();
panel.add(slider);
add(panel);
}
public static void main(String s[]) {
SliderExample frame=new SliderExample();
frame.pack();
frame.setVisible(true);
}
}
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
import javax.swing.*;
import java.awt.*;
import java.text.*;
import java.util.*;
public class DigitalWatch implements Runnable{
JFrame f;
Thread t=null;
int hours=0, minutes=0, seconds=0;
String timeString = "";
JButton b;
DigitalWatch(){
f=new JFrame();
t = new Thread(this);
t.start();
b=new JButton();
b.setBounds(100,100,100,50);
f.add(b);
f.setSize(300,400);
f.setLayout(null);
f.setVisible(true);
}
public void run() {
try {
while (true) {
Calendar cal = Calendar.getInstance();
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
}
catch (Exception e) { }
oval with the default color and specified width and height.
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).
public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer): is used draw the specified image.
public abstract void drawArc(int x, int y, int width, int height, int
startAngle, int arcAngle): is used draw a circular or elliptical arc.
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.
2.
3.
4.
5.
6.
7.
8.
9.
10.
import java.awt.*;
import javax.swing.JFrame;
public class DisplayGraphics extends Canvas{
public void paint(Graphics g) {
g.drawString("Hello",40,40);
setBackground(Color.WHITE);
g.fillRect(130, 30,100, 80);
g.drawOval(30,130,50, 60);
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
setForeground(Color.RED);
g.fillOval(130,130,50, 60);
g.drawArc(30, 200, 40,50,90,60);
g.fillArc(30, 130, 40,50,180,40);
}
1.
2.
3.
4.
5.
6.
7.
8.
import java.awt.*;
import javax.swing.JFrame;
public class MyCanvas extends Canvas{
public void paint(Graphics g) {
Toolkit t=Toolkit.getDefaultToolkit();
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
Image i=t.getImage("p3.gif");
g.drawImage(i, 120,100,this);
}
public static void main(String[] args) {
MyCanvas m=new MyCanvas();
JFrame f=new JFrame();
f.add(m);
f.setSize(400,400);
f.setVisible(true);
}
}
import javax.swing.*;
import java.awt.event.*;
public class Notepad implements ActionListener{
JFrame f;
JMenuBar mb;
JMenu file,edit,help;
JMenuItem cut,copy,paste,selectAll;
JTextArea ta;
Notepad(){
f=new JFrame();
cut=new JMenuItem("cut");
copy=new JMenuItem("copy");
paste=new JMenuItem("paste");
selectAll=new JMenuItem("selectAll");
cut.addActionListener(this);
copy.addActionListener(this);
paste.addActionListener(this);
selectAll.addActionListener(this);
mb=new JMenuBar();
mb.setBounds(5,5,400,40);
file=new JMenu("File");
edit=new JMenu("Edit");
help=new JMenu("Help");
edit.add(cut);edit.add(copy);edit.add(paste);edit.add(selectAll);
mb.add(file);mb.add(edit);mb.add(help);
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
ta=new JTextArea();
ta.setBounds(5,30,460,460);
f.add(mb);f.add(ta);
f.setLayout(null);
f.setSize(500,500);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==cut)
ta.cut();
if(e.getSource()==paste)
ta.paste();
if(e.getSource()==copy)
ta.copy();
if(e.getSource()==selectAll)
ta.selectAll();
}
public static void main(String[] args) {
new Notepad();
}
}
import
import
import
import
java.awt.*;
javax.swing.*;
java.awt.event.*;
java.io.*;
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
ta=new JTextArea(800,800);
ta.setBounds(0,20,800,800);
add(mb);
add(ta);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==open){
openFile();
}
}
void openFile(){
JFileChooser fc=new JFileChooser();
int i=fc.showOpenDialog(this);
if(i==JFileChooser.APPROVE_OPTION){
File f=fc.getSelectedFile();
String filepath=f.getPath();
displayContent(filepath);
}
}
void displayContent(String fpath){
try{
BufferedReader br=new BufferedReader(new FileReader(fpath));
String s1="",s2="";
while((s1=br.readLine())!=null){
s2+=s1+"\n";
}
ta.setText(s2);
br.close();
}catch (Exception e) {e.printStackTrace(); }
}
public static void main(String[] args) {
OpenMenu om=new OpenMenu();
om.setSize(800,800);
om.setLayout(null);
om.setVisible(true);
om.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Example of Notepad
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
import
import
import
import
import
import
java.io.*;
java.util.Date;
java.awt.*;
java.awt.event.*;
javax.swing.*;
javax.swing.event.*;
/************************************/
class FileOperation
{
Notepad npd;
boolean saved;
boolean newFileFlag;
String fileName;
String applicationTitle="Javapad";
File fileRef;
JFileChooser chooser;
/////////////////////////////
boolean isSave(){return saved;}
void setSave(boolean saved){this.saved=saved;}
String getFileName(){return new String(fileName);}
void setFileName(String fileName){this.fileName=new String(fileName);}
/////////////////////////
FileOperation(Notepad npd)
{
this.npd=npd;
saved=true;
newFileFlag=true;
fileName=new String("Untitled");
fileRef=new File(fileName);
this.npd.f.setTitle(fileName+" - "+applicationTitle);
)"));
chooser=new JFileChooser();
chooser.addChoosableFileFilter(new MyFileFilter(".java","Java Source Files(*.java
chooser.addChoosableFileFilter(new MyFileFilter(".txt","Text Files(*.txt)"));
chooser.setCurrentDirectory(new File("."));
}
//////////////////////////////////////
boolean saveFile(File temp)
{
FileWriter fout=null;
try
{
fout=new FileWriter(temp);
fout.write(npd.ta.getText());
}
catch(IOException ioe){updateStatus(temp,false);return false;}
finally
{try{fout.close();}catch(IOException excp){}}
updateStatus(temp,true);
return true;
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
}
////////////////////////
boolean saveThisFile()
{
if(!newFileFlag)
{return saveFile(fileRef);}
return saveAsFile();
}
////////////////////////////////////
boolean saveAsFile()
{
File temp=null;
chooser.setDialogTitle("Save As...");
chooser.setApproveButtonText("Save Now");
chooser.setApproveButtonMnemonic(KeyEvent.VK_S);
chooser.setApproveButtonToolTipText("Click me to save!");
do
{
if(chooser.showSaveDialog(this.npd.f)!=JFileChooser.APPROVE_OPTION)
return false;
temp=chooser.getSelectedFile();
if(!temp.exists()) break;
if( JOptionPane.showConfirmDialog(
this.npd.f,"<html>"+temp.getPath()+" already exists.<br>Do you want to rep
lace it?<html>",
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.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
break;
JOptionPane.showMessageDialog(this.npd.f,
"<html>"+temp.getName()+"<br>file not found.<br>"+
"Please verify the correct file name was given.<html>",
"Open", JOptionPane.INFORMATION_MESSAGE);
} while(true);
this.npd.ta.setText("");
if(!openFile(temp))
{
fileName="Untitled"; saved=true;
this.npd.f.setTitle(fileName+" - "+applicationTitle);
}
if(!temp.canWrite())
newFileFlag=true;
}
////////////////////////
void updateStatus(File temp,boolean saved)
{
if(saved)
{
this.saved=true;
fileName=new String(temp.getName());
if(!temp.canWrite())
{fileName+="(Read only)"; newFileFlag=true;}
fileRef=temp;
npd.f.setTitle(fileName + " - "+applicationTitle);
npd.statusBar.setText("File : "+temp.getPath()+" saved/opened successfully.");
newFileFlag=false;
}
170.
171.
172.
173.
174.
175.
176.
177.
178.
+
179.
180.
181.
182.
183.
184.
185.
186.
187.
188.
189.
190.
191.
192.
193.
194.
195.
196.
197.
198.
199.
200.
201.
202.
203.
204.
205.
206.
207.
208.
209.
210.
211.
212.
213.
214.
215.
216.
217.
218.
219.
220.
221.
222.
223.
224.
225.
else
{
npd.statusBar.setText("Failed to save/open : "+temp.getPath());
}
}
///////////////////////
boolean confirmSave()
{
String strMsg="<html>The text in the "+fileName+" file has been changed.<br>"
"Do you want to save the changes?<html>";
if(!saved)
{
int x=JOptionPane.showConfirmDialog(this.npd.f,strMsg,applicationTitle,
JOptionPane.YES_NO_CANCEL_OPTION);
if(x==JOptionPane.CANCEL_OPTION) return false;
if(x==JOptionPane.YES_OPTION && !saveAsFile()) return false;
}
return true;
}
///////////////////////////////////////
void newFile()
{
if(!confirmSave()) return;
this.npd.ta.setText("");
fileName=new String("Untitled");
fileRef=new File(fileName);
saved=true;
newFileFlag=true;
this.npd.f.setTitle(fileName+" - "+applicationTitle);
}
//////////////////////////////////////
}// end defination of class FileOperation
/************************************/
public class Notepad implements ActionListener, MenuConstants
{
JFrame f;
JTextArea ta;
JLabel statusBar;
private String fileName="Untitled";
private boolean saved=true;
String applicationName="Javapad";
String searchString, replaceString;
int lastSearchIndex;
FileOperation fileHandler;
FontChooser fontDialog=null;
FindDialog findReplaceDialog=null;
JColorChooser bcolorChooser=null;
JColorChooser fcolorChooser=null;
JDialog backgroundDialog=null;
JDialog foregroundDialog=null;
226.
227.
228.
229.
230.
231.
232.
233.
234.
235.
236.
237.
238.
239.
240.
241.
242.
243.
244.
245.
246.
247.
248.
249.
250.
251.
252.
253.
254.
255.
256.
257.
258.
259.
260.
261.
262.
263.
264.
265.
266.
267.
268.
269.
270.
271.
272.
273.
274.
275.
276.
277.
278.
279.
280.
281.
282.
283.
284.
285.
286.
287.
288.
289.
290.
291.
292.
293.
294.
295.
296.
297.
298.
299.
300.
301.
ber);
302.
303.
304.
305.
306.
307.
308.
309.
310.
311.
312.
313.
314.
315.
316.
317.
318.
319.
320.
321.
322.
323.
324.
325.
326.
327.
328.
329.
330.
331.
332.
333.
334.
335.
336.
337.
338.
f.addWindowListener(frameClose);
//////////////////
/*
ta.append("Hello dear hello hi");
ta.append("\nwho are u dear mister hello");
ta.append("\nhello bye hel");
ta.append("\nHello");
ta.append("\nMiss u mister hello hell");
fileHandler.saved=true;
*/
}
////////////////////////////////////
void goTo()
{
int lineNumber=0;
try
{
lineNumber=ta.getLineOfOffset(ta.getCaretPosition())+1;
String tempStr=JOptionPane.showInputDialog(f,"Enter Line Number:",""+lineNum
if(tempStr==null)
{return;}
lineNumber=Integer.parseInt(tempStr);
ta.setCaretPosition(ta.getLineStartOffset(lineNumber-1));
}catch(Exception e){}
}
///////////////////////////////////
public void actionPerformed(ActionEvent ev)
{
String cmdText=ev.getActionCommand();
////////////////////////////////////
if(cmdText.equals(fileNew))
fileHandler.newFile();
else if(cmdText.equals(fileOpen))
fileHandler.openFile();
////////////////////////////////////
else if(cmdText.equals(fileSave))
fileHandler.saveThisFile();
////////////////////////////////////
else if(cmdText.equals(fileSaveAs))
fileHandler.saveAsFile();
////////////////////////////////////
else if(cmdText.equals(fileExit))
{if(fileHandler.confirmSave())System.exit(0);}
////////////////////////////////////
else if(cmdText.equals(filePrint))
JOptionPane.showMessageDialog(
Notepad.this.f,
"Get ur printer repaired first! It seems u dont have one!",
"Bad Printer",
JOptionPane.INFORMATION_MESSAGE
);
////////////////////////////////////
else if(cmdText.equals(editCut))
ta.cut();
////////////////////////////////////
else if(cmdText.equals(editCopy))
339.
340.
341.
342.
343.
344.
345.
346.
347.
348.
349.
350.
351.
352.
353.
354.
355.
356.
357.
358.
359.
360.
361.
362.
363.
364.
365.
366.
367.
368.
369.
370.
371.
372.
373.
374.
375.
376.
377.
378.
379.
380.
381.
382.
383.
384.
385.
386.
387.
388.
389.
390.
391.
392.
393.
394.
395.
ta.copy();
////////////////////////////////////
else if(cmdText.equals(editPaste))
ta.paste();
////////////////////////////////////
else if(cmdText.equals(editDelete))
ta.replaceSelection("");
////////////////////////////////////
else if(cmdText.equals(editFind))
{
if(Notepad.this.ta.getText().length()==0)
return; // text box have no text
if(findReplaceDialog==null)
findReplaceDialog=new FindDialog(Notepad.this.ta);
findReplaceDialog.showDialog(Notepad.this.f,true);//find
}
////////////////////////////////////
else if(cmdText.equals(editFindNext))
{
if(Notepad.this.ta.getText().length()==0)
return; // text box have no text
if(findReplaceDialog==null)
statusBar.setText("Use Find option of Edit Menu first !!!!");
else
findReplaceDialog.findNextWithSelection();
}
////////////////////////////////////
else if(cmdText.equals(editReplace))
{
if(Notepad.this.ta.getText().length()==0)
return; // text box have no text
if(findReplaceDialog==null)
findReplaceDialog=new FindDialog(Notepad.this.ta);
findReplaceDialog.showDialog(Notepad.this.f,false);//replace
}
////////////////////////////////////
else if(cmdText.equals(editGoTo))
{
if(Notepad.this.ta.getText().length()==0)
return; // text box have no text
goTo();
}
////////////////////////////////////
else if(cmdText.equals(editSelectAll))
ta.selectAll();
////////////////////////////////////
else if(cmdText.equals(editTimeDate))
ta.insert(new Date().toString(),ta.getSelectionStart());
////////////////////////////////////
else if(cmdText.equals(formatWordWrap))
{
JCheckBoxMenuItem temp=(JCheckBoxMenuItem)ev.getSource();
ta.setLineWrap(temp.isSelected());
}
////////////////////////////////////
396.
397.
398.
399.
400.
401.
402.
403.
404.
405.
406.
407.
408.
409.
410.
411.
412.
413.
414.
415.
416.
417.
418.
419.
420.
421.
422.
423.
424.
425.
426.
427.
428.
429.
430.
431.
432.
433.
434.
435.
436.
437.
438.
439.
440.
441.
442.
443.
444.
445.
446.
447.
448.
449.
450.
451.
452.
else if(cmdText.equals(formatFont))
{
if(fontDialog==null)
fontDialog=new FontChooser(ta.getFont());
if(fontDialog.showDialog(Notepad.this.f,"Choose a font"))
Notepad.this.ta.setFont(fontDialog.createFont());
}
////////////////////////////////////
else if(cmdText.equals(formatForeground))
showForegroundColorDialog();
////////////////////////////////////
else if(cmdText.equals(formatBackground))
showBackgroundColorDialog();
////////////////////////////////////
else if(cmdText.equals(viewStatusBar))
{
JCheckBoxMenuItem temp=(JCheckBoxMenuItem)ev.getSource();
statusBar.setVisible(temp.isSelected());
}
////////////////////////////////////
else if(cmdText.equals(helpAboutNotepad))
{
JOptionPane.showMessageDialog(Notepad.this.f,aboutText,"Dedicated 2 u!",
JOptionPane.INFORMATION_MESSAGE);
}
else
statusBar.setText("This "+cmdText+" command is yet to be implemented");
}//action Performed
////////////////////////////////////
void showBackgroundColorDialog()
{
if(bcolorChooser==null)
bcolorChooser=new JColorChooser();
if(backgroundDialog==null)
backgroundDialog=JColorChooser.createDialog
(Notepad.this.f,
formatBackground,
false,
bcolorChooser,
new ActionListener()
{public void actionPerformed(ActionEvent evvv){
Notepad.this.ta.setBackground(bcolorChooser.getColor());}},
null);
backgroundDialog.setVisible(true);
}
////////////////////////////////////
void showForegroundColorDialog()
{
if(fcolorChooser==null)
fcolorChooser=new JColorChooser();
if(foregroundDialog==null)
foregroundDialog=JColorChooser.createDialog
(Notepad.this.f,
formatForeground,
453.
false,
454.
fcolorChooser,
455.
new ActionListener()
456.
{public void actionPerformed(ActionEvent evvv){
457.
Notepad.this.ta.setForeground(fcolorChooser.getColor());}},
458.
null);
459.
460.
foregroundDialog.setVisible(true);
461.
}
462.
463.
///////////////////////////////////
464.
JMenuItem createMenuItem(String s, int key,JMenu toMenu,ActionListener al)
465.
{
466.
JMenuItem temp=new JMenuItem(s,key);
467.
temp.addActionListener(al);
468.
toMenu.add(temp);
469.
470.
return temp;
471.
}
472.
////////////////////////////////////
473.
JMenuItem createMenuItem(String s, int key,JMenu toMenu,int aclKey,ActionListe
ner al)
474.
{
475.
JMenuItem temp=new JMenuItem(s,key);
476.
temp.addActionListener(al);
477.
temp.setAccelerator(KeyStroke.getKeyStroke(aclKey,ActionEvent.CTRL_MASK));
478.
toMenu.add(temp);
479.
480.
return temp;
481.
}
482.
////////////////////////////////////
483.
JCheckBoxMenuItem createCheckBoxMenuItem(String s,
484.
int key,JMenu toMenu,ActionListener al)
485.
{
486.
JCheckBoxMenuItem temp=new JCheckBoxMenuItem(s);
487.
temp.setMnemonic(key);
488.
temp.addActionListener(al);
489.
temp.setSelected(false);
490.
toMenu.add(temp);
491.
492.
return temp;
493.
}
494.
////////////////////////////////////
495.
JMenu createMenu(String s,int key,JMenuBar toMenuBar)
496.
{
497.
JMenu temp=new JMenu(s);
498.
temp.setMnemonic(key);
499.
toMenuBar.add(temp);
500.
return temp;
501.
}
502.
/*********************************/
503.
void createMenuBar(JFrame f)
504.
{
505.
JMenuBar mb=new JMenuBar();
506.
JMenuItem temp;
507.
508.
JMenu fileMenu=createMenu(fileText,KeyEvent.VK_F,mb);
509.
510.
511.
512.
513.
514.
515.
516.
517.
518.
519.
520.
521.
522.
523.
524.
525.
526.
527.
528.
JMenu
JMenu
JMenu
JMenu
editMenu=createMenu(editText,KeyEvent.VK_E,mb);
formatMenu=createMenu(formatText,KeyEvent.VK_O,mb);
viewMenu=createMenu(viewText,KeyEvent.VK_V,mb);
helpMenu=createMenu(helpText,KeyEvent.VK_H,mb);
createMenuItem(fileNew,KeyEvent.VK_N,fileMenu,KeyEvent.VK_N,this);
createMenuItem(fileOpen,KeyEvent.VK_O,fileMenu,KeyEvent.VK_O,this);
createMenuItem(fileSave,KeyEvent.VK_S,fileMenu,KeyEvent.VK_S,this);
createMenuItem(fileSaveAs,KeyEvent.VK_A,fileMenu,this);
fileMenu.addSeparator();
temp=createMenuItem(filePageSetup,KeyEvent.VK_U,fileMenu,this);
temp.setEnabled(false);
createMenuItem(filePrint,KeyEvent.VK_P,fileMenu,KeyEvent.VK_P,this);
fileMenu.addSeparator();
createMenuItem(fileExit,KeyEvent.VK_X,fileMenu,this);
temp=createMenuItem(editUndo,KeyEvent.VK_U,editMenu,KeyEvent.VK_Z,this);
temp.setEnabled(false);
editMenu.addSeparator();
cutItem=createMenuItem(editCut,KeyEvent.VK_T,editMenu,KeyEvent.VK_X,this);
529.
copyItem=createMenuItem(editCopy,KeyEvent.VK_C,editMenu,KeyEvent.VK_C,th
is);
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,this)
;
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.VK
_H,this);
538.
gotoItem=createMenuItem(editGoTo,KeyEvent.VK_G,editMenu,KeyEvent.VK_G,th
is);
539.
editMenu.addSeparator();
540.
selectAllItem=createMenuItem(editSelectAll,KeyEvent.VK_A,editMenu,KeyEvent.V
K_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.
560.
561.
562.
563.
564.
565.
566.
567.
568.
569.
570.
571.
572.
573.
574.
575.
576.
577.
578.
579.
580.
581.
582.
583.
584.
585.
586.
587.
588.
589.
590.
591.
592.
593.
594.
595.
596.
597.
598.
599.
600.
601.
602.
603.
604.
605.
606.
607.
608.
609.
610.
611.
612.
613.
614.
615.
createMenuItem(helpAboutNotepad,KeyEvent.VK_A,helpMenu,this);
MenuListener editMenuListener=new MenuListener()
{
public void menuSelected(MenuEvent evvvv)
{
if(Notepad.this.ta.getText().length()==0)
{
findItem.setEnabled(false);
findNextItem.setEnabled(false);
replaceItem.setEnabled(false);
selectAllItem.setEnabled(false);
gotoItem.setEnabled(false);
}
else
{
findItem.setEnabled(true);
findNextItem.setEnabled(true);
replaceItem.setEnabled(true);
selectAllItem.setEnabled(true);
gotoItem.setEnabled(true);
}
if(Notepad.this.ta.getSelectionStart()==ta.getSelectionEnd())
{
cutItem.setEnabled(false);
copyItem.setEnabled(false);
deleteItem.setEnabled(false);
}
else
{
cutItem.setEnabled(true);
copyItem.setEnabled(true);
deleteItem.setEnabled(true);
}
}
public void menuDeselected(MenuEvent evvvv){}
public void menuCanceled(MenuEvent evvvv){}
};
editMenu.addMenuListener(editMenuListener);
f.setJMenuBar(mb);
}
/*************Constructor**************/
////////////////////////////////////
public static void main(String[] s)
{
new Notepad();
}
}
/**************************************/
//public
interface MenuConstants
{
final String fileText="File";
final String editText="Edit";
final String formatText="Format";
final String viewText="View";
final String helpText="Help";
616.
617.
618.
619.
620.
621.
622.
623.
624.
625.
626.
627.
628.
629.
630.
631.
632.
633.
634.
635.
636.
637.
638.
639.
640.
641.
642.
643.
644.
645.
646.
647.
648.
final
final
final
final
final
final
final
String
String
String
String
String
String
String
fileNew="New";
fileOpen="Open...";
fileSave="Save";
fileSaveAs="Save As...";
filePageSetup="Page Setup...";
filePrint="Print";
fileExit="Exit";
final
final
final
final
final
final
final
final
final
final
final
String
String
String
String
String
String
String
String
String
String
String
editUndo="Undo";
editCut="Cut";
editCopy="Copy";
editPaste="Paste";
editDelete="Delete";
editFind="Find...";
editFindNext="Find Next";
editReplace="Replace";
editGoTo="Go To...";
editSelectAll="Select All";
editTimeDate="Time/Date";
final
final
final
final
String
String
String
String
formatWordWrap="Word Wrap";
formatFont="Font...";
formatForeground="Set Text color...";
formatBackground="Set Pad color...";
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class puzzle extends JFrame implements ActionListener{
JButton b1,b2,b3,b4,b5,b6,b7,b8,b9,next;
puzzle(){
super("puzzle");
b1=new JButton("1");
b2=new JButton(" ");
b3=new JButton("3");
b4=new JButton("4");
b5=new JButton("5");
b6=new JButton("6");
b7=new JButton("7");
b8=new JButton("8");
b9=new JButton("2");
next=new JButton("next");
b1.setBounds(10,30,50,40);
b2.setBounds(70,30,50,40);
b3.setBounds(130,30,50,40);
b4.setBounds(10,80,50,40);
b5.setBounds(70,80,50,40);
b6.setBounds(130,80,50,40);
b7.setBounds(10,130,50,40);
b8.setBounds(70,130,50,40);
b9.setBounds(130,130,50,40);
next.setBounds(70,200,100,40);
add(b1);add(b2);add(b3);add(b4);add(b5);add(b6);add(b7);add(b8);add(b9); a
dd(next);
31.
b1.addActionListener(this);
32.
b2.addActionListener(this);
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
b9.addActionListener(this);
next.addActionListener(this);
next.setBackground(Color.black);
next.setForeground(Color.green);
setSize(250,300);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}//end of constructor
public void actionPerformed(ActionEvent e){
if(e.getSource()==next){
String s=b4.getLabel();
b4.setLabel(b9.getLabel());
b9.setLabel(s);
s=b1.getLabel();
b1.setLabel(b5.getLabel());
b5.setLabel(s);
s=b2.getLabel();
b2.setLabel(b7.getLabel());
b7.setLabel(s);
}
if(e.getSource()==b1){
String s=b1.getLabel();
if(b2.getLabel().equals(" ")){ b2.setLabel(s); b1.setLabel(" ");}
else if(b4.getLabel().equals(" ")){ b4.setLabel(s); b1.setLabel(" ");}
}//end of if
if(e.getSource()==b3){
String s=b3.getLabel();
if(b2.getLabel().equals(" ")){ b2.setLabel(s); b3.setLabel(" ");}
else if(b6.getLabel().equals(" ")){ b6.setLabel(s); b3.setLabel(" ");}
}//end of if
if(e.getSource()==b2){
String s=b2.getLabel();
if(b1.getLabel().equals(" ")){ b1.setLabel(s); b2.setLabel(" ");}
else if(b3.getLabel().equals(" ")){ b3.setLabel(s); b2.setLabel(" ");}
else if(b5.getLabel().equals(" ")){ b5.setLabel(s); b2.setLabel(" ");}
}//end of if
if(e.getSource()==b4){
String s=b4.getLabel();
if(b1.getLabel().equals(" ")){ b1.setLabel(s); b4.setLabel(" ");}
else if(b7.getLabel().equals(" ")){ b7.setLabel(s); b4.setLabel(" ");}
else if(b5.getLabel().equals(" ")){ b5.setLabel(s); b4.setLabel(" ");}
}//end of if
if(e.getSource()==b5){
String s=b5.getLabel();
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
class picpuzzle2 extends JFrame implements ActionListener{
JButton b1,b2,b3,b4,b5,b6,b7,b8,b9,sample,starB;
Icon star;
Icon ic0=new ImageIcon("pic/starB0.jpg");
Icon ic10=new ImageIcon("pic/starB10.jpg");
Icon ic20=new ImageIcon("pic/starB20.jpg");
Icon samicon1=new ImageIcon("pic/main.jpg");
Icon samicon2=new ImageIcon("pic/main2.jpg");
Icon samicon3=new ImageIcon("pic/main3.jpg");
Icon ic1=new ImageIcon("pic/1.jpg");
Icon ic2=new ImageIcon("pic/5.jpg");
Icon ic3=new ImageIcon("pic/2.jpg");
Icon ic4=new ImageIcon("pic/7.jpg");
Icon ic5=new ImageIcon("pic/4.jpg");
Icon ic6=new ImageIcon("pic/6.jpg");
Icon ic7=new ImageIcon("pic/8.jpg");
Icon ic8=new ImageIcon("pic/9.jpg");
Icon ic9=new ImageIcon("pic/3.jpg");
Icon ic11=new ImageIcon("pic/12.jpg");
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
Icon
Icon
Icon
Icon
Icon
Icon
Icon
Icon
ic12=new
ic13=new
ic14=new
ic15=new
ic16=new
ic17=new
ic18=new
ic19=new
ImageIcon("pic/13.jpg");
ImageIcon("pic/16.jpg");
ImageIcon("pic/11.jpg");
ImageIcon("pic/14.jpg");
ImageIcon("pic/19.jpg");
ImageIcon("pic/17.jpg");
ImageIcon("pic/15.jpg");
ImageIcon("pic/18.jpg");
Icon
Icon
Icon
Icon
Icon
Icon
Icon
Icon
Icon
ic21=new
ic22=new
ic23=new
ic24=new
ic25=new
ic26=new
ic27=new
ic28=new
ic29=new
ImageIcon("pic/24.jpg");
ImageIcon("pic/25.jpg");
ImageIcon("pic/21.jpg");
ImageIcon("pic/27.jpg");
ImageIcon("pic/23.jpg");
ImageIcon("pic/29.jpg");
ImageIcon("pic/28.jpg");
ImageIcon("pic/22.jpg");
ImageIcon("pic/26.jpg");
picpuzzle2(){
super("pic puzzle");
b1=new JButton(ic1);
b1.setBounds(10,80,100,100);
b2=new JButton(ic2);
b2.setBounds(110,80,100,100);
b3=new JButton(ic3);
b3.setBounds(210,80,100,100);
b4=new JButton(ic4);
b4.setBounds(10,180,100,100);
b5=new JButton(ic5);
b5.setBounds(110,180,100,100);
b6=new JButton(ic6);
b6.setBounds(210,180,100,100);
b7=new JButton(ic7);
b7.setBounds(10,280,100,100);
b8=new JButton(ic8);
b8.setBounds(110,280,100,100);
b9=new JButton(ic9);
b9.setBounds(210,280,100,100);
sample=new JButton(samicon1);
sample.setBounds(380,100,200,200);
JLabel l1=new JLabel("Sample:");
l1.setBounds(330,200,70,20);
JLabel l2=new JLabel("NOTE:
icon has power to swap with neighbour icon=");
l2.setBounds(5,15,500,20);
JLabel l3=new JLabel("click sample picture to next puzzle");
l3.setBounds(380,320,200,20);
l3.setForeground(Color.red);
starB=new JButton(ic0);
starB.setBounds(330,5,50,50);
star=b9.getIcon();
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
add(b1);add(b2);add(b3);add(b4);add(b5);add(b6);add(b7);add(b8);
add(b9);add(sample);add(l1);add(l2);add(starB);add(l3);
b1.addActionListener(this); b2.addActionListener(this);
b3.addActionListener(this); b4.addActionListener(this);
b5.addActionListener(this); b6.addActionListener(this);
b7.addActionListener(this); b8.addActionListener(this);
b9.addActionListener(this);
sample.addActionListener(this);
setLayout(null);
setSize(600,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==b1){
Icon s1=b1.getIcon();
if(b2.getIcon()==star){
b2.setIcon(s1);
b1.setIcon(star);
} else if(b4.getIcon()==star){
b4.setIcon(s1);
b1.setIcon(star);
}
}//end of if
if(e.getSource()==b2){
Icon s1=b2.getIcon();
if(b1.getIcon()==star){
b1.setIcon(s1);
b2.setIcon(star);
} else if(b5.getIcon()==star){
b5.setIcon(s1);
b2.setIcon(star);
}
else if(b3.getIcon()==star){
b3.setIcon(s1);
b2.setIcon(star);
}
}//end of if
if(e.getSource()==b3){
Icon s1=b3.getIcon();
if(b2.getIcon()==star){
b2.setIcon(s1);
b3.setIcon(star);
} else if(b6.getIcon()==star){
b6.setIcon(s1);
b3.setIcon(star);
}
}//end of if
if(e.getSource()==b4){
Icon s1=b4.getIcon();
if(b1.getIcon()==star){
b1.setIcon(s1);
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.
183.
184.
185.
186.
187.
188.
189.
190.
191.
192.
193.
194.
b4.setIcon(star);
} else if(b5.getIcon()==star){
b5.setIcon(s1);
b4.setIcon(star);
}
else if(b7.getIcon()==star){
b7.setIcon(s1);
b4.setIcon(star);
}
}//end of if
if(e.getSource()==b5){
Icon s1=b5.getIcon();
if(b2.getIcon()==star){
b2.setIcon(s1);
b5.setIcon(star);
} else if(b4.getIcon()==star){
b4.setIcon(s1);
b5.setIcon(star);
}
else if(b6.getIcon()==star){
b6.setIcon(s1);
b5.setIcon(star);
}
else if(b8.getIcon()==star){
b8.setIcon(s1);
b5.setIcon(star);
}
}//end of if
if(e.getSource()==b6){
Icon s1=b6.getIcon();
if(b3.getIcon()==star){
b3.setIcon(s1);
b6.setIcon(star);
} else if(b5.getIcon()==star){
b5.setIcon(s1);
b6.setIcon(star);
}
else if(b9.getIcon()==star){
b9.setIcon(s1);
b6.setIcon(star);
}
}//end of if
if(e.getSource()==b7){
Icon s1=b7.getIcon();
if(b4.getIcon()==star){
b4.setIcon(s1);
b7.setIcon(star);
} else if(b8.getIcon()==star){
b8.setIcon(s1);
b7.setIcon(star);
}
}//end of if
if(e.getSource()==b8){
195.
196.
197.
198.
199.
200.
201.
202.
203.
204.
205.
206.
207.
208.
209.
210.
211.
212.
213.
214.
215.
216.
217.
218.
219.
220.
221.
222.
223.
224.
225.
226.
227.
228.
229.
230.
231.
232.
233.
234.
235.
236.
237.
238.
239.
240.
241.
242.
243.
244.
245.
246.
247.
248.
249.
250.
251.
Icon s1=b8.getIcon();
if(b7.getIcon()==star){
b7.setIcon(s1);
b8.setIcon(star);
} else if(b5.getIcon()==star){
b5.setIcon(s1);
b8.setIcon(star);
}
else if(b9.getIcon()==star){
b9.setIcon(s1);
b8.setIcon(star);
}
}//end of if
if(e.getSource()==b9){
Icon s1=b9.getIcon();
if(b8.getIcon()==star){
b8.setIcon(s1);
b9.setIcon(star);
} else if(b6.getIcon()==star){
b6.setIcon(s1);
b9.setIcon(star);
}
}//end of if
if(e.getSource()==sample){
Icon s1=sample.getIcon();
if(s1==samicon3){
sample.setIcon(samicon1);
b1.setIcon(ic1);
b2.setIcon(ic2);
b3.setIcon(ic3);
b4.setIcon(ic4);
b5.setIcon(ic5);
b6.setIcon(ic6);
b7.setIcon(ic7);
b8.setIcon(ic8);
b9.setIcon(ic9);
star=b9.getIcon();
starB.setIcon(ic0);
}//eof if
else if(s1==samicon1){
sample.setIcon(samicon2);
b1.setIcon(ic11);
b2.setIcon(ic12);
b3.setIcon(ic13);
b4.setIcon(ic14);
b5.setIcon(ic15);
b6.setIcon(ic16);
b7.setIcon(ic17);
b8.setIcon(ic18);
b9.setIcon(ic19);
star=b6.getIcon();
starB.setIcon(ic10);
}//eof else
else{
252.
253.
254.
255.
256.
257.
258.
259.
260.
261.
262.
263.
264.
265.
266.
267.
268.
269.
270.
271.
272.
sample.setIcon(samicon3);
b1.setIcon(ic21);
b2.setIcon(ic22);
b3.setIcon(ic23);
b4.setIcon(ic24);
b5.setIcon(ic25);
b6.setIcon(ic26);
b7.setIcon(ic27);
b8.setIcon(ic28);
b9.setIcon(ic29);
star=b6.getIcon();
starB.setIcon(ic20);
}//eof else
}
}//end of actionPerformed
public static void main(String args[]){
new picpuzzle2();
}//end of main
}//end of class
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class TTT1 extends JFrame implements ItemListener, ActionListener{
int i,j,ii,jj,x,y,yesnull;
int a[][]={{10,1,2,3,11},{10,1,4,7,11},{10,1,5,9,11},{10,2,5,8,11},
{10,3,5,7,11},{10,3,6,9,11},{10,4,5,6,11},
{10,7,8,9,11} };
int a1[][]={{10,1,2,3,11},{10,1,4,7,11},{10,1,5,9,11},{10,2,5,8,11},
{10,3,5,7,11},{10,3,6,9,11},{10,4,5,6,11},{10,7,8,9,11} };
boolean state,type,set;
Icon ic1,ic2,icon,ic11,ic22;
Checkbox c1,c2;
JLabel l1,l2;
JButton b[]=new JButton[9];
JButton reset;
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
for(j=1;j<=3;j++){
//for2
if(b[(a[i][j]-1)].getIcon()==null){ //if 1
b[(a[i][j]-1)].setIcon(ic2);
this.check(a[i][j]);
set=false;
break;
}
//eof if1
}
//eof for 2
if(set==false)
break;
}//eof elseif
if(set==false)
break;
}//eof for 1
}//eof complogic
/*********************************************************/
TTT1(){
super("tic tac toe by ashwani");
CheckboxGroup cbg=new CheckboxGroup();
c1=new Checkbox("vs computer",cbg,false);
c2=new Checkbox("vs friend",cbg,false);
c1.setBounds(120,80,100,40);
c2.setBounds(120,150,100,40);
add(c1); add(c2);
c1.addItemListener(this);
c2.addItemListener(this);
state=true;type=true;set=true;
ic1=new ImageIcon("ic1.jpg");
ic2=new ImageIcon("ic2.jpg");
ic11=new ImageIcon("ic11.jpg");
ic22=new ImageIcon("ic22.jpg");
setLayout(null);
setSize(330,450);
setVisible(true);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}//eof constructor
/*************************************************************/
public void itemStateChanged(ItemEvent e){
if(c1.getState())
{
type=false;
}
else if(c2.getState())
{ type=true;
}
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.
183.
184.
185.
186.
187.
188.
189.
190.
remove(c1);remove(c2);
repaint(0,0,330,450);
showButton();
}//eof itemstate
/************************************************************/
public void actionPerformed(ActionEvent e){
/********************************/
if(type==true)//logicfriend
{
if(e.getSource()==reset){
for(i=0;i<=8;i++){
b[i].setIcon(null);
}//eof for
}
else{
for(i=0;i<=8;i++){
if(e.getSource()==b[i]){
if(b[i].getIcon()==null){
if(state==true){ icon=ic2;
state=false;} else{ icon=ic1; state=true; }
b[i].setIcon(icon);
}
}
}//eof for
}//eof else
}//eof logicfriend
else if(type==false){
// complogic
if(e.getSource()==reset){
for(i=0;i<=8;i++){
b[i].setIcon(null);
}//eof for
for(i=0;i<=7;i++)
for(j=0;j<=4;j++)
a[i][j]=a1[i][j]; //again initialsing array
}
else{ //complogic
for(i=0;i<=8;i++){
if(e.getSource()==b[i]){
if(b[i].getIcon()==null){
b[i].setIcon(ic1);
if(b[4].getIcon()==null){
b[4].setIcon(ic2);
this.check(5);
} else{
this.complogic(i);
}
}
}
}//eof for
}
}//eof complogic
for(i=0;i<=7;i++){
Icon icon1=b[(a[i][1]-1)].getIcon();
191.
192.
193.
194.
195.
196.
197.
198.
199.
200.
201.
202.
203.
204.
205.
206.
207.
208.
209.
210.
211.
212.
213.
214.
215.
216.
217.
218.
Icon icon2=b[(a[i][2]-1)].getIcon();
Icon icon3=b[(a[i][3]-1)].getIcon();
if((icon1==icon2)&&(icon2==icon3)&&(icon1!=null)){
if(icon1==ic1){
b[(a[i][1]-1)].setIcon(ic11);
b[(a[i][2]-1)].setIcon(ic11);
b[(a[i][3]-1)].setIcon(ic11);
JOptionPane.showMessageDialog(TTT1.this,"!!!YOU won!!! click reset");
break;
}
else if(icon1==ic2){
b[(a[i][1]-1)].setIcon(ic22);
b[(a[i][2]-1)].setIcon(ic22);
b[(a[i][3]-1)].setIcon(ic22);
JOptionPane.showMessageDialog(TTT1.this,"won! click reset");
break;
}
}
}
}//eof actionperformed
/************************************************************/
public static void main(String []args){
new TTT1();
}//eof main
}//eof class
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
import java.awt.event.*;
import javax.swing.*;
class OnlineTest extends JFrame implements ActionListener
{
JLabel l;
JRadioButton jb[]=new JRadioButton[5];
JButton b1,b2;
ButtonGroup bg;
int count=0,current=0,x=1,y=1,now=0;
int m[]=new int[10];
OnlineTest(String s)
{
super(s);
l=new JLabel();
add(l);
bg=new ButtonGroup();
for(int i=0;i<5;i++)
{
jb[i]=new JRadioButton();
add(jb[i]);
bg.add(jb[i]);
}
b1=new JButton("Next");
b2=new JButton("Bookmark");
b1.addActionListener(this);
b2.addActionListener(this);
add(b1);add(b2);
set();
l.setBounds(30,40,450,20);
jb[0].setBounds(50,80,100,20);
jb[1].setBounds(50,110,100,20);
jb[2].setBounds(50,140,100,20);
jb[3].setBounds(50,170,100,20);
b1.setBounds(100,240,100,30);
b2.setBounds(270,240,100,30);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
setLocation(250,100);
setVisible(true);
setSize(600,350);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
if(check())
count=count+1;
current++;
set();
if(current==9)
{
b1.setEnabled(false);
b2.setText("Result");
}
}
if(e.getActionCommand().equals("Bookmark"))
61.
{
62.
JButton bk=new JButton("Bookmark"+x);
63.
bk.setBounds(480,20+30*x,100,30);
64.
add(bk);
65.
bk.addActionListener(this);
66.
m[x]=current;
67.
x++;
68.
current++;
69.
set();
70.
if(current==9)
71.
b2.setText("Result");
72.
setVisible(false);
73.
setVisible(true);
74.
}
75.
for(int i=0,y=1;i<x;i++,y++)
76.
{
77.
if(e.getActionCommand().equals("Bookmark"+y))
78.
{
79.
if(check())
80.
count=count+1;
81.
now=current;
82.
current=m[y];
83.
set();
84.
((JButton)e.getSource()).setEnabled(false);
85.
current=now;
86.
}
87.
}
88.
89.
if(e.getActionCommand().equals("Result"))
90.
{
91.
if(check())
92.
count=count+1;
93.
current++;
94.
//System.out.println("correct ans="+count);
95.
JOptionPane.showMessageDialog(this,"correct ans="+count);
96.
System.exit(0);
97.
}
98.
}
99.
void set()
100.
{
101.
jb[4].setSelected(true);
102.
if(current==0)
103.
{
104.
l.setText("Que1: Which one among these is not a primitive datatype?");
105.
jb[0].setText("int");jb[1].setText("Float");jb[2].setText("boolean");jb[3].
setText("char");
106.
}
107.
if(current==1)
108.
{
109.
l.setText("Que2: Which class is available to all the class automatically?");
110.
jb[0].setText("Swing");jb[1].setText("Applet");jb[2].setText("Object");jb[
3].setText("ActionEvent");
111.
}
112.
if(current==2)
113.
{
114.
l.setText("Que3: Which package is directly available to our class without i
mporting it?");
115.
jb[0].setText("swing");jb[1].setText("applet");jb[2].setText("net");jb[3].s
etText("lang");
116.
}
117.
if(current==3)
118.
{
119.
l.setText("Que4: String class is defined in which package?");
120.
jb[0].setText("lang");jb[1].setText("Swing");jb[2].setText("Applet");jb[3]
.setText("awt");
121.
}
122.
if(current==4)
123.
{
124.
l.setText("Que5: Which institute is best for java coaching?");
125.
jb[0].setText("Utek");jb[1].setText("Aptech");jb[2].setText("SSS IT");jb[
3].setText("jtek");
126.
}
127.
if(current==5)
128.
{
129.
l.setText("Que6: Which one among these is not a keyword?");
130.
jb[0].setText("class");jb[1].setText("int");jb[2].setText("get");jb[3].setTe
xt("if");
131.
}
132.
if(current==6)
133.
{
134.
l.setText("Que7: Which one among these is not a class? ");
135.
jb[0].setText("Swing");jb[1].setText("Actionperformed");jb[2].setText("A
ctionEvent");
136.
jb[3].setText("Button");
137.
}
138.
if(current==7)
139.
{
140.
l.setText("Que8: which one among these is not a function of Object class?
");
141.
jb[0].setText("toString");jb[1].setText("finalize");jb[2].setText("equals");
142.
jb[3].setText("getDocumentBase");
143.
}
144.
if(current==8)
145.
{
146.
l.setText("Que9: which function is not present in Applet class?");
147.
jb[0].setText("init");jb[1].setText("main");jb[2].setText("start");jb[3].set
Text("destroy");
148.
}
149.
if(current==9)
150.
{
151.
l.setText("Que10: Which one among these is not a valid component?");
152.
jb[0].setText("JButton");jb[1].setText("JList");jb[2].setText("JButtonGrou
p");
153.
jb[3].setText("JTextArea");
154.
}
155.
l.setBounds(30,40,450,20);
156.
for(int i=0,j=0;i<=90;i+=30,j++)
157.
jb[j].setBounds(50,80+i,200,20);
158.
}
159.
boolean check()
160.
{
161.
if(current==0)
162.
return(jb[1].isSelected());
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.
183.
184.
185.
186.
187.
if(current==1)
return(jb[2].isSelected());
if(current==2)
return(jb[3].isSelected());
if(current==3)
return(jb[0].isSelected());
if(current==4)
return(jb[2].isSelected());
if(current==5)
return(jb[2].isSelected());
if(current==6)
return(jb[1].isSelected());
if(current==7)
return(jb[3].isSelected());
if(current==8)
return(jb[1].isSelected());
if(current==9)
return(jb[2].isSelected());
return false;
}
public static void main(String s[])
{
new OnlineTest("Online Test Of Java");
}
}
Output
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:
o
Secured
Drawback of Applet
Do You Know
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends
Container which is the subclass of Component.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle
methods of applet.
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.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}
}
Note: class must be public because its object is created by Java Plugin software
that resides on the browser.
myapplet.html
1.
2.
3.
4.
5.
6.
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome to applet",150,150);
}
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
To execute the applet by appletviewer tool, write in command prompt:
c:\>javac First.java
c:\>appletviewer First.java
Next TopicGraphics in applet
import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet{
public void paint(Graphics g){
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
15.
16.
17.
18.
19.
20.
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
}
}
myapplet.html
1.
2.
3.
4.
5.
6.
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>
Image. Syntax:
public Image getImage(URL u, String image){}
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
import java.awt.*;
import java.applet.*;
public class DisplayImage extends Applet {
Image picture;
public void init() {
picture = getImage(getDocumentBase(),"sonoo.jpg");
}
public void paint(Graphics g) {
g.drawImage(picture, 30,30, this);
}
}
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.
2.
3.
4.
5.
6.
<html>
<body>
<applet code="DisplayImage.class" width="300" height="300">
</applet>
</body>
</html>
Animation in Applet
Applet is mostly used in games and animation. For this purpose image is required to
be moved.
1.
2.
3.
4.
5.
6.
7.
8.
9.
import java.awt.*;
import java.applet.*;
public class AnimationExample extends Applet {
Image picture;
public void init() {
picture =getImage(getDocumentBase(),"bike_1.gif");
}
10.
11.
12.
13.
14.
15.
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.
2.
3.
4.
5.
6.
<html>
<body>
<applet code="DisplayImage.class" width="300" height="300">
</applet>
</body>
</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.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class EventApplet extends Applet implements ActionListener{
Button b;
TextField tf;
public void init(){
tf=new TextField();
tf.setBounds(30,40,150,20);
b=new Button("Click");
b.setBounds(80,150,60,50);
add(b);add(tf);
16.
17.
18.
19.
20.
21.
22.
23.
24.
b.addActionListener(this);
setLayout(null);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
}
In the above example, we have created all the controls in init() method because it is
invoked only once.
myapplet.html
1.
2.
3.
4.
5.
6.
<html>
<body>
<applet code="EventApplet.class" width="300" height="300">
</applet>
</body>
</html>
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
public class EventJApplet extends JApplet implements ActionListener{
JButton b;
JTextField tf;
public void init(){
tf=new JTextField();
tf.setBounds(30,40,150,20);
b=new JButton("Click");
b.setBounds(80,150,70,40);
add(b);add(tf);
b.addActionListener(this);
setLayout(null);
}
public void actionPerformed(ActionEvent e){
22.
23.
24.
tf.setText("Welcome");
}
}
In the above example, we have created all the controls in init() method because it is
invoked only once.
myapplet.html
1.
2.
3.
4.
5.
6.
<html>
<body>
<applet code="EventJApplet.class" width="300" height="300">
</applet>
</body>
</html>
Painting in Applet
We can perform painting operation in applet by the mouseDragged() method of
MouseMotionListener.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class MouseDrag extends Applet implements MouseMotionListener{
public void init(){
addMouseMotionListener(this);
setBackground(Color.red);
}
public void mouseDragged(MouseEvent me){
Graphics g=getGraphics();
g.setColor(Color.white);
g.fillOval(me.getX(),me.getY(),5,5);
}
public void mouseMoved(MouseEvent me){}
}
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.
2.
3.
4.
<html>
<body>
<applet code="MouseDrag.class" width="300" height="300">
</applet>
5.
6.
</body>
</html>
import
import
import
import
java.applet.*;
java.awt.*;
java.util.*;
java.text.*;
}
}
repaint();
t.sleep( 1000 ); // interval given in milliseconds
40.
41.
42.
43.
44.
45.
46.
47.
48.
catch (Exception e) { }
myapplet.html
1.
2.
3.
4.
5.
6.
<html>
<body>
<applet code="DigitalClock.class" width="300" height="300">
</applet>
</body>
</html>
import
import
import
import
java.applet.*;
java.awt.*;
java.util.*;
java.text.*;
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
if ( t == null ) {
t = new Thread( this );
t.setPriority( Thread.MIN_PRIORITY );
threadSuspended = false;
t.start();
}
else {
if ( threadSuspended ) {
threadSuspended = false;
synchronized( this ) {
notify();
}
}
}
}
public void stop() {
threadSuspended = true;
}
public void run() {
try {
while (true) {
Calendar cal = Calendar.getInstance();
hours = cal.get( Calendar.HOUR_OF_DAY );
if ( hours > 12 ) hours -= 12;
minutes = cal.get( Calendar.MINUTE );
seconds = cal.get( Calendar.SECOND );
SimpleDateFormat formatter
= new SimpleDateFormat( "hh:mm:ss", Locale.getDefault() );
Date date = cal.getTime();
timeString = formatter.format( date );
// Now the thread checks to see if it should suspend itself
if ( threadSuspended ) {
synchronized( this ) {
while ( threadSuspended ) {
wait();
}
}
}
repaint();
t.sleep( 1000 ); // interval specified in milliseconds
}
}
catch (Exception e) { }
}
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
myapplet.html
1.
2.
3.
4.
5.
6.
<html>
<body>
<applet code="MyClock.class" width="300" height="300">
</applet>
</body>
</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.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
g.drawString(str,50, 50);
}
}
myapplet.html
1.
2.
3.
4.
5.
6.
7.
<html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</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.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
myapplet.html
1.
<html>
2.
3.
4.
5.
6.
7.
8.
9.
<body>
<applet code="ContextApplet.class" width="150" height="150" name="app1">
</applet>
<applet code="First.class" width="150" height="150" name="app2">
</applet>
</body>
</html>
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.
o
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
1.
2.
3.
long millis=System.currentTimeMillis();
java.util.Date date=new java.util.Date(millis);
System.out.println(date);
Output:
Wed Mar 27 08:22:02 IST 2015
3rd way:
1.
2.
3.
long millis=System.currentTimeMillis();
java.sql.Date date=new java.sql.Date(millis);
System.out.println(date);
Output:
2015-03-27
4th way:
1.
2.
Date date=java.util.Calendar.getInstance().getTime();
System.out.println(date);
Output:
Wed Mar 27 08:22:02 IST 2015
Next Topicjava.util.Date class
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.
1
Constructor
Description
Date()
Date(long
milliseconds)
java.util.Date Methods
No.
Method
Description
1)
2)
3)
Object clone()
4)
5)
6)
7)
instant)
date.
long getTime()
object.
8)
int hashCode()
9)
10
Instant toInstant()
String toString()
)
11
)
java.util.Date Example
Let's see the example to print date in java using java.util.Date class.
1st way:
1.
2.
1.
2.
3.
long millis=System.currentTimeMillis();
java.util.Date date=new java.util.Date(millis);
System.out.println(date);
Output:
Wed Mar 27 08:22:02 IST 2015
Next Topicjava.sql.Date class
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
milliseconds)
java.sql.Date Methods
No.
1
Method
Description
Instant toInstant()
LocalDate toLocalDate()
)
2
)
3
)
4
object.
String toString()
date)
LocalDate.
3.
4.
5.
6.
7.
long millis=System.currentTimeMillis();
java.sql.Date date=new java.sql.Date(millis);
System.out.println(date);
}
Output:
2015-03-30
import java.sql.Date;
public class StringToSQLDateExample {
public static void main(String[] args) {
String str="2015-03-31";
Date date=Date.valueOf(str);//converting string into sql date
System.out.println(date);
}
}
Output:
2015-03-31
Next TopicJava Date Format
java.text.DateFormat Fields
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
java.text.DateFormat Methods
No.
Public Method
Description
1)
2)
ParseException
3)
4)
5)
getTimeInstance()
getTimeInstance(int style)
locale)
6)
7)
getDateInstance()
getDateInstance(int style)
8)
locale)
9)
getDateTimeInstance()
10
getDateTimeInstance(int dateStyle,int
timeStyle)
11
12
)
13
Calendar getCalendar()
)
14
)
15
)
16
TimeZone getTimeZone()
import java.text.DateFormat;
import java.util.Date;
public class DateFormatExample {
public static void main(String[] args) {
Date currentDate = new Date();
System.out.println("Current Date: "+currentDate);
String dateToStr = DateFormat.getInstance().format(currentDate);
System.out.println("Date Format using getInstance(): "+dateToStr);
}
}
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.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
import java.text.DateFormat;
import java.util.Date;
public class DateFormatExample2 {
public static void main(String[] args) {
Date currentDate = new Date();
System.out.println("Current Date: "+currentDate);
String dateToStr = DateFormat.getInstance().format(currentDate);
System.out.println("Date Format using getInstance(): "+dateToStr);
dateToStr = DateFormat.getDateInstance().format(currentDate);
System.out.println("Date Format using getDateInstance(): "+dateToStr);
dateToStr = DateFormat.getTimeInstance().format(currentDate);
System.out.println("Date Format using getTimeInstance(): "+dateToStr);
);
19.
20.
21.
22.
23.
24.
dateToStr = DateFormat.getTimeInstance(DateFormat.SHORT).format(curre
ntDate);
28.
29.
dateToStr = DateFormat.getTimeInstance(DateFormat.MEDIUM).format(curr
25.
26.
27.
dateToStr = DateFormat.getDateTimeInstance().format(currentDate);
System.out.println("Date Format using getDateTimeInstance(): "+dateToStr
dateToStr = DateFormat.getTimeInstance(DateFormat.LONG).format(curren
tDate);
dateToStr = DateFormat.getDateTimeInstance(DateFormat.LONG,DateForma
t.SHORT).format(currentDate);
30.
System.out.println("Date Format using getDateTimeInstance(DateFormat.LO
NG,DateFormat.SHORT): "+dateToStr);
31.
32.
}
33.
}
Output:
import java.text.DateFormat;
import java.util.Date;
public class DateFormatExample3 {
public static void main(String[] args)throws Exception {
5.
6.
7.
8.
Output:
Date is: Tue Mar 31 00:00:00 IST 2015
Next TopicJava SimpleDateFormat
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.
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatExample {
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String strDate= formatter.format(date);
System.out.println(strDate);
}
}
Test it Now
Output:
13/04/2015
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class SimpleDateFormatExample2 {
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
String strDate = formatter.format(date);
System.out.println("Date Format with MM/dd/yyyy : "+strDate);
formatter = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
strDate = formatter.format(date);
System.out.println("Date Format with dd-M-yyyy hh:mm:ss : "+strDate);
formatter = new SimpleDateFormat("dd MMMM yyyy");
strDate = formatter.format(date);
System.out.println("Date Format with dd MMMM yyyy : "+strDate);
formatter = new SimpleDateFormat("dd MMMM yyyy zzzz");
strDate = formatter.format(date);
System.out.println("Date Format with dd MMMM yyyy zzzz : "+strDate);
formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
strDate = formatter.format(date);
System.out.println("Date Format with E, dd MMM yyyy HH:mm:ss z : "+strDat
e);
30.
}
Test it Now
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
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatExample3 {
public static void main(String[] args) {
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
try {
Date date = formatter.parse("31/03/2015");
System.out.println("Date is: "+date);
} catch (ParseException e) {e.printStackTrace();}
}
}
Test it Now
Output:
Date is: Tue Mar 31 00:00:00 IST 2015
Next TopicJava Date
By printing the instance of java.util.Date class, you can print current date and time in
java. There are two ways to do so.
1st way:
1.
2.
1.
2.
3.
long millis=System.currentTimeMillis();
java.util.Date date=new java.util.Date(millis);
System.out.println(date);
Output:
Thu Mar 26 08:22:02 IST 2015
long millis=System.currentTimeMillis();
java.sql.Date date=new java.sql.Date(millis);
System.out.println(date);
Output:
2015-03-26
Date date=java.util.Calendar.getInstance().getTime();
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.
Next TopicJava Date
Collections in Java
1. Java Collection Framework
2. Hierarchy of Collection Framework
3. Collection interface
4. Iterator interface
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).
is optional.
2. Algorithm
Do You Know ?
How can we sort the elements of an object. What is the difference between
Comparable and Comparator interfaces?
No Method
.
Description
element)
collection.
element)
9
10
returns an iterator.
11
12
13
14
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
Next TopicArrayList In Collection Framework
Java ArrayList class uses a dynamic array for storing the elements. It extends
AbstractList class and implements List interface.
Java ArrayList allows random access because array works at the index basis.
1.
import java.util.*;
class TestCollection1{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();//creating arraylist
al.add("Ravi");//adding object in arraylist
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator itr=al.iterator();//getting Iterator from arraylist to traverse elements
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Test it Now
Ravi
Vijay
Ravi
Ajay
import java.util.*;
class TestCollection2{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
for(String obj:al)
System.out.println(obj);
}
}
Test it Now
Ravi
Vijay
Ravi
Ajay
class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
}
1.
2.
3.
4.
import java.util.*;
public class TestCollection3{
public static void main(String args[]){
//Creating user-defined class objects
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
import java.util.*;
class TestCollection4{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
ArrayList<String> al2=new ArrayList<String>();
al2.add("Sonoo");
al2.add("Hanumat");
al.addAll(al2);
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Test it Now
Ravi
Vijay
Ajay
Sonoo
Hanumat
import java.util.*;
class TestCollection5{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
ArrayList<String> al2=new ArrayList<String>();
al2.add("Ravi");
al2.add("Hanumat");
al.removeAll(al2);
System.out.println("iterating the elements after removing the elements of al2..."
);
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Test it Now
iterating the elements after removing the elements of al2...
Vijay
Ajay
import java.util.*;
class TestCollection6{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
ArrayList<String> al2=new ArrayList<String>();
al2.add("Ravi");
al2.add("Hanumat");
al.retainAll(al2);
13.
14.
15.
16.
17.
18.
19.
20.
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Test it Now
iterating the elements after retaining the elements of al2...
Ravi
Next TopicLinkedList In Collection Framework
Java LinkedList class uses doubly linked list to store the elements. It extends the
AbstractList class and implements List and Deque interfaces.
import java.util.*;
public class TestCollection7{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
15.
16.
}
}
Test it Now
Output:Ravi
Vijay
Ravi
Ajay
Next TopicArrayList vs LinkedList
ArrayList
LinkedList
required in memory.
accessing data.
manipulating data.
import java.util.*;
class TestArrayLinked{
public static void main(String args[]){
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
ListIterator Interface is used to traverse the element in backward and forward direction.
import java.util.*;
public class TestCollection8{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Amit");
al.add("Vijay");
al.add("Kumar");
al.add(1,"Sachin");
System.out.println("element at 2nd position: "+al.get(2));
ListIterator<String> itr=al.listIterator();
System.out.println("traversing elements in forward direction...");
while(itr.hasNext()){
System.out.println(itr.next());
}
System.out.println("traversing elements in backward direction...");
while(itr.hasPrevious()){
System.out.println(itr.previous());
}
}
}
Test it Now
Output:element at 2nd position: Vijay
traversing elements in forward direction...
Amit
Sachin
Vijay
Kumar
traversing elements in backward direction...
Kumar
Vijay
Sachin
Amit
Next TopicHashSet Class In Collection Framework
uses hashtable to store the elements.It extends AbstractSet class and implements
Set interface.
import java.util.*;
class TestCollection9{
public static void main(String args[]){
HashSet<String> al=new HashSet<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Test it Now
Output:Ajay
Vijay
Ravi
Next TopicLinkedHashSet Class In Collection Framework
contains unique elements only like HashSet. It extends HashSet class and
implements Set interface.
import java.util.*;
class TestCollection10{
public static void main(String args[]){
LinkedHashSet<String> al=new LinkedHashSet<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Test it Now
Output:>Ravi
Vijay
Ajay
<<prevnext>>
contains unique elements only like HashSet. The TreeSet class implements
NavigableSet interface that extends the SortedSet interface.
import java.util.*;
class TestCollection11{
public static void main(String args[]){
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
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.
2.
import java.util.*;
class TestCollection12{
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
<<prevnext>>
Entry
Entry is the subinterface of Map.So we will access it by Map.Entry name.It provides
methods to get key and value.
A HashMap contains values based on the key. It implements the Map interface
and extends AbstractMap class.
It maintains no order.
import java.util.*;
class TestCollection13{
public static void main(String args[]){
HashMap<Integer,String> hm=new HashMap<Integer,String>();
hm.put(100,"Amit");
hm.put(101,"Vijay");
hm.put(102,"Rahul");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Test it Now
Output:102 Rahul
100 Amit
101 Vijay
import java.util.*;
class TestCollection14{
public static void main(String args[]){
LinkedHashMap<Integer,String> hm=new LinkedHashMap<Integer,String>();
hm.put(100,"Amit");
hm.put(101,"Vijay");
hm.put(102,"Rahul");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Test it Now
Output:100 Amit
101 Vijay
103 Rahul
Next TopicTreeMap Class In Collection Framework
It cannot have null key but can have multiple null values.
import java.util.*;
class TestCollection15{
public static void main(String args[]){
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
It is synchronized.
Example of Hashtable:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
import java.util.*;
class TestCollection16{
public static void main(String args[]){
Hashtable<Integer,String> hm=new Hashtable<Integer,String>();
hm.put(100,"Amit");
hm.put(102,"Ravi");
hm.put(101,"Vijay");
hm.put(103,"Rahul");
11.
12.
13.
14.
15.
16.
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Test it Now
Output:103 Rahul
102 Ravi
101 Vijay
100 Amit
Next TopicDifference between HashMap and Hashtable
HashMap
Hashtable
threads.
synchronization code.
2) HashMap allows one null key and
or value.
4) HashMap is fast.
Hashtable is slow.
can't be unsynchronized.
Map m =
Collections.synchronizedMap(hashMap)
;
8) HashMap