2.0 Object Oriented Programming in Java
2.0 Object Oriented Programming in Java
By
TOPIC-I
OOP Concepts:- Data abstraction, encapsulation, inheritance, Benefits of Inheritance,
Polymorphism, classes and objects, Procedural and object oriented programming paradigms.
Java Programming- History of Java, comments, Data types, Variables, Constants, Scope and
Lifetime of variables, Operators, Operator Hierarchy, Expressions, Type conversion and casting,
Enumerated types, Control flow- block scope, conditional statements, loops, break and continue
statements, simple java stand alone programs, arrays, console input and output, formatting output,
constructors, methods, parameter passing, static fields and methods, access control, this reference,
overloading methods and constructors, recursion, garbage collection, building strings, exploring
string class.
TOPIC – II
Inheritance – Inheritance hierarchies super and sub classes, Member access rules, super
keyword, preventing inheritance: final classes and methods, the Object class and its methods.
Polymorphism – dynamic binding, method overriding, abstract classes and methods.
Interfaces- Interfaces Vs Abstract classes, defining an interface, implement interfaces, accessing
implementations through interface references, extending interface.
Inner classes- Uses of inner classes, local inner classes, anonymous inner classes, static inner
classes, examples.
Packages- Defining, creating and accessing a package, Understanding CLASSPATH, importing
packages.
TOPIC-III
Exception handling- Dealing with errors, benefits of exception handling, the classification of
exceptions- exception hierarchy, checked exceptions and unchecked exceptions, usage of try,
catch, throw, throws and finally, rethrowing exceptions, exception specification, built in
exceptions, creating own exception sub classes.
Multithreading – Differences between multiple processes and multiple threads, thread states,
creating threads, interrupting threads, thread priorities, synchronizing threads, inter-thread
communication, producer consumer pattern,Exploring java.net and java.text.
TOPIC-IV
Collection Framework in Java – Introduction to java collections, Overview of java collection
framework, Generics, Commonly used collection classes- Array List, Vector, Hash table, Stack,
Enumeration, Iterator, String Tokenizer, Random, Scanner, Calendar and Properties.
Files- Streams- Byte streams, Character streams, Text input/output, Binary input/output, random
access file operations, File management using File class.
Connecting to Database – JDBC Type 1 to 4 drivers, Connecting to a database, querying a
database and processing the results, updating data with JDBC.
TOPIC-V
GUI Programming with Java- The AWT class hierarchy, Introduction to Swing, Swing Vs
AWT, Hierarchy for Swing components, Containers – Jframe, JApplet, JDialog, JPanel,
Overview of some Swing components – Jbutton, JLabel, JTextField, JTextArea, simple Swing
applications, Layout management – Layout manager types – border, grid and flow
Event Handling- Events, Event sources, Event classes, Event Listeners, Relationship between
Event sources and Listeners, Delegation event model, Examples: Handling a button click,
Handling Mouse events, Adapter classes.
Applets – Inheritance hierarchy for applets, differences between applets and applications,
Life cycle of an applet, Passing parameters to applets, applet security issues.
TEXT BOOK:
1. Java Fundamentals – A Comprehensive Introduction, Herbert Schildt and Dale Skrien,
TMH.
REFERENCE BOOKS:
1. Java for Programmers, P.J.Deitel and H.M.Deitel, PEA (or) Java: How to
Program , P.J.Deitel and H.M.Deitel, PHI
2. Object Oriented Programming through Java, P. Radha Krishna, Universities Press.
3. Thinking in Java, Bruce Eckel, PE
4. Programming in Java, S. Malhotra and S. Choudhary, Oxford Universities Press.
Course Outcomes:
An understanding of the principles and practice of object oriented analysis and design
in the construction of robust, maintainable programs which satisfy their requirements;
A competence to design, write, compile, test and execute straightforward programs using
a high level language;
An appreciation of the principles of object oriented programming;
An awareness of the need for a professional approach to design and the importance
of good documentation to the finished programs.
Be able to implement, compile, test and run Java programs comprising more than
one class, to address a particular software problem.
Demonstrate the ability to use simple data structures like arrays in a Java program.
Be able to make use of members of classes found in the Java API (such as the Math class).
INDEX
2 Benefits of Inheritance 2
I
OOP Concepts
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:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o 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
Page 7
logical.
Class
Inheritance
Polymorphism
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.
Page 8
A java class is the example of encapsulation. Java bean is the fully
encapsulated class because all the data members are private here.
Benefits of Inheritance
the same.
Extensibility - extending the base class logic as per business logic of the
derived class.
Data hiding - base class can decide to keep some data private so that it
cannot be altered by the derived class
Procedural and object oriented programming paradigms
Page 9
Page 10
Java Programming- History of Java
The history of java starts from Green Team. Java team members
(also known as Green Team), initiated a revolutionary task to develop a
language for digital devices such as set-top boxes, televisions etc.
For the green team members, it was an advance concept at that time. But,
it was suited for internet programming. Later, Java technology as
incorporated by Netscape.
3) Firstly, it was called "Green talk" 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.
Page 11
Java Version History
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. 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)
Features of Java
There is given many features of java. They are also known as java
buzzwords. The Java Features given below are simple and easy to
understand.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Dynamic
Page 12
9. Interpreted
10.High Performance
11.Multithreaded
12.Distributed
Java Comments
The java comments are statements that are not executed by the compiler
and interpreter. The comments can be used to provide information or
explanation about the variable, method, class or any statement. It can also
be used to hide program code for specific time.
Syntax:
Example:
Page 13
public class CommentExample1 {
public static void main(String[] args) {
int i=10; //Here, i is a variable
System.out.println(i);
}
}
Output:10
Syntax:
Example:
public class CommentExample2 {
public static void main(String[] args) {
/* Let's declare and
print variable in java. */
int i=10;
System.out.println(i);
}
}
Output:10
Page 14
Java Documentation Comment
Syntax:
/** This is
Documentation comment
*/
Example:
/** The Calculator class provides methods to get addition and subtraction of
given 2 numbers.*/
public class Calculator {
/** The add() method returns addition of given numbers.*/
public static int add (int a, int b){
return a+b;
}
/** The sub() method returns subtraction of given numbers.*/
public static int sub (int a, int b){
return a-b;
}
}
Page 15
javac Calculator.java
javadoc Calculator.java
Now, there will be HTML files created for your Calculator class in the
current directory. Open the HTML files and see the explanation of
Calculator class provided through documentation comment.
Data Types
Data types represent the different values to be stored in the variable. In java,
there are two types of data types:
Page 16
Data Type Default Value Default size
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
Output:20
Page 17
Variables and Data Types in Java
There are two types of data types in java: primitive and non-primitive.
Types of Variable
o local variable
o instance variable
o static variable
1) Local Variable
2) Instance Variable
A variable which is declared inside the class but outside the method, is
called instance variable . It is not declared as static.
3) Static variable
Page 18
Example to understand the types of variables in java
class A{
int data=50; //instance variable
static int m=100; //static variable
void method(){
int n=90; //local variable
}
} //end of class
Constants in Java
A constant is a variable which cannot have its value changed after declaration. It uses
the 'final' keyword.
Syntax
modifier final data
Type variable
Name = value; //global constant
Page 19
Scope and Life Time of Variables
The scope of a variable defines the section of the code in which the
variable is visible. As a general rule, variables that are defined within a
block are not accessible outside that block. The lifetime of a variable
refers to how long the variable exists before it is destroyed. Destroying
variables refers to deallocating the memory that was allotted to the
variables when declaring it. We have written a few classes till now. You
might have observed that not all variables are the same. The ones
declared in the body of a method were different from those that were
declared in the class itself. There are three types of variables: instance
variables, formal parameters or local variables and local variables.
Instance variables
Instance variables are those that are defined within a class itself and not
in any method or constructor of the class. They are known as instance
variables because every instance of the class (object) contains a copy of
these variables. The scope of instance variables is determined by the
access specifier that is applied to these variables. We have already seen
about it earlier. The lifetime of these variables is the same as the lifetime
of the object to which it belongs. Object once created do not exist for
ever. They are destroyed by the garbage collector of Java when there are
no more reference to that object. We shall see about Java's automatic
garbage collector later on.
Argument variables
These are the variables that are defined in the header oaf constructor or
a method. The scope of these variables is the method or constructor in
which they are defined. The lifetime is limited to the time for which the
method keeps executing. Once the method finishes execution, these
variables are destroyed.
Page 20
Local variables
Operators in java
o Unary Operator,
o Arithmetic Operator,
o shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
Page 21
Operators Hierarchy
Page 22
Expressions
Expressions are essential building blocks of any Java program, usually
created to produce a new value, although sometimes an expression
simply assigns a value to a variable. Expressions are built using values,
variables, operators and method calls.
Types of Expressions
For Example, in java the numeric data types are compatible with each other
but no automatic conversion is supported from numeric type to char or
boolean. Also, char and boolean are not compatible with each other.
Page 23
Narrowing or Explicit Conversion
If we want to assign a value of larger data type to a smaller data type we
perform explicit type casting or narrowing.
Page 24
Java Enum
Output:
WINTER
SPRING
SUMMER
FALL
Page 25
Control Flow Statements
if (condition) {
// execute this code
}
Page 26
Creating a Stand-Alone Java Application
1. Write a main method that runs your program. You can write this
method anywhere. In this example, I'll write my main method in a
class called Main that has no other methods.
For example:
public class Main{
public static void main(String[] args) {
Game.play();
}
}
Make sure your code is compiled, and that you have tested it thoroughly.
If you're using Windows, you will need to set your path to include
Java, if you haven't done so already. This is a delicate operation.
Open Explorer, and look inside C:\ProgramFiles\Java, and you
should see some version of the JDK. Open this folder, and then open
the bin folder. Select the complete path from the top of the Explorer
window, and press Ctrl-C to copy it.
Next, find the "My Computer" icon (on your Start menu or desktop), right-
click it, and select properties. Click on the Advanced tab, and then click on
the Environment variables button.
Look at the variables listed for all users, and click on the Path variable.
Do not delete the contents of this variable! Instead, edit the contents
by moving the cursor to the right end, entering a semicolon (;), and
pressing Ctrl-V to paste the path you copied earlier. Then go ahead
and save your changes. (If you have any Cmd windows open, you will
need to close them.)
In Windows, type dir at the command prompt to list the contents of the current
directory. On a Mac or Linux machine, type ls to do this.
cd Desktop
cd ..
Every time you change to a new directory, list the contents of that
directory to see where to go next. Continue listing and changing
directories until you reach the directory that contains
your .class files.
8. If you compiled your program using Java 1.6, but plan to run it
on a Mac, you'll need to recompile your code from the command
line, by typing:
9. Now we'll create a single JAR file containing all of the files needed to run
your program.
Page 28
Arrays
This tutorial introduces how to declare array variables, create arrays, and
process arrays using indexed variables.
Example:
Page 29
The following code snippets are examples of this syntax:
Creating
Arrays:
You can create an array by using the new operator with the following syntax:
The array elements are accessed through the index. Array indices are
0-based; that is, they start from 0 to arrayRefVar.length-1.
Page 30
Example:
Following statement declares an array variable, myList, creates an
array of 10 elements of double type and assigns its reference to
myList:
Page 31
Processing Arrays:
When processing array elements, we often use either for loop or for each
loop because all of the elements in an array are of the same type and the
size of the array is known.
Example:
Here is a complete example of showing how to create, initialize and process
arrays:
Page 32
public class TestArray
{
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4,
3.5};
// Print all the array elements
for (int i = 0; i < myList.length; i++)
{
System.out.println(myList[i] + " ");
}
// Summing all
elements double total =
0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest
element double max =
myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max =
myList[i];
Page 33
This would produce the following result:
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
}}}
The Java Console class is be used to get input from console. It provides
methods to read texts and passwords.
If you read password using Console class, it will not be displayed to the user.
1. String text=System.console().readLine();
Page 34
2. System.out.println("Text is: "+text);
import java.io.Console;
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);
}
}
Page 35
Output
Constructors
class Bike1{
Bike1(){
System.out.println("Bike is created");
}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
class Student4{
int id;
String name;
Student4 (int i, String n){
id = i;
name = n;
}
void display(){
System.out.println(id+" "+name);
}
Page 37
public static void main(String args[]){
Student4 s1 = new Student4(111, "Karan");
Student4 s2 = new Student4(222, "Aryan");
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan
Page 39
s2.display();
}}
Output:
111 Karan 0
222 Aryan 25
There are many ways to copy the values of one object into another in java.
They are:
o By constructor
oBy assigning the values of one object into another
oBy clone() method of Object class
In this example, we are going to copy the values of one object into
another using java constructor.
class Student6{
int id;
String
name;
Student6(int
i,String n){ id = i;
name = n;
}
Student6(Studen
t6 s){ id = s.id;
name =s.name;
Page 40
}
void display(){System.out.println(id+" "+name);}
Output:
111 Karan
111 Karan
Page 41
Java -Methods
A Java method is a collection of statements that are grouped together to
perform an operation. When you call the System.out.println() method,
for example, the system actually executes several statements in order to
display a message on the console.
Now you will learn how to create your own methods with or without
return values, invoke a method with or without parameters, and
apply method abstraction in the program design.
Creating Method
Considering the following example to explain the syntax of a method −
Syntax
Here,
a, b − formal parameters
Page 43
Parameter List − The list of parameters, it is the type, order, and
number of parameters of a method. These are optional, method
may contain zero parameters.
method body − The method body defines what the method does with the
statements.
Call by Value and Call by Reference in Java
There is only call by value in java, not call by reference. If we call a
method passing a value, it is known as call by value. The changes
being done in the called method, is not affected in the calling method.
Example of call by value 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);
}
Output:before change 50
after change 50
Page 44
In Java, parameters are always passed by value. For example,
following program prints i = 10, j = 20.
//
Test.jav
a class
Test {
// swap() doesn't swap i and j
public static void swap(Integer i,
Integer j) { Integer temp = new
Integer(i);
i = j;
j = temp;
}
public static void
main(String[] args) {
Integer i = new Integer(10);
Integer j = new
Integer(20); swap(i,
j);
System.out.println("i = " + i + ", j = " + j);
Page 45
}
}
Page 47
String name;
static String
college ="ITS";
Student8(int
r,String n){ rollno
= r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void
main(String args[]){
Student8 s1 = new
Student8(111,"Karan");
Student8 s2 = new
Student8(222,"Aryan");
s1.display();
s2.display();
}}
Output:111 Karan ITS
222 Aryan ITS
If you apply static keyword with any method, it is known as static method.
class
Student9
{ int
rollno;
String
name;
static String college = "ITS";
static void
change(){
college =
"BBDIT";
}
Student9(int r,
String n){ rollno =
r;
name = n;
Page 49
}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void
main(String args[]){
Student9.change();
Student9 s1 = new Student9
(111,"Karan"); Student9 s2 =
new Student9 (222,"Aryan");
Student9 s3 = new Student9
(333,"Sonoo"); s1.display();
s2.display();
s3.display();
}}
Example of static
block class A2{
static{System.out.println("static block is
invoked");} public static void
main(String args[]){
System.out.println("Hello main");
Page 50
Output: static block is invoked
Hello main
}}
Access Control
There are two types of modifiers in java: access modifiers and non-access
modifiers.
Page 51
1. private
2. default
3. protected
4. public
//save by
B.java
package
mypack;
import
pack.*;
Page 53
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.
In this example, we have created the two packages pack and mypack.
The A class of pack package is public, so can be accessed from outside
the package. But msg method of this package is declared as protected, so
it can be accessed from outside the class only through inheritance.
//save by
A.java
package
pack;
public
class A{
protected void msg(){System.out.println("Hello");} }
//save by
B.java
Page 54
package
mypack;
import
pack.*; class
B extends A{
public static void
main(String args[]){ B obj =
new B();
obj.msg();
}}
Output:Hello
Page 55
Example of public access modifier
//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
Y N N N
Page 56
Private
Y Y N N
Default
Y Y Y N
Protected
Y Y Y Y
Public
Page 57
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.
class
Student{ i
nt rollno;
String
name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=ro
llno;
this.name=na
me;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String
args[]){ Student s1=new
Student(111,"ankit",5000f);
Student s2=new
Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output:
111 ankit 5000
112 sumit 6000
Page 58
Difference between constructor and method in java
Constructor must not have return type. Method must have return
type.
Constructor name must be same as the class Method name may or may
name. not be
Page 59
same as class name.
There are many differences between constructors and methods. They are
given belo
Output:
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void
main(String[] args){
System.out.println(Adder.add(
11,11));
System.out.println(Adder.add(
JAVA PROGRAMMING Page 32
11,11,11));
}}
Output:
22
33
Output:
}}
Java String
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new
String(ch); ssame
as:
1. String s="javatpoint";
CharSequence Interface
String Literal
1. String s="welcome";
Each time you create a string literal, the JVM checks the string constant
pool first. If the string already exists in the pool, a reference to the pooled
instance is returned. If string doesn't exist in the pool, a new string
instance is created and placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//will not create new instance
By new keyword
1. String s=new String("Welcome");//creates two objects and one reference
JAVA PROGRAMMING Page 38
variable
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).
Java String
Example
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java
string by new keyword System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
java
The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.
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);
}}
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
barking...
eating...
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
Output:
weeping...
barking...
eating...
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...
A subclass includes all of the members of its super class but it cannot access those members of
the super class that have been declared as private. Attempt to access a private variable would
cause compilation error as it causes access violation. The variables declared as private, is only
accessible by other members of its own class. Subclass have no access to it.
The super keyword in java is a reference variable which is used to refer immediate parent class
object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog
class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
JAVA PROGRAMMING Page 44
d.printColor();
}}
Output:
black
white
The final keyword in java is used to restrict the user. The java final keyword can be used in many
context. Final can be:
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.
The Object class is the parent class of all the classes in java by default. 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 know what object will be returned from this method
The Object class provides some common behaviors to all the objects such as object can be
compared, object can be cloned, object can be notified etc.
1. 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 Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}}
Output:
SBI Rate of Interest: 8
A class that is declared with abstract keyword is known as abstract class in java. It can have
abstract and non-abstract methods (method with body). It needs to be extended and its method
implemented. It cannot be instantiated.
abstract method
1. abstract void printStatus();//no body and abstract
The interface in java is a mechanism to achieve abstraction. There can be only abstract methods
in the java interface not method body. It is used to achieve abstraction and multiple inheritance in
Java.
There are mainly three reasons to use interface. They are given below.
o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.
interface Printable{
Output:Hello
Welcome
Abstract class Interface
1) Abstract class can have Interface can have only abstract methods. Since
abstract and non-abstract Java 8, it can have default and static
methods. methods also.
2) Abstract class doesn't support Interface supports multiple inheritance.
multiple inheritance.
3) Abstract class can have final, non- Interface has only static and final variables.
final, static and non-static variables.
4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.
5) The abstract keyword is used to The interface keyword is used to declare
declare abstract class. interface.
6) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
We use inner classes to logically group classes and interfaces in one place so that it can be more
readable and maintainable.
There are basically three advantages of inner classes in java. They are as follows:
1) Nested classes represent a special type of relationship that is it can access all the
members (data members and methods) of outer class including private.
2) Nested classes are used to develop more readable and maintainable code because
it logically group classes and interfaces in one place only.
Inner class is a part of nested class. Non-static nested classes are known as inner classes.
There are two types of nested classes non-static and static nested classes.The non-static nested
classes are also known as inner classes.
Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined
package. There are many built-in packages such as java, lang, awt, javax, swing, net, io,
1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}}
If you are not using any IDE, you need to follow the syntax given below:
//save by
A.java 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
Exception Handling
The exception handling in java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.
What is exception
In java, exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.
The core advantage of exception handling is to maintain the normal flow of the application.
Exception normally disrupts the normal flow of the application that is why we use exception
handling.
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
1) Checked Exception: The classes that extend Throwable class except RuntimeException and Error
are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked
at compile-time.
2) Unchecked Exception: The classes that extend RuntimeException are known as unchecked
exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time rather they are checked at runtime.
Java try block is used to enclose the code that might throw an exception. It must be used within
the method.
1. try{
2. //code that may throw exception
3. }catch(Exception_class_Name ref){}
1. try{
2. //code that may throw exception
3. }finally{}
Java catch block is used to handle the Exception. It must be used after the try block only.
As displayed in the above example, rest of the code is not executed (in such case, rest of the
code... statement is not printed).
There can be 100 lines of code after exception. So all the code after exception will not be
executed.
Now, as displayed in the above example, rest of the code is executed i.e. rest of the code...
statement is printed.
If you have to perform different tasks at the occurrence of different Exceptions, use java multi
catch block.
Output:task1 completed
rest of the code...
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{
JAVA PROGRAMMING Page 55
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..");
}
1. }
Java finally block
Java finally block is a block that is used to execute important code such as closing connection,
stream etc.
Case 1
Let's see the java finally example where exception doesn't occur.
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...");
}
}
Output:5
finally block is always executed
rest of the code...
We can throw either checked or uncheked exception in java by throw keyword. The throw
keyword is mainly used to throw custom exception. We will see custom exceptions later.
1. throw exception;
In this example, we have created the validate method that takes integer value as a parameter. If
the age is less than 18, we are throwing the ArithmeticException otherwise print a message
welcome to vote.
Output:
The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to provide the
exception handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers fault that he is not
performing check up before the code being used.
Let's see the example of java throws clause which describes that checked exceptions can be
propagated by throws keyword.
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
If you are creating your own Exception that is known as custom exception or user-defined
exception. Java custom exceptions are used to customize the exception according to user need.
By the help of custom exception, you can have your own exception and message.
But we use multithreading than multiprocessing because threads share a common memory area.
They don't allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process.
1) It doesn't block the user because threads are independent and you can perform
multiple operations at same time.
3) Threads are independent so it doesn't affect other threads if exception occur in a single thread.
A thread can be in one of the five states. According to sun, there is only 4 states in thread life
cycle in java new, runnable, non-runnable and terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
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.
o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)
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:
o A new thread starts(with new callstack).
o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.
When a thread invokes a synchronized method, it automatically acquires the lock for that object
and releases it when the thread completes its task.
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(){
ThreadGroup(String name)
ThreadGroup(ThreadGroup parent, String
name)
Now all 3 threads belong to one group. Here, tg1 is the thread group name, MyRunnable is the
class that implements Runnable interface and "one", "two" and "three" are the thread names.
1. Thread.currentThread().getThreadGroup().interrupt();
The java.net package of the J2SE APIs contains a collection of classes and interfaces that
provide the low-level communication details, allowing you to write programs that focus on
solving the problem at hand.
The java.net package provides support for the two common network protocols −
TCP − TCP stands for Transmission Control Protocol, which allows for reliable
communication between two applications. TCP is typically used over the Internet
Protocol, which is referred to as TCP/IP.
UDP − UDP stands for User Datagram Protocol, a connection-less protocol that allows
for packets of data to be transmitted between applications.
Socket Programming − This is the most widely used concept in Networking and it has
been explained in very detail.
java.text
The java.text package is necessary for every java developer to master because it has a lot of
classes that is helpful in formatting such as dates, numbers, and messages.
java.text Classes
package [table]
Class|Description
SimpleDateFormat|is a concrete class that helps in formatting and parsing of dates.
[/table]
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).
Collection framework represents a unified architecture for storing and manipulating group of
objects. It has:
Constructor Description
Java ArrayList
Example import java.util.*;
class TestCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next()); } }}
Ravi
Vijay
Ravi
Ajay
ArrayList and Vector both implements List interface and maintains insertion order.
But there are many differences between ArrayList and Vector classes that are given below.
ArrayList Vector
2)ArrayList increments 50% of Vector increments 100% means doubles the array
current array size if number of size if total number of element exceeds than its
element exceeds from its capacity. capacity.
5) ArrayLis tuses Iterator interface Vector uses Enumeration interface to traverse the
to traverse the elements. elements. But it can use Iterator also.
Let's see a simple example of java Vector class that uses Enumeration interface.
1. import java.util.*;
2. class TestVector1{
3. public static void main(String args[]){
4. Vector<String> v=new Vector<String>();//creating vector
5. v.add("umesh");//method of Collection
6. v.addElement("irfan");//method of Vector
7. v.addElement("kumar");
8. //traversing elements using Enumeration
Output:
umesh
irfan
kumar
Java Hashtable class implements a hashtable, which maps keys to values. It inherits Dictionary
class and implements the Map interface.
o A Hashtable is an array of list. Each list is known as a bucket. The position of bucket is
identified by calling the hashcode() method. A Hashtable contains values based on the
key.
o It contains only unique elements.
o It may have not have any null key or value.
o It is synchronized.
Constructor Description
Hashtable(int size) It is used to accept an integer parameter and creates a hash table
that has an initial size specified by integer value size.
Hashtable(int size, float It is used to create a hash table that has an initial size specified by
fillRatio) size and a fill ratio specified by fillRatio.
Output:
103 Rahul
102 Ravi
101 Vijay
100 Amit
Stack
Stack only defines the default constructor, which creates an empty stack. Stack includes all the
methods defined by Vector, and adds several of its own.
import java.util.*;
st.push(new Integer(a));
System.out.println("push(" + a + ")");
System.out.println(a);
showpush(st, 42);
showpush(st, 66);
showpush(st, 99);
showpop(st);
showpop(st);
showpop(st);
try {
showpop(st);
} catch (EmptyStackException e) {
System.out.println("empty stack");
Output
stack: [ ] push(42) stack: [42] push(66) stack: [42, 66] push(99)
stack: [42, 66, 99]
pop -> 99
stack: [42, 66]
pop -> 66
stack: [42]
pop -> 42 stack: [ ]
pop -> empty stack
Enumeration
The Enumeration Interface
The Enumeration interface defines the methods by which you can enumerate (obtain one at a
time) the elements in a collection of objects.
The methods declared by Enumeration are summarized in the following table −
1
boolean hasMoreElements( )
When implemented, it must return true while there are still more elements to extract, and
false when all the elements have been enumerated.
2
Object nextElement( )
This returns the next object in the enumeration as a generic Object reference.
Example
import java.util.Vector;
import
java.util.Enumeration;
Enumeration days;
dayNames.add("Sunday");
dayNames.add("Monday");
dayNames.add("Tuesday");
dayNames.add("Wednesday");
dayNames.add("Thursday");
dayNames.add("Friday");
dayNames.add("Saturday");
days = dayNames.elements();
while (days.hasMoreElements()) {
System.out.println(days.nextElement());
Output
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Iterator
StringTokenizer in Java
The java.util.StringTokenizer class allows you to break a string into tokens. It is simple way
to break string.
It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc.
String nextToken() returns the next token from the StringTokenizer object.
String nextToken(String delim) returns the next token based on the delimeter.
Let's see the simple example of StringTokenizer class that tokenizes a string "my name is khan"
on the basis of whitespace.
import java.util.StringTokenizer;
public class Simple{
public static void main(String args[]){
java.util.Random
For using this class to generate random numbers, we have to first create an instance of this
class and then invoke methods such as nextInt(), nextDouble(), nextLong() etc using that
instance.
We can generate random numbers of types integers, float, double, long, booleans using this
class.
We can pass arguments to the methods for placing an upper bound on the range of the
numbers to be generated. For example, nextInt(6) will generate numbers in the range 0 to 5
both inclusive.
// A Java program to demonstrate random number generation
// using java.util.Random;
import java.util.Random;
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
public String next() it returns the next token from the scanner.
public String nextLine() it moves the scanner position to the next line and returns the value
as a string.
Let's see the simple example of the Java Scanner class which reads the int, string and double
value as an input:
import java.util.Scanner;
class ScannerTest{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter your rollno");
int rollno=sc.nextInt();
System.out.println("Enter your name");
String name=sc.next();
System.out.println("Enter your fee");
double fee=sc.nextDouble();
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
sc.close();
} } Output:
Enter your
rollno 111
Enter your name
Ratan
Enter
450000
Rollno:111 name:Ratan fee:450000
Java Calendar class is an abstract class that provides methods for converting date between a
specific instant in time and a set of calendar fields such as MONTH, YEAR, HOUR, etc. It
inherits Object class and implements the Comparable interface.
import java.util.Calendar;
public class CalendarExample1 {
public static void main(String[] args) {
Calendar calendar =
Calendar.getInstance();
System.out.println("The current date is : " + calendar.getTime());
calendar.add(Calendar.DATE, -15);
System.out.println("15 days ago: " + calendar.getTime());
calendar.add(Calendar.MONTH, 4);
System.out.println("4 months later: " + calendar.getTime());
calendar.add(Calendar.YEAR, 2);
System.out.println("2 years later: " + calendar.getTime());
}}
Output:
Stream
A stream can be defined as a sequence of data. There are two kinds of Streams −
Java provides strong but flexible support for I/O related to files and networks but this tutorial
covers very basic functionality related to streams and I/O. We will see the most commonly used
examples one by one −
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
classes related to byte streams but the most frequently used classes
are, FileInputStream and FileOutputStream. Following is an example which makes use of
these two classes to copy an input file into an output file −
Example
import java.io.*;
FileInputStream in = null;
try {
in = new FileInputStream("input.txt");
int c;
}finally {
if (in != null) {
in.close();
if (out != null)
{ out.close();
}} }}
As a next step, compile the above program and execute it, which will result in creating output.txt
file with the same content as we have in input.txt. So let's put the above code in CopyFile.java
file and do the following −
$javac CopyFile.java
$java CopyFile
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, whereas
Java Character streams are used to perform input and output for 16-bit unicode. Though there
are many classes related to character streams but the most frequently used classes
are, FileReader and FileWriter. Though internally FileReader uses FileInputStream and
FileWriter uses FileOutputStream but here the major difference is that FileReader reads two
bytes at a time and FileWriter writes two bytes at a time.
We can re-write the above example, which makes the use of these two classes to copy an
input file (having unicode characters) into an output file −
Example
import java.io.*;
FileWriter out =
null; try {
in = new FileReader("input.txt");
int c;
out.write(c);}
}finally {
if (in != null) {
in.close();}
if (out != null)
{ out.close();
}} }}
As a next step, compile the above program and execute it, which will result in creating output.txt
file with the same content as we have in input.txt. So let's put the above code in CopyFile.java
file and do the following −
$javac CopyFile.java
$java CopyFile
Standard Streams
All the programming languages provide support for standard I/O where the user's program can
take input from a keyboard and then produce an output on the computer screen. Java provides the
following three standard streams −
Standard Input − This is used to feed the data to user's program and usually a keyboard
is used as standard input stream and represented asSystem.in.
Standard Error − This is used to output the error data produced by the user's program
and usually a computer screen is used for standard error stream and represented
as System.err.
Following is a simple program, which creates InputStreamReader to read standard input stream
until the user types a "
Example
import java.io.*;
try {
char c;
do {
c = (char) cin.read();
System.out.print(c);
} while(c != 'q');
}finally {
if (cin != null) {
cin.close();
} } }}
This program continues to read and output the same character until we press 'q' −
$javac ReadConsole.java
$java ReadConsole
q
Reading and Writing Files
As described earlier, a stream can be defined as a sequence of data. The InputStream is used to
read data from a source and the OutputStream is used for writing data to a destination.
FileInputStream
This stream is used for reading data from the files. Objects can be created using the
keyword new and there are several types of constructors available.
Following constructor takes a file name as a string to create an input stream object to read the
file −
ByteArrayInputStream
DataInputStream
FileOutputStream
FileOutputStream is used to create a file and write data into it. The stream would create a file, if
it doesn't already exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream object.
Following constructor takes a file name as a string to create an input stream object to write the
file −
Following constructor takes a file object to create an output stream object to write the file. First,
we create a file object using File() method as follows −
Example
import java.io.*;
try {
JAVA PROGRAMMING Page 87
byte bWrite [] = {11,21,3,40,5};
} }}
Java.io.RandomAccessFile Class
The Java.io.RandomAccessFile class file behaves like a large array of bytes stored in the file
system.Instances of this class support both reading and writing to a random access file.
Class declaration
Following is the declaration for Java.io.RandomAccessFile class −
public class RandomAccessFile extends Object
implements DataOutput, DataInput, Closeable
Class constructors
S.N. Constructor & Description
1
RandomAccessFile(File file, String mode)
This creates a random access file stream to read from, and optionally to write to, the file
specified by the File argument.
This creates a random access file stream to read from, and optionally to write to, a file with
the specified name.
Methodsinherited
This class inherits methods from the following classes −
Java.io.Object
defines an abstract file name for the geeks file in directory /usr/local/bin. This is an absolute
abstract file name.
Program to check if a file or directory physically exist or not.
// In this program, we accepts a file or directory name from
// command line arguments. Then the program will check if
// that file or directory physically exist or not and
// it displays the property of that file or directory.
*import java.io.File;
Output:
File
name :file.txt
Path: file.txt
Absolute path:C:\Users\akki\IdeaProjects\codewriting\src\
file.txt Parent:null
Exists :true
Is
writeable:true
Is readabletrue
Is a
Connceting to DB
Whatis JDBCDriver?
JDBC drivers implement the defined interfaces in the JDBC API, for interacting with your
database server.
For example, using JDBC drivers enable you to open database connections and to interact with it
by sending SQL or database commands then receiving results with Java.
When Java first came out, this was a useful driver because most databases only supported ODBC
access but now this type of driver is recommended only for experimental use or when no other
alternative is available.
This kind of driver is extremely flexible, since it requires no code installed on the client and a
single driver can actually provide access to multiple databases.
Your application server might use a Type 1, 2, or 4 driver to communicate with the database,
understanding the nuances will prove helpful.
This kind of driver is extremely flexible, you don't need to install special software on the client
or server. Further, these drivers can be downloaded dynamically.
MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their
network protocols, database vendors usually supply type 4 drivers.
If your Java application is accessing multiple types of databases at the same time, type 3 is the
preferred driver.
Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not available yet for
your database.
For connecting java application with the mysql database, you need to follow 5 steps to perform
database connectivity.
In this example we are using MySql as the database. So we need to know following informations
for the mysql database:
1. Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
2. Connection URL: The connection URL for the mysql database
is jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database,
localhost is the server name on which mysql is running, we may also use IP address, 3306
is the port number and sonoo is the database name. We may use any database, in such
case, you need to replace the sonoo with your database name.
3. Username: The default username for the mysql database is root.
4. Password: Password is given by the user at the time of installing the mysql database.
In this example, we are going to use root as the password.
Let's first create a table in the mysql database, but before creating table, we need to create
database first.
database
In this example, sonoo is the database name, root is the username and password.
import java.sql.*;
class MysqlCon{
public static void main(String args[]){
try{ Class.forName("com.mysql.jdbc.Dri
ver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sonoo","root","root");
JAVA PROGRAMMING Page 89
//here sonoo is database name, root is username and password
The above example will fetch all the records of emp table.
To connect java application with the mysql database mysqlconnector.jar file is required to be
loaded.
2) set classpath:
There are two ways to set the
classpath: 1.temporary
2.permanent
Go to environment variable then click on new tab. In variable name write classpath and in
variable value paste the path to the mysqlconnector.jar file by appending mysqlconnector.jar;.; as
C:\folder\mysql-connector-java-5.0.8-bin.jar;
JDBC-Result Sets
The SQL statements that read data from a database query, return the data in a result set. The
SELECT statement is the standard way to select rows from a database and view them in a result
set. The java.sql.ResultSet interface represents the result set of a database query.
The methods of the ResultSet interface can be broken down into three categories −
Get methods: Used to view the data in the columns of the current row being pointed
by the cursor.
Update methods: Used to update the data in the columns of the current row. The updates
can then be updated in the underlying database as well.
The cursor is movable based on the properties of the ResultSet. These properties are designated
when the corresponding Statement that generates the ResultSet is created.
JDBC provides the following connection methods to create statements with desired ResultSet −
The first argument indicates the type of a ResultSet object and the second argument is one of two
ResultSet constants for specifying whether a result set is read-only or updatable.
Type of ResultSet
The possible RSType are given below. If you do not specify any ResultSet type, you will
automatically get one that is TYPE_FORWARD_ONLY.
Type Description
Concurrencyof ResultSet
The possible RSConcurrency are given below. If you do not specify any Concurrency type, you
will automatically get one that is CONCUR_READ_ONLY.
Concurrency Description
There is a get method for each of the possible data types, and each get method has two versions
For example, if the column you are interested in viewing contains an int, you need to use one of
the getInt() methods of ResultSet −
Returns the int in the current row in the column named columnName.
There are also methods for getting SQL data types java.sql.Date, java.sql.Time,
java.sql.TimeStamp, java.sql.Clob, and java.sql.Blob. Check the documentation for more
information about using these SQL data types.
As with the get methods, there are two update methods for each data type −
There are update methods for the eight primitive data types, as well as String, Object, URL, and
the SQL data types in the java.sql package.
Updating a row in the result set changes the columns of the current row in the ResultSet object,
but not in the underlying database. To update your changes to the row in the database, you need
to invoke one of the following methods.
Updates the current row by updating the corresponding row in the database.
Java AWT components are platform-dependent i.e. components are displayed according to the
view of operating system. AWT is heavyweight i.e. its components are using the resources of OS.
The java.awt package provides classes for AWT api such as TextField, Label,
TextArea, RadioButton, CheckBox, Choice, List etc.
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.
Method Description
public void setSize(int width,int height) sets the size (width and height) of the component.
public void setLayout(LayoutManager defines the layout manager for the component.
m)
To create simple awt example, you need a frame. There are two ways to create a frame in AWT.
Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing
Button component on the Frame.
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();
}}
The setBounds(int xaxis, int yaxis, int width, int height) method is used in the above example that
sets the position of the awt button.
Java Swing
Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window-
based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely
written in java.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
3) AWT doesn't support pluggable look Swing supports pluggable look and
and feel. feel.
Method Description
public void setLayout(LayoutManager sets the layout manager for the component.
m)
We can write the code of swing inside the main(), constructor or any other method.
Let's see a simple swing example where we are creating one button and adding it on the JFrame
object inside the main() method.
File: FirstSwingExample.java
Java JFrame
The javax.swing.JFrame class is a type of container which inherits the java.awt.Frame class.
JFrame works like the main window where components like labels, buttons, textfields are added
to create a GUI.
Unlike Frame, JFrame has the option to hide or close the window with the help of
setDefaultCloseOperation(int) method.
JFrame Example
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Jpanel;
public class JFrameExample {
public static void main(String s[]) {
JFrame frame = new JFrame("JFrame Example");
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
JLabel label = new JLabel("JFrame By Example");
JButton button = new JButton();
button.setText("Button");
panel.add(label);
JAVA PROGRAMMING Page 101
panel.add(button);
frame.add(panel);
frame.setSize(200, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}}
JApplet
As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of swing.
The JApplet class extends the Applet class.
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){
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. <html>
2. <body>
3. <applet code="EventJApplet.class" width="300" height="300">
JAVA PROGRAMMING Page 102
</applet>
</body>
</html>
JDialog
The JDialog control represents a top level window with a border and a title used to take some
form of input from the user. It inherits the Dialog class.
Constructor Description
JDialog(Frame owner, String title, It is used to create a dialog with the specified
boolean modal) title, owner Frame and modality.
}); Output:
JPanel
The JPanel is a simplest container class. It provides space in which an application can attach any
other component. It inherits the JComponents class.
The JButton class is used to create a labeled button that has platform independent implementation. The
application result in some action when the button is pushed. It inherits AbstractButton class.
import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true); } }
Java JLabel
The object of JLabel class is a component for placing text in a container. It is used to display a
single line of read only text. The text can be changed by an application but a user cannot edit it
directly. It inherits JComponent class.
Constructor Description
JLabel(String s, Icon i, int Creates a JLabel instance with the specified text,
horizontalAlignment) image, and horizontal alignment.
Methods Description
void setText(String text) It defines the single line of text this component will
display.
Icon getIcon() It returns the graphic image that the label displays.
import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
l1.setBounds(50,50, 100,30);
l2=new JLabel("Second Label.");
l2.setBounds(50,100, 100,30);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
The object of a JTextField class is a text component that allows the editing of a single line text. It
inherits JTextComponent class.
import javax.swing.*;
class TextFieldExample
{
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to Javatpoint.");
t1.setBounds(50,100, 200,30);
t2=new JTextField("AWT Tutorial");
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.s etLayout(null);
f.setVisible(true);
} }
Java JTextArea
The object of a JTextArea class is a multi line region that displays text. It allows the editing of
multiple line text. It inherits JTextComponent class
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public Example() {
setTitle("Simple example");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
BorderLayout
The BorderLayout provides five constants for each region:
Types of Event
Foreground Events - Those events which require the direct interaction of user.They are
generated as consequences of a person interacting with the graphical components in
Graphical User Interface. For example, clicking on a button, moving the mouse, entering
a character through keyboard,selecting an item from list, scrolling the page etc.
Background Events - Those events that require the interaction of end user are known as
Event Handling
Event Handling is the mechanism that controls the event and decides what should happen if an
event occurs. This mechanism have the code which is known as event handler that is executed
when an event occurs. Java Uses the Delegation Event Model to handle the events. This model
defines the standard mechanism to generate and handle the events.Let's have a brief introduction
to this model.
The Delegation Event Model has the following key participants namely:
Source - The source is an object on which event occurs. Source is responsible for
providing information of the occurred event to it's handler. Java provide as with classes
for source object.
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
For registering the component with the Listener, many classes provide the registration methods.
For example:
o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
EventHandling Codes:
We can put the event handling code into one of the following places:
1. Same class
2. Other class
3. Annonymous class
}}
Java adapter classes provide the default implementation of listener interfaces. If you inherit the
adapter class, you will not be forced to provide the implementation of all the methods of listener
interfaces. So it saves code.
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
1. import java.awt.*;
import java.awt.event.*;
public class AdapterExample{
Frame f; AdapterExample()
{
f=new Frame("Window Adapter");
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
f.dispose(); } });
f.s etSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new AdapterExample();
}}
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
Drawback of Applet
o Plugin is required at client browser to execute applet.
The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life
cycle methods for an applet.
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.
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.
To execute the applet by html file, create an applet and compile it. After that create an html
file and place the applet code in html file. Now click the html file.
1. //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);
}
}
To execute the applet by appletviewer tool, create an applet that contains applet tag in comment
and compile it. After that run it by: appletviewer First.java. Now Html file is not required but it is
for testing purpose only.
1. //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>
*/
c:\>javac First.java
c:\>appletviewer First.java