0% found this document useful (0 votes)
2 views

Java

The document outlines the history of Java, initiated by the Green Team at Sun Microsystems in 1991, with James Gosling as the primary developer. It explains the Java Virtual Machine (JVM), its components, and the features of Java such as being object-oriented, platform-independent, and secure. Additionally, it covers Java's basic syntax, data types, control structures, and the principles of object-oriented programming.

Uploaded by

anagandularaju12
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Java

The document outlines the history of Java, initiated by the Green Team at Sun Microsystems in 1991, with James Gosling as the primary developer. It explains the Java Virtual Machine (JVM), its components, and the features of Java such as being object-oriented, platform-independent, and secure. Additionally, it covers Java's basic syntax, data types, control structures, and the principles of object-oriented programming.

Uploaded by

anagandularaju12
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 125

HISTORY OF JAVA

The history of java starts from Green Team. Green team at sun microsystem.

The team members are James Gosling, Mike Sheridan and Patrick Naughton.

Team initiated the Java language project in June 1991.

Team initiated a task to develop a language for digital devices such as set-top boxes,
televisions etc.

Father of java (Developer) : James Gosling

Year : 1995 (The version is 1.o)

Company : Sun Microsystems (Present Subsidiary of Oracle)

Team : Green Team (Not only James Gosling total 10 members

Team called green team)

Green Talk : First name of java

OAK : Rename to OAK (The name is inspired by an OAK tree that

Stood outside Gosling’s office. Oak tree is a symbol of

Strength and national tree of many countries like U.S.A,

France, Germany and trade mark in the World)

JAVA (1995) : All the team members decided to change the name to java

The suggested words were “dynamic”, “silk”, “DNA” etc.

According to James Gosling “Java and Silk” were two top

Choices.

JAVA: Java is an island of Indonesia where first coffee was produced (called java coffee)
Java coffee consumed in large quantities by the languages creators.

NOTE: JAVA has no abbrivation.


JVM (JAVA VIRTUAL MACHINE)
JVM stands for java virtual machine.

 JVM is an abstractive machine that executes byte code instructions.


 JVM is a specification that provides an environment in which a java byte code can be
executed.

 There are various JVM’S available for many hardware and software platforms.
 JVM is platform dependent.
 JVM performs the following operations.
1. Loads the class files.
2. Verifies the code.
3. Execute the code.
4. Provides runtime environment.
JVM has the following components.

1. Class loader substem :-


It is a part of the JVM. It takes responsibility to load the class files in to the memory.

2. Runtime memory areas:-


The JVM allocate five different types of memory areas for different components of the

program.

They are:-

1. Method/ class area.


2. Stack memory.
3. Heap memory.
4. PC Register.
5. Native method area.
Method / class area:-

It can store the class structures and a method data.

Stack memory:-

It can store the variables and results of the program.

Heap area:-

It can store’s the object created in the program.

PC register:-

PC can store the executable instructions to execute next.

Native method area:-

It is responsible for storing the native method information.

Execution Engine:-

Execution engine is a part of the JVM. It has two components.

1. Java interpreter.
2. JIT compiler.
It executes byte code instructions and generates machine code instructions.

The java interpreter converts the byte code instructions into machine code line by line

sequentially.

JIT COMPILER:-
JIT (JUST IN TIME) compiler improves the performance of the java program execution by

converting byte code files into machine code at a time.

Java features are :

Object Oriented: In Java, everything is an Object. Java can be easily extended since it is based on the Object

model.

Platform Independent: Unlike many other programming languages including C and C++, when Java is

compiled, it is not compiled into platform specific machine, rather into platform independent byte code.

This byte code is distributed over the web and interpreted by the Virtual Machine (JVM) on whichever

platform it is being run on.

Simple: Java is designed to be easy to learn. If you understand the basic concept of OOP Java, it would be

easy to master.

Secure: With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication

techniques are based on public-key encryption.

Architecture-neutral: Java compiler generates an architecture-neutral object file format, which makes the

compiled code executable on many processors, with the presence of Java runtime system.

Portable: Being architecture-neutral and having no implementation dependent aspects of the specification

makes Java portable. Compiler in Java is written in ANSI C with a clean portability.

Robust: Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time

error checking and runtime checking.

Multithreaded: With Java's multithreaded feature it is possible to write programs that can perform many

tasks simultaneously. This design feature allows the developers to construct interactive applications that

can run smoothly.

Interpreted: Java byte code is translated on the fly to native machine instructions and is not stored

anywhere. The development process is more rapid and analytical since the linking is an incremental and

light-weight process.

High Performance: With the use of Just-In-Time compilers, Java enables high performance.

Distributed: Java is designed for the distributed environment of the internet.

Dynamic: Java programs can carry extensive amount of run-time information that can be used to verify and

resolve accesses to objects on run-time.
Java – Basic Syntax

When we consider a Java program, it can be defined as a collection of objects that communicate via invoking

each other's methods. Let us now briefly look into what do class, object, methods, and instance variables mean.

Object - Objects have states and behaviours. Example: A dog has states - color, name, breed as well as

behaviour such as wagging their tail, barking, eating. An object is an instance of a class.

Class - A class can be defined as a template/blueprint that describes the behaviour/state that the object of

its type supports.

Methods - A method is basically a behaviour. A class can contain many methods. It is in methods where the

logics are written, data is manipulated and all the actions are executed.

Instance Variables - Each object has its unique set of instance variables. An object's state is created by the

values assigned to these instance variables.

Let's look at how to save the file, compile, and run the program. Please follow the subsequent steps:

Open notepad and add the code as above.



Save the file as: MyFirstJavaProgram.java.

Open a command prompt window and go to the directory where you saved the class. Assume it's C:\.

Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there are no errors in your

code, the command prompt will take you to the next line (Assumption : The path variable is set).

Now, type ' java MyFirstJavaProgram ' to run your program.



You will be able to see ' Hello World ' printed on the window.

C:\> javac MyFirstJavaProgram.java

C:\> java MyFirstJavaProgram

output is: Hello World

DATA TYPES

Data type defined type of values to be stored in a variable

Data type is a type of data that can be stored in a variable.


In java programming to declare a variable we must specific the data type.

In java data types can be classified in to two types.

1. Primitive type.
2. Non primitive type.
Primitive type:-

Primitive data types are the types inherited from the old languages such as c and c++.

Primitive data types are divided into two types.

1. Numeric.
2. Non numeric.
Numeric:-

The numeric data types are used to defined and declared the number type values in the

program.

These are two types.

1. Integer type.
2. Floating point.
Integer Type:-

Data Type Size Minimum Maximum

Byte 8(bits) 1Byte -128 127

Short 16(bits) 2 Bytes -32768 32767

Int 32(bits) 4 Bytes 2,147,438,648 2,147,483,647

Long 64(bits) 8 Bytes 9223372036854775808 9223372036854775807


Floating Point:-

Data Type Size

Float 4(Bytes)

Double 8(Bytes)

These data types are used to represent the floating point value(decimal) in the program.

Non numeric:-

These data types are used to represent the non numeric values such as character.

Data Type Size min Max

Char 2 Bytes 0 65536

Boolean 1 Byte True False

Type casting
Type casting is the process of converting one data type to another data type.

Java supports two types of type castings.

1. Implicit type casting.


2. Explicit type casting.

Implicit type casting:-

Implicit type casting is also known as automatic type conversion.

The automatic type conversion can be done by the java compiler


automatically.
Automatic type conversion is possible when the two types are compatible
and the target type is larger than the source type.

Ex:- byte b=10;

Int a;

a=b;

This process of assigning smaller type to larger type is known as widening.

Byte char short int long float double

Explicit type casting:-


Explicit type casting is the process of assigning the larger data type to a
smaller data type.

It is also known as narrowing.

Double float long int short char byte

DECISION MAKING AND BRANCHING MECHANISM (OR) CONDITIONAL STATEMENTS:-

CONTROL STRUCTURES:-

 A java program is a set of statements that are executed sequentially in a specific order.
 In some situations the programmer needs to change the order of execution of the statements.
 To control the execution of statements we can use control structures.
 The java supports the following types of control structures.
1. Conditional control structures (Branching).
2. Iterative control structures (Looping).
3. Jumping control structures.
CONDITIONAL CONTROL STRUCTURES:-

The conditional control structures are used to control the flow of execution depending on the given

condition.

The conditional control structures can be classified in to as follows.

1. Simple if statement.
2. If else statement.
3. Nested if statement.
4. Else if ladder.
Simple if statement:-

The general form a simple if statement is:

IF (CONDITION)

EXECUTABLE STATEMENTS;

STATEMENT-X;

Explanation:-

If the given condition is true the statements in the if block will be executed. Other-wise the action will

be skipped to out of the block statement-x executed.

IF ELSE STATEMENT:-

The general form or syntax of if else statement is:

IF (CONDITION)
{

STATEMENTS;

ELSE

STATEMENTS;

STATEMENT-X;

Explanation:-

If the condition is true the statements in the if block get executed. Otherwise the statements in the else

block get executed and statement-x also executed.

NESTED IF CONDITION:-

The general form of nested if statement or syntax is:

IF (CONDITION-1)

IF (CONDITION-2)

STATEMENTS;

}
statement-x;

Explanation:-

If statement is used with in another if statement used then it is said to be nested if condition.

The inner if block is executed only when outer block if condition is true. Other-wise the action will be

skipped.

The statements in inner if condition block will be executed only when both inner and outer block if

conditions are true.

The statement-x is executed whether the condition may be true or false.

Object and Classes


Since Java is an object oriented language, complete java language is build on classes
and object. Java is also known as a strong Object oriented programming language
(OOPS).
OOPS is a programming approach which provides solution to problems with the help of
algorithms based on real world. It uses real world approach to solve a problem.

Main Features of OOPS

 Inheritence
 Polymorphism
 Encapsulation
 Abstraction

As an object oriented language Java supports all the features given above. We will
discuss all these features in detail later.

Class
In Java everything is encapsulated under classes.
Class is the core of Java language.
A class defines new data type.
Once defined this new type can be used to create object of that type.
Object is an instance of class.
A class is declared using class keyword.
A class contain both data and code that operate on that data.
The data or variables defined within a class are called instance variables and the code
that operates on this data is known as methods.
Thus, the instance variables and methods are known as class members.
Class is also known as a user defined data type.

Rules for Java Class

 A class can have only public or default (no modifier) access specifier.

 It must have the class keyword, and class must be followed by a legal identifier.
 The class's variables and methods are declared within a set of curly braces { }.
 Class is a model for creating objects.
 An object is physical representation of data.
 An object is an instance of a class.

Defining a class:-

Class class_name
{
[field declaration;]//member variables
[methods declaration;] // member function
}
Example:-

Class Student
{
//body of the class
}

Field declaration:-

Data fields are also known as member variables.


These variables are called as instance variables.
The variables can be declared as follows.

A simple class example


Suppose, Student is a class and student's name, roll number, age will be its property.
Lets see this in Java syntax.

class Student
{
String name; //field declaration
int rollno; // field declaration
int age; // field declaration
}

Method declaration:-
Method is the behaviour of the object methods are declared inside the body of the class
but immediately after the declaration of instance variables.

Syntax:-
Data-type method name(parameter list)
{
Method body;
}
Method declaration has four basic parts:-
1. The name of the method.
2. The type of value the method returns.
3. A list of parameters.
4. The body of the methods.

Example:-
class Student
{
String name;
int rollno;
int age;
void dis(String n, int r, int ag)
{
name=n;
rollno=r;
age=ag;
}
}

Creating object:-

When a reference is made to a particular student with its property then it becomes
an object, physical existence of Student class.

Syntax:-
Class-name object-name=new class-name();

Example:-

Student std=new Student();

After the above statement std is object of Student class.

Here the new keyword creates an actual physical copy of the object and assign it to
the std variable.
It will have physical existence and get memory in heap area. The new operator
dynamically allocates memory for an object.

Accessing class members:-

We can not access the instance variables & methods directly.

The members can be accessed by using object-name with dot operator.

Syntax:-

Object-name . variable-name = value;


Object-name . method-name (parameter list);

Q. How a class is initialized in java?


A Class is initialized in Java when an instance of class is created using
either new operator or using reflection using class.forName(). A class is also said to be
initialized when a static method of Classis invoked or a static field of Class is assigned.

Methods in Java
Method describe behavior of an object. A method is a collection of statements that are
group together to perform an operation.
Syntax :
return-type methodName(parameter-list)
{
//body of method
}

Example of a Method
public String getName(String st)
{
String name="StudyTonight";
name=name+st;
return name;
}
Modifier : Modifier are access type of method. We will discuss it in detail later.
Return Type : A method may return value. Data type of value return by a method is
declare in method heading.
Method name : Actual name of the method.
Parameter : Value passed to a method.
Method body : collection of statement that defines what method does.

Parameter Vs. Argument


While talking about method, it is important to know the difference between two
terms parameter and argument.
Parameter is variable defined by a method that receives value when the method is
called. Parameter are always local to the method they dont have scope outside the
method. While argument is a value that is passed to a method when it is called.
call-by-value and call-by-reference
There are two ways to pass an argument to a method

1. call-by-value : In this approach copy of an argument value is pass to a method.


Changes made to the argument value inside the method will have no effect on the
arguments.
2. call-by-reference : In this reference of an argument is pass to a method. Any
changes made inside the method will affect the agrument value.

NOTE :There is only call by value in java, not call by reference.

Example of call-by-value
public class Test
{
public void callByValue(int x)
{
x=100;
}
public static void main(String[] args)
{
int x=50;
Test t = new Test();
t.callByValue(x); //function call
System.out.println(x);
}

50

Method overloading
If two or more method in a class have same name but different parameters, it is known
as method overloading. Overloading always occur in the same class(unlike method
overriding).
Method overloading is one of the ways through which java supports polymorphism.
Method overloading can be done by changing number of arguments or by changing the
data type of arguments. If two or more method have same name and same parameter
list but differs in return type are not said to be overloaded method
Note: Overloaded method can have different access modifiers.

Different ways of Method overloading


There are two different ways of method overloading
Method overloading by changing data type of Arguments
Example :
class Calculate
{
void sum (int a, int b)
{
System.out.println("sum is"+(a+b)) ;
}
void sum (float a, float b)
{
System.out.println("sum is"+(a+b));
}
public static void main (String[] args)
{
Calculate cal = new Calculate();
cal.sum (8,5); //sum(int a, int b) is method is called.
cal.sum (4.6f, 3.8f); //sum(float a, float b) is called.
}
}

Sum is 13

Sum is 8.4

You can see that sum() method is overloaded two times. The first takes two integer
arguments, the second takes two float arguments.

Method overloading by changing no. of argument.


Example :
class Area
{
void find(int l, int b)
{
System.out.println("Area is"+(l*b)) ;
}
void find(int l, int b,int h)
{
System.out.println("Area is"+(l*b*h));
}
public static void main (String[] args)
{
Area ar = new Area();
ar.find(8,5); //find(int l, int b) is method is called.
ar.find(4,6,2); //find(int l, int b,int h) is called.
}
}

Area is 40

Area is 48

In this example the find() method is overloaded twice. The first takes two arguments to
calculate area, and the second takes three arguments to calculate area.

Constructors in Java
A constructor is a special method that is used to initialize an object.Every class has a
constructor,if we don't explicitly declare a constructor for any java class the compiler
builds a default constructor for that class.
A constructor does not have any return type.
A constructor has same name as the class in which it resides.
Constructor in Java can not be abstract, static, final or synchronized. These modifiers
are not allowed for constructor.
class Car
{
String name ;
String model;
Car( ) //Constructor
{
name ="";
model="";
}
}

There are two types of Constructor

 Default Constructor
 Parameterized constructor

Each time a new object is created at least one constructor will be invoked.
Car c = new Car() //Default constructor invoked
Car c = new Car(name); //Parameterized constructor invoked

Parameterized constructor:-
If any constructor is declared with one or more parameters
then it is called as parameterized constructor.
Constructor Overloading
Like methods, a constructor can also be overloaded. Overloaded constructors are
differentiated on the basis of their type of parameters or number of parameters.
Constructor overloading is not much different than method overloading. In case of
method overloading you have multiple methods with same name but different signature,
whereas in Constructor overloading you have multiple constructor with different
signature but only difference is that Constructor doesn't have return type in Java.
Instance variable:-
If variable is declared with in the class but outside of the method then it is
said to be instance variable.

The instance variable should not be declared as static.

Instance variable are created when the objects will be instantiated.

The instance variable are associated with the object.

this’ reference in Java


‘This’ is a reference variable that refers to the current
object.

This
This is a keyword in Java. This keyword in java can be used
inside the Method or constructor of Class. It (this) works as
a reference to the current Object, whose Method or
constructor is being invoked. This keyword can be used to
refer to any member of the current object from within an
instance Method or a constructor.

Concept of Array in Java


An array is a collection of similar data types. Array is a container object that hold values
of homogenous type. It is also known as static data structure because size of an array
must be specified at the time of its declaration.
An array can be either primitive or reference type. It gets memory in heap area. Index of
array starts from zero to size-1.

Features of Array
 It is always indexed. Index begins from 0.
 It is a collection of similar data types.
 It occupies a contiguous memory location.

Array Declaration
Syntax :
datatype[] identifier;
or
datatype identifier[];
Both are valid syntax for array declaration. But the former is more readable.
Example :
int[ ] arr;
char[ ] arr;
short[ ] arr;
long[ ] arr;
int[ ][ ] arr; // two dimensional array.

Initialization of Array
new operator is used to initialize an array.

Example :
int[] arr = new int[10]; //this creates an empty array named arr of
integer type whose size is 10.
or
int[] arr = {10,20,30,40,50}; //this creates an array named arr whose
elements are given.

Accessing array element


As mention ealier array index starts from 0. To access nth element of an array. Syntax
arrayname[n-1];
Example of constructor overloading
class Cricketer
{
String name;
int age;
Cricketer () //default constructor.
{
}
Cricketer(String n, int a) //constructor overloaded
{
name = n;
age = a;
}
Cricketer (Cricketer ckt) //constructor similar to copy constructor of
c++
{
name = ckt.name;
age = ckt.age;
}
void disp()
{
System.out.println(name+” “+age);
}
}

class Test
{
public static void main (String[] args)
{
Cricketer c1 = new Cricketer();
Cricketer c2 = new Cricketer("sachin", 32);
Cricketer c3 = new Cricketer(c2);
c2.disp();
}
}

this is sachin of india

this is sachin of india


this is virat of india

Q What's the difference between constructors and normal


methods?
Constructors must have the same name as the class and can not return a value. They
are only called once for a single object while regular methods could be called many
times and it can return a value or can be void.

Q. What is constructor chaining in Java?


Constructor chaining is a phenomena of calling one constructor from another constructor
of same class. Since constructor can only be called from another constructor in Java,
constructor chaining is used for this purpose.
class Test
{
Test()
{
this(10);
}
Test(int x)
{
System.out.println("x="+x);
}
public static void main(String arg[])
{
Test object = new Test();
}
}

x=10

Inheritance (IS-A)
Inheritance is one of the key features of Object Oriented Programming. Inheritance
provided mechanism that allowed a class to inherit property of another class. When
a Class extends another class it inherits all non-private members including fields and
methods. Inheritance in Java can be best understood in terms of Parent and Child
relationship, also known as Super class(Parent) and Sub class(child) in Java language.
Inheritance defines is-a relationship between a Super class and its Sub
class. extends and implements keywords are used to describe inheritance in Java.
Let us see how extends keyword is used to achieve Inheritance.
class Vehicle.
{
......
}
class Car extends Vehicle
{
....... //extends the property of vehicle class.
}
Now based on above example. In OOPs term we can say that,

 Vehicle is super class of Car.


 Car is sub class of Vehicle.
 Car IS-A Vehicle.

Purpose of Inheritance

1. It promotes the code reusabilty i.e the same methods and variables which are
defined in a parent/super/base class can be used in the child/sub/derived class.
2. It promotes polymorphism by allowing method overriding.

Disadvantages of Inheritance
Main disadvantage of using inheritance is that the two classes (parent and child class)
gets tightly coupled.
This means that if we change code of parent class, it will affect to all the child classes
which is inheriting/deriving the parent class, and hence, it cannot be independent of
each other.

Simple example of Inheritance


class Parent
{
public void p1()
{
System.out.println("Parent method");
}
}
public class Child extends Parent {
public void c1()
{
System.out.println("Child method");
}
public static void main(String[] args)
{
Child cobj = new Child();
cobj.c1(); //method of Child class
cobj.p1(); //method of Parent class
}
}

Child method

Parent method

Another example of Inheritance


class Vehicle
{
String vehicleType;
}
public class Car extends Vehicle {
String modelType;
public void showDetail()
{
vehicleType = "Car"; //accessing Vehicle class member
modelType = "sports";
System.out.println(modelType+" "+vehicleType);
}
public static void main(String[] args)
{
Car car =new Car();
car.showDetail();
}
}

sports Car

Types of Inheritance

1. Single Inheritance
2. Multilevel Inheritance
3. Heirarchical Inheritance

NOTE :Multiple inheritance is not supported in java

Why multiple inheritance is not supported in Java

 To remove ambiguity.
 To provide more maintainable and clear design.
super keyword
In Java, super keyword is used to refer to immediate parent class of a child class. In
other words super keyword is used by a subclass whenever it need to refer to its
immediate super class.
Example of Child class refering Parent
class property using super keyword
class Parent
{
String name;

}
public class Child extends Parent {
String name;
public void details()
{
super.name = "Parent"; //refers to parent class member
name = "Child";
System.out.println(super.name+" and "+name);
}
public static void main(String[] args)
{
Child cobj = new Child();
cobj.details();
}
}

Parent and Child

Example of Child class refering Parent


class methods using super keyword
class Parent
{
String name;
public void details()
{
name = "Parent";
System.out.println(name);
}
}
public class Child extends Parent {
String name;
public void details()
{
super.details(); //calling Parent class details() method
name = "Child";
System.out.println(name);
}
public static void main(String[] args)
{
Child cobj = new Child();
cobj.details();
}
}

Parent

Child

Example of Child class calling Parent


class constructor using super keyword
class Parent
{
String name;

public Parent(String n)
{
name = n;
}

}
public class Child extends Parent {
String name;

public Child(String n1, String n2)


{

super(n1); //passing argument to parent class constructor


this.name = n2;
}
public void details()
{
System.out.println(super.name+" and "+name);
}
public static void main(String[] args)
{
Child cobj = new Child("Parent","Child");
cobj.details();
}
}

Parent and Child

Note: When calling the parent class constructor from the child class using super
keyword, super keyword should always be the first line in the method/constructor of the
child class.

Super class reference pointing to Sub class object.


In context to above example where Class B extends class A.
A a=new B();
is legal syntax because of IS-A relationship is there between class A and Class B.

What is final in Java?


Final is a keyword in Java that is used to restrict the user and can be used in
many respects. Final can be used with:

 Variables

Variable declared as final


Once a variable is assigned with the keyword final, it always contains the
same exact value. Again things may happen like this; if a final variable holds
a reference to an object then the state of the object can be altered if
programmers perform certain operations on those objects, but the variable
will always refer to the same object. A final variable that is not initialized at
the time of declaration is known as a blank final variable. If you are declaring
a final variable in a constructor, then you must initialize the blank final
variable within the constructor of the class. Otherwise, the program might
show a compilation error.

Here is an example of a program in Java showing the


use of the final variable
Example:

import java.util.*;

import java.lang.*;

import java.io.*;

class stud {

final int val;

stud() {

val = 60;

void method() {

System.out.println(val);

public static void main(String args[]) {

stud S1 = new stud();

S1.method();

}
Method Overriding
When a method in a sub class has same name, same number of arguments and same
type signature as a method in its super class, then the method is known as overridden
method. Method overriding is also referred to as runtime polymorphism. The key benefit
of overriding is the abitility to define method that's specific to a particular subclass
type.

Example of Method Overriding


class Animal
{
public void eat()
{
System.out.println("Generic Animal eating");
}
}

class Dog extends Animal


{
public void eat() //eat() method overriden by Dog class.
{
System.out.println("Dog eat meat");
}
}
As you can see here Dog class gives it own implementation of eat() method. Method
must have same name and same type signature.
NOTE : Static methods cannot be overridden because, a static method is bounded with
class where as instance method is bounded with object.

Covariant return type


Since Java 5, it is possible to override a method by changing its return type. If subclass
override any method by changing the return type of super class method, then the return
type of overriden method must be subtype of return type declared in original method
inside the super class. This is the only way by which method can be overriden by
changing its return type.
Example :
class Animal
{
Animal myType()
{
return new Animal();
}
}

class Dog extends Animal


{
Dog myType() //Legal override after Java5 onward
{
return new Dog();
}
}

Difference between Overloading and Overriding

Method Overloading Method Overriding

Parameter must be different and Both name and parameter must be same.
name must be same.

Compile time polymorphism. Runtime polymorphism.

Increase readability of code. Increase reusability of code.

Access specifier can be changed. Access specifier cannot be more restrictive than original
method(can be less restrictive).
Command line argument in Java
The command line argument is the argument passed to a program at the time when you
run it. To access the command-line argument inside a java program is quite easy, they
are stored as string in String array passed to the args parameter of main() method.
Example
class cmd
{
public static void main(String[] args)
{
for(int i=0;i< args.length;i++)
{
System.out.println(args[i]);
}
}
}
Execute this program as java cmd 10 20 30

10

20

30
Java Package
Package are used in Java, in-order to avoid name conflicts and to control access of
class, interface and enumeration etc. A package can be defined as a group of similar
types of classes, interface, enumeration or sub-package. Using package it becomes
easier to locate the related classes and it also provides a good structure for projects with
hundreds of classes and other files.

Types of Packages: Built-in and User defined

 Built-in Package: Existing Java package for example java.lang, java.util etc.
 User-defined-package: Java package created by user to categorize their project's
classes and interface.
applet

Creating a package
Creating a package in java is quite easy. Simply include a package command followed
by name of the package as the first statement in java source file.
package mypack;
public class employee
{
statement;
}
The above statement will create a package woth name mypack in the project directory.
Java uses file system directories to store packages. For example the .java file for any
class you define to be part of mypack package must be stored in
a directory called mypack.
Additional points about package:

 A package is always defined as a separate folder having the same name as the
package name.
 Store all the classes in that package folder.
 All classes of the package which we wish to access outside the package must be
declared public.
 All classes within the package must have the package statement as its first line.
 All classes of the package must be compiled before use (So that they are error free)
Example of Java packages
//save as FirstProgram.java
package learnjava;
public class FirstProgram{
public static void main(String args[]) {
System.out.println("Welcome to package");
}
}

How to compile Java programs inside packages?


This is just like compiling a normal java program. If you are not using any IDE, you need
to follow the steps given below to successfully compile your packages:
javac -d directory javafilename
Example:
javac -d . FirstProgram.java
The -d switch specifies the destination where to put the generated class file. You can
use any directory name like d:/abc (in case of windows) etc. If you want to keep the
package within the same directory, you can use . (dot).

How to run Java package program?


You need to use fully qualified name e.g. learnjava.FirstProgram etc to run the class.
To Compile:
javac -d . FirstProgram.java
To Run:
java learnjava.FirstProgram
Output: Welcome to package

import keyword
import keyword is used to import built-in and user-defined packages into your java
source file so that your class can refer to a class that is in another package by directly
using its name.
There are 3 different ways to refer to any class that is present in a different package:
1. Using fully qualified name (But this is not a good practice.)

If you use fully qualified name to import any class into your program, then only that
particular class of the package will be accessible in your program, other classes in
the same package will not be accessible. For this approach, there is no need to use
the import statement. But you will have to use the fully qualified name every time
you are accessing the class or the interface, which can look a little untidy if the
package name is long.

This is generally used when two packages have classes with same names. For
example: java.util and java.sql packages contain Date class.

Example :
//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

2. To import only the class/classes you want to use

If you import packagename.classname then only the class with name classname in
the package with name packagename will be available for use.
Example :
//save by A.java
package pack;
public class A {
public void msg() {
System.out.println("Hello");
}
}

//save by B.java
package mypack;
import pack.A;
class B {
public static void main(String args[]) {
A obj = new A();
obj.msg();
}
}

Output:

Hello

3. To import all the classes from a particular package

If you use packagename.*, then all the classes and interfaces of this package will be
accessible but the classes and interface inside the subpackages will not be available
for use.

The import keyword is used to make the classes and interface of another package
accessible to the current package.

Example :
//save by First.java
package learnjava;
public class First{
public void msg() {
System.out.println("Hello");
}
}

//save by Second.java
package Java;
import learnjava.*;
class Second {
public static void main(String args[]) {
First obj = new First();
obj.msg();
}
}

Output:

Hello
Points to remember

 When a package name is not specified, the classes are defined into the default package
(the current working directory) and the package itself is given no name. That is why, you
were able to execute assignments earlier.
 While creating a package, care should be taken that the statement for creating package
must be written before any other import statements.

// not allowed
import package p1.*;
package p3;
Below code is correct, while the code mentioned above is incorrect.
//correct syntax
package p3;
import package p1.*;

Wrapper class in Java


Wrapper class in java provides the mechanism to convert primitive into object and
object into primitive.

Since J2SE 5.0, autoboxing and unboxing feature converts primitive into object and
object into primitive automatically. The automatic conversion of primitive into object is
known as autoboxing and vice-versa unboxing.
The eight classes of java.lang package are known as wrapper classes in java. The list of
eight wrapper classes are given below:

Primitive Type Wrapper class

boolean Boolean

char Character

byte Byte

short Short

int Integer

long Long

float Float

double Double

Wrapper class Example: Primitive to Wrapper


1. public class WrapperExample1
2. {
3. public static void main(String args[])
4. {
5. //Converting int into Integer
6. int a=20;
7. Integer i=Integer.valueOf(a);//converting int into Integer
8. System.out.println(a+" "+i);
9. }

10. }

Output:

20 20

Abstract class
If a class contain any abstract method then the class is declared as abstract class. An
abstract class is never instantiated. It is used to provide abstraction. Although it does not
provide 100% abstraction because it can also have concrete method.
Syntax :
abstract class class_name { }

Abstract method
Method that are declared without any body within an abstract class are called abstract
method. The method body will be defined by its subclass. Abstract method can never be
final and static. Any class that extends an abstract class must implement all the abstract
methods declared by the super class.
Syntax :
abstract return_type function_name (); //No definition

Example of Abstract class


abstract class A
{
abstract void callme();
}
class B extends A
{
void callme()
{
System.out.println("this is callme.");
}
public static void main(String[] args)
{
B b = new B();
b.callme();
}
}

this is callme.

Abstract class with concrete(normal) method.


Abstract classes can also have normal methods with definitions, along with abstract
methods.
abstract class A
{
abstract void callme();
public void normal()
{
System.out.println("this is concrete method");
}
}
class B extends A
{
void callme()
{
System.out.println("this is callme.");
}
public static void main(String[] args)
{
B b = new B();
b.callme();
b.normal();
}
}

this is callme.

this is concrete method.

Points to Remember

1. Abstract classes are not Interfaces. They are different, we will study this when we
will study Interfaces.
2. An abstract class may or may not have an abstract method. But if any class has
even a single abstract method, then it must be declared abstract.
3. Abstract classes can have Constructors, Member variables and Normal methods.
4. Abstract classes are never instantiated.
5. When you extend Abstract class with abstract method, you must define the abstract
method in the child class, or make the child class abstract.
Abstraction using abstract class
Abstraction is an important feature of OOPS. It means hiding complexity. Abstract class
is used to provide abstraction. Although it does not provide 100% abstraction because it
can also have concrete method. Lets see how abstract class is used to provide
abstraction.
abstract class Vehicle
{
public abstract void engine();
}
public class Car extends Vehicle {

public void engine()


{
System.out.println("Car engine");
//car engine implementation
}

public static void main(String[] args)


{
Vehicle v = new Car();
v.engine();
}
}

Car engine

Here by casting instance of Car type to Vehicle reference, we are hiding the complexity
of Car type under Vechicle. Now the Vehicle reference can be used to provide the
implementation but it will hide the actual implementation process.

Interface
Interface is a pure abstract class.They are syntactically similar to classes, but you
cannot create instance of an Interface and their methods are declared without any body.
Interface is used to achieve complete abstraction in Java. When you create an interface
it defines what a class can do without saying anything about how the class will do it.
Syntax :
interface interface_name { }

Example of Interface
interface Moveable
{
int AVERAGE-SPEED=40;
void move();
}

NOTE : Compiler automatically converts methods of Interface as public and abstract,


and the data members as public, static and final by default.

Rules for using Interface

 Methods inside Interface must not be static, final, native or strictfp.


 All variables declared inside interface are implicitly public static final
variables(constants).
 All methods declared inside Java Interfaces are implicitly public and abstract, even if
you don't use public or abstract keyword.
 Interface can extend one or more other interface.
 Interface cannot implement a class.
 Interface can be nested inside another interface.

Example of Interface implementation


interface Moveable
{
int AVG-SPEED = 40;
void move();
}

class Vehicle implements Moveable


{
public void move()
{
System .out. print in ("Average speed is"+AVG-SPEED");
}
public static void main (String[] arg)
{
Vehicle vc = new Vehicle();
vc.move();
}
}

Average speed is 40.

StringBuffer class
StringBuffer class is used to create a mutable string object i.e its state can be changed
after it is created. It represents growable and writable character sequence. As we know
that String objects are immutable, so if we do a lot of changes with String objects, we
will end up with a lot of memory leak.
So StringBuffer class is used when we have to make lot of modifications to our string. It
is also thread safe i.e multiple threads cannot access it simultaneously. StringBuffer
defines 4 constructors. They are,

1. StringBuffer ( )
2. StringBuffer ( int size )
3. StringBuffer ( String str )
4. StringBuffer ( charSequence [ ]ch )

 StringBuffer() creates an empty string buffer and reserves room for 16 characters.
 stringBuffer(int size) creates an empty string and takes an integer argument to

set capacity of the buffer.

Example showing difference between String and StringBuffer


class Test {
public static void main(String args[])
{
String str = "study";
str.concat("tonight");
System.out.println(str); // Output: study

StringBuffer strB = new StringBuffer("study");


strB.append("tonight");
System.out.println(strB); // Output: studytonight
}
}
Reason:
Output is such because String objects are immutable objects. Hence, if we concatenate
on the same String object, it won't be altered(Output: study). But StringBuffer creates
mutable objects. Hence, it can be altered(Output: studytonight)

Important methods of StringBuffer class


The following methods are some most commonly used methods of StringBuffer class.
append()
This method will concatenate the string representation of any type of data to the end of
the invoking StringBuffer object. append() method has several overloaded forms.
StringBuffer append(String str)

StringBuffer append(int n)

StringBuffer append(Object obj)


The string representation of each parameter is appended to StringBuffer object.
StringBuffer str = new StringBuffer("test");
str.append(123);
System.out.println(str);
test123

insert()
This method inserts one string into another. Here are few forms of insert() method.
StringBuffer insert(int index, String str)

StringBuffer insert(int index, int num)

StringBuffer insert(int index, Object obj)


Here the first parameter gives the index at which position the string will be inserted and
string representation of second parameter is inserted into StringBuffer object.
StringBuffer str = new StringBuffer("test");
str.insert(4, 123);
System.out.println(str);

test123

reverse()
This method reverses the characters within a StringBuffer object.
StringBuffer str = new StringBuffer("Hello");
str.reverse();
System.out.println(str);

olleH

replace()
This method replaces the string from specified start index to the end index.
<
StringBuffer str = new StringBuffer("Hello World");
str.replace( 6, 11, "java");
System.out.println(str);

Hello java
capacity()
This method returns the current capacity of StringBuffer object.
StringBuffer str = new StringBuffer();
System.out.println( str.capacity() );

16

Note: Empty constructor reserves space for 16 characters. Therefore the output is 16.

ensureCapacity()
This method is used to ensure minimum capacity of StringBuffer object.
If the argument of the ensureCapacity() method is less than the existing capacity, then
there will be no change in existing capacity.
If the argument of the ensureCapacity() method is greater than the existing capacity,
then there will be change in the current capacity using following rule: newCapacity =
(oldCapacity*2) + 2.
StringBuffer str = new StringBuffer();
System.out.println( str.capacity()); //output: 16 (since empty constructor
reserves space for 16 characters)
str.ensureCapacity(30); //greater than the existing capacity
System.out.println( str.capacity()); //output: 34 (by following the rule -
(oldcapacity*2) + 2.) i.e (16*2)+2 = 34.

String class function


The following methods are some of the most commonly used methods of String class.
charAt()
charAt() function returns the character located at the specified index.
String str = "studytonight";
System.out.println(str.charAt(2));
Output: u
NOTE: Index of a String starts from 0, hence str.charAt(2) means third character of
the String str.

equalsIgnoreCase()
equalsIgnoreCase() determines the equality of two Strings, ignoring thier case (upper
or lower case doesn't matters with this fuction ).
String str = "java";
System.out.println(str.equalsIgnoreCase("JAVA"));

true

indexOf()
indexOf() function returns the index of first occurrence of a substring or a
character. indexOf()method has four forms:

 int indexOf(String str): It returns the index within this string of the first

occurrence of the specified substring.


 int indexOf(int ch, int fromIndex): It returns the index within this string of the

first occurrence of the specified character, starting the search at the specified index.
 int indexOf(int ch): It returns the index within this string of the first occurrence of

the specified character.


 int indexOf(String str, int fromIndex): It returns the index within this string of

the first occurrence of the specified substring, starting at the specified index.

Example:
public class StudyTonight {
public static void main(String[] args) {
String str="StudyTonight";
System.out.println(str.indexOf('u')); //3rd form
System.out.println(str.indexOf('t', 3)); //2nd form
String subString="Ton";
System.out.println(str.indexOf(subString)); //1st form
System.out.println(str.indexOf(subString,7)); //4th form
}
}

11

-1
NOTE: -1 indicates that the substring/Character is not found in the given String.

length()
length() function returns the number of characters in a String.
String str = "Count me";
System.out.println(str.length());

trim()
This method returns a string from which any leading and trailing whitespaces has been
removed.
String str = " hello ";
System.out.println(str.trim());

hello

NOTE: If the whitespaces are between the string, for example: String s1 = "study
tonight"; then System.out.println(s1.trim()); will output "study tonight".

trim() method removes only the leading and trailing whitespaces.

Exception Handling
Exception Handling is the mechanism to handle runtime malfunctions. We need to
handle such exceptions to prevent abrupt termination of program. The term exception
means exceptional condition, it is a problem that may arise during the execution of
program. A bunch of things can lead to exceptions, including programmer error,
hardware failures, files that need to be opened cannot be found, resource exhaustion
etc.

Exception
A Java Exception is an object that describes the exception that occurs in a program.
When an exceptional events occurs in java, an exception is said to be thrown. The code
that's responsible for doing something about the exception is called an exception
handler.

Exception class Hierarchy


All exception types are subclasses of class Throwable, which is at the top of exception
class hierarchy.
 Exception class is for exceptional conditions that program should catch. This class
is extended to create user specific exception classes.
 RuntimeException is a subclass of Exception. Exceptions under this class are
automatically defined for programs.
 Exceptions of type Error are used by the Java run-time system to indicate errors
having to do with the run-time environment, itself. Stack overflow is an example of
such an error.

Exception are categorized into 3 category.

 Checked Exception

The exception that can be predicted by the programmer at the compile time.Example
: File that need to be opened is not found. These type of exceptions must be
checked at compile time.

 Unchecked Exception

Unchecked exceptions are the class that extends RuntimeException. Unchecked


exception are ignored at compile time. Example : ArithmeticException,
NullPointerException, Array Index out of Bound exception. Unchecked exceptions
are checked at runtime.
 Error

Errors are typically ignored in code because you can rarely do anything about an
error. Example :if stack overflow occurs, an error will arise. This type of error cannot
be handled in the code.

Uncaught Exceptions
When we don't handle the exceptions, they lead to unexpected program termination.
Lets take an example for better understanding.
class UncaughtException
{
public static void main(String args[])
{
int a = 0;
int b = 7/a; // Divide by zero, will lead to exception
}
}
This will lead to an exception at runtime, hence the Java run-time system will construct
an exception and then throw it. As we don't have any mechanism for handling exception
in the above program, hence the default handler will handle the exception and will print
the details of the exception on the terminal.

Exception Handling Mechanism


In java, exception handling is done using five keywords,

1. try
2. catch
3. throw
4. throws
5. finally
Exception handling is done by transferring the execution of a program to an appropriate
exception handler when exception occurs.

Using try and catch


Try is used to guard a block of code in which exception may occur. This block of code is
called guarded region. A catch statement involves declaring the type of exception you are
trying to catch. If an exception occurs in guarded code, the catch block that follows the try is
checked, if the type of exception that occured is listed in the catch block then the exception is
handed over to the catch block which then handles it.

Example using Try and catch


class Excp
{
public static void main(String args[])
{
int a,b,c;
try
{
a=0;
b=10;
c=b/a;
System.out.println("This line will not be executed");
}
catch(ArithmeticException e)
{
System.out.println("Divided by zero");
}
System.out.println("After exception is handled");
}
}

Divided by zero

After exception is handled

An exception will thrown by this program as we are trying to divide a number by zero
inside try block. The program control is transferred outside try block. Thus the line "This
line will not be executed" is never parsed by the compiler. The exception thrown is handled
in catch block. Once the exception is handled, the program control is continue with the next
line in the program i.e after catch block. Thus the line "After exception is handled" is printed.
Multiple catch blocks:
A try block can be followed by multiple catch blocks. You can have any number of catch
blocks after a single try block.If an exception occurs in the guarded code the exception is
passed to the first catch block in the list. If the exception type of exception, matches with the
first catch block it gets caught, if not the exception is passed down to the next catch block.
This continue until the exception is caught or falls through all catches.

Example for Multiple Catch blocks


class Excep
{
public static void main(String[] args)
{
try
{
int arr[]={1,2};
arr[2]=3/0;
}
catch(ArithmeticException ae)
{
System.out.println("divide by zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("array index out of bound exception");
}
}
}

divide by zero

Note: Although both ArrayIndexOutOfBoundsException and ArithmeticException occured,


but since first catch is of Arithmetic Exception, It will be caught there and program control
will be continued after the catch block.
Note: At a time, only one exception is processed and only one respective catch block is
executed.
Example for Unreachable Catch block
While using multiple catch statements, it is important to remember that sub classes of class
Exception inside catch must come before any of their super classes otherwise it will lead to
compile time error. This is because in Java, if any code is unreachable, then it gives compile
time error.
class Excep
{
public static void main(String[] args)
{
try
{
int arr[]={1,2};
arr[2]=3/0;
}
catch(Exception e) //This block handles all Exception
{
System.out.println("Generic exception");
}
catch(ArrayIndexOutOfBoundsException e) //This block is unreachable
{
System.out.println("array index out of bound exception");
}
}
}

Generic exception

Nested try statement


try statement can be nested inside another block of try. Nested try block is used when a part
of a block may cause one error while entire block may cause another error. In case if
inner try block does not have a catch handler for a particular exception then the outer try
catch block is checked for match.
class Excep
{
public static void main(String[] args)
{
try
{
int arr[]={5,0,1,2};
try
{
int x=arr[3]/arr[1];
}
catch(ArithmeticException ae)
{
System.out.println("divide by zero");
}
arr[4]=3;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("array index out of bound exception");
}
}
}

divide by zero

array index out of bound exception

Important points to Remember

1. If you do not explicitly use the try catch blocks in your program, java will provide a
default exception handler, which will print the exception details on the terminal,
whenever exception occurs.
2. Super class Throwable overrides toString() function, to display error message in form of
string.
3. While using multiple catch block, always make sure that sub-classes of Exception class
comes before any of their super classes. Else you will get compile time error.
4. In nested try catch, the inner try block uses its own catch block as well as catch block of
the outer try, if required.
5. Only the object of Throwable class or its subclasses can be thrown.
Try with Resource Statement
JDK 7 introduces a new version of try statement known as try-with-resources statement.
This feature add another way to exception handling with resources management. It is also
referred to as automatic resource management.
Syntax
try(resource-specification(there can be more than one resource))
{
//use the resource
}catch()
{...}
This try statement contains a parenthesis in which one or more resources is declared. Any
object that implements java.lang.AutoCloseable or java.io.Closeable, can be passed
as a parameter to try statement. A resource is an object that is used in program and must be
closed after the program is finished. The try-with-resources statement ensures that each
resource is closed at the end of the statement of the try block. You do not have to explicitly
close the resources.

Example without using try with Resource Statement


import java.io.*;
class Test
{
public static void main(String[] args)
{
try{
String str;
//opening file in read mode using BufferedReader stream
BufferedReader br=new BufferedReader(new FileReader("d:\\myfile.txt"));
while((str=br.readLine())!=null)
{
System.out.println(str);
}
br.close(); //closing BufferedReader stream
}catch(IOException ie)
{ System.out.println("exception"); }
}
}
Example using try with Resource Statement
import java.io.*;
class Test
{
public static void main(String[] args)
{
try(BufferedReader br=new BufferedReader(new FileReader("d:\\myfile.txt")))
{
String str;
while((str=br.readLine())!=null)
{
System.out.println(str);
}
}catch(IOException ie)
{ System.out.println("exception"); }
}
}
NOTE: In the above example, we do not need to explicitly call close() method to
close BufferedReader stream.

Points to Remember

1. A resource is an object in a program that must be closed after the program has finished.
2. Any object that implements java.lang.AutoCloseable or java.io.Closeable can be passed
as a parameter to try statement.
3. All the resources declared in the try-with-resources statement will be closed
automatically when the try block exits. There is no need to close it explicitly.
4. We can write more than one resources in the try statement.
5. In a try-with-resources statement, any catch or finally block is run after the resources
declared have been closed.

throw Keyword
throw keyword is used to throw an exception explicitly. Only object of Throwable class or its
sub classes can be thrown. Program execution stops on encountering throw statement, and
the closest catch statement is checked for matching type of exception.
Syntax :
throw ThrowableInstance

Creating Instance of Throwable class


There are two possible ways to create an instance of class Throwable,

1. Using a parameter in catch block.


2. Creating instance with new operator.

new NullPointerException("test");

This constructs an instance of NullPointerException with name test.

Example demonstrating throw Keyword


class Test
{
static void avg()
{
try
{
throw new ArithmeticException("demo");
}
catch(ArithmeticException e)
{
System.out.println("Exception caught");
}
}

public static void main(String args[])


{
avg();
}
}
In the above example the avg() method throw an instance of ArithmeticException, which is
successfully handled using the catch statement and thus, the program outputs "Exception
caught".

throws Keyword
Any method that is capable of causing exceptions must list all the exceptions possible during
its execution, so that anyone calling that method gets a prior knowledge about which
exceptions are to be handled. A method can do so by using the throws keyword.
Syntax :
type method_name(parameter_list) throws exception_list
{
//definition of method
}

Example demonstrating throws Keyword


class Test
{
static void check() throws ArithmeticException
{
System.out.println("Inside check function");
throw new ArithmeticException("demo");
}

public static void main(String args[])


{
try
{
check();
}
catch(ArithmeticException e)
{
System.out.println("caught" + e);
}
}
}
Inside check function

caughtjava.lang.ArithmeticException: demo

Difference between throw and throws


throw throws
throw keyword is used to throw an exception throws keyword is used to declare an exception
explicitly. possible during its execution.
throw keyword is followed by an instance of throws keyword is followed by one or more
Throwable class or one of its sub-classes. Exception class names separated by commas.
throw keyword is declared inside a method throws keyword is used with method signature
body. (method declaration).
We cannot throw multiple exceptions using We can declare multiple exceptions (separated
throw keyword. by commas) using throws keyword.

finally clause
A finally keyword is used to create a block of code that follows a try block. A finally block of
code is always executed whether an exception has occurred or not. Using a finally block, it
lets you run any cleanup type statements that you want to execute, no matter what happens in
the protected code. A finally block appears at the end of catch block.
Example demonstrating finally Clause
Class ExceptionTest
{
public static void main(String[] args)
{
int a[]= new int[2];
System.out.println("out of try");
try
{
System.out.println("Access invalid element"+ a[3]);
/* the above statement will throw ArrayIndexOutOfBoundException */
}
finally
{
System.out.println("finally is always executed.");
}
}
}

Out of try
finally is always executed.

Exception in thread main java. Lang. exception array Index out of bound exception.

You can see in above example even if exception is thrown by the program, which is not
handled by catch block, still finally block will get executed.

User defined Exception subclass


You can also create your own exception sub class simply by extending
java Exception class. You can define a constructor for your Exception sub class (not
compulsory) and you can override the toString() function to display your customized
message on catch.
class MyException extends Exception
{
private int ex;
MyException(int a)
{
ex=a;
}
public String toString()
{
return "MyException[" + ex +"] is less than zero";
}
}

class Test
{
static void sum(int a,int b) throws MyException
{
if(a<0)
{
throw new MyException(a); //calling constructor of user-defined
exception class
}
else
{
System.out.println(a+b);
}
}
public static void main(String[] args)
{
try
{
sum(-10, 10);
}
catch(MyException me)
{
System.out.println(me); //it calls the toString() method of user-
defined Exception
}
}
}

MyException[-10] is less than zero

Points to Remember

1. Extend the Exception class to create your own exception class.


2. You don't have to implement anything inside it, no methods are required.
3. You can have a Constructor if you want.
4. You can override the toString() function, to display customized message.

Introduction to Multithreading
A program can be divided into a number of small processes. Each small process can be
addressed as a single thread (a lightweight process). You can think of a lightweight process as
a virtual CPU that executes code or system calls. You usually do not need to concern yourself
with lightweight processes to program with threads. Multithreaded programs contain two or
more threads that can run concurrently and each thread defines a separate path of execution.
This means that a single program can perform two or more tasks simultaneously. For
example, one thread is writing content on a file at the same time another thread is performing
spelling check.
In Java, the word thread means two different things.

 An instance of Thread class.


 or, A thread of execution.
An instance of Thread class is just an object, like any other object in java. But a thread of
execution means an individual "lightweight" process that has its own call stack. In java each
thread has its own call stack.

The main thread


When we run any java program, the program begins to execute its code starting from the
main method. Therefore, the JVM creates a thread to start executing the code present
in main method. This thread is called as main thread. Although the main thread is
automatically created, you can control it by obtaining a reference to it by
calling currentThread() method.
Two important things to know about main thread are,

 It is the thread from which other threads will be produced.


 main thread must be always the last thread to finish execution.

class MainThread
{
public static void main(String[] args)
{
Thread t=Thread.currentThread();
t.setName("MainThread");
System.out.println("Name of thread is "+t);
}
}

Name of thread is Thread[MainThread,5,main]


Life cycle of a Thread

1. New : A thread begins its life cycle in the new state. It remains in this state until the
start() method is called on it.
2. Runnable : After invocation of start() method on new thread, the thread becomes
runnable.
3. Running : A thread is in running state if the thread scheduler has selected it.
4. Waiting : A thread is in waiting state if it waits for another thread to perform a task. In
this stage the thread is still alive.
5. Terminated : A thread enter the terminated state when it complete its task.

Thread Priorities
Every thread has a priority that helps the operating system determine the order in which
threads are scheduled for execution. In java thread priority ranges between 1 to 10,

 MIN-PRIORITY (a constant of 1)
 MAX-PRIORITY (a constant of 10)
By default every thread is given a NORM-PRIORITY(5). The main thread always have
NORM-PRIORITY.
Note: Thread priorities cannot guarantee that a higher priority thread will always be executed
first than the lower priority thread. The selection of the threads for execution depends upon
the thread scheduler which is platform dependent.

Thread Class
Thread class is the main class on which Java's Multithreading system is based. Thread class,
along with its companion interface Runnable will be used to create and run threads for
utilizing Multithreading feature of Java.

Constructors of Thread class

1. Thread ( )
2. Thread ( String str )
3. Thread ( Runnable r )
4. Thread ( Runnable r, String str)

You can create new thread, either by extending Thread class or by implementing Runnable
interface. Thread class also defines many methods for managing threads. Some of them are,

Method Description

setName() to give thread a name

getName() return thread's name

getPriority() return thread's priority

isAlive() checks if thread is still running or not

join() Wait for a thread to end


Method Description

run() Entry point for a thread

sleep() suspend thread for a specified time

start() start a thread by calling run() method

Some Important points to Remember

1. When we extend Thread class, we cannot override setName() and getName() functions,
because they are declared final in Thread class.
2. While using sleep(), always handle the exception it throws.

static void sleep(long milliseconds) throws InterruptedException

Creating a thread
Java defines two ways by which a thread can be created.

 By implementing the Runnable interface.


 By extending the Thread class.

Implementing the Runnable Interface


The easiest way to create a thread is to create a class that implements the runnable
interface. After implementing runnable interface , the class needs to implement
the run() method, which is of form,
public void run()

 run() method introduces a concurrent thread into your program. This thread will end
when run() method terminates.
 You must specify the code that your thread will execute inside run() method.
 run() method can call other methods, can use other classes and declare variables
just like any other normal method.

To call the run() method, start() method is used. On calling start(), a new stack is
provided to the thread and run() method is called to introduce the new thread into the
program.
Note: If you are implementing Runnable interface in your class, then you need to
explicitly create a Thread class object and need to pass the Runnable interface
implemented class object as a parameter in its constructor.

Syntax:-

Thread t=new Thread();

t.start;

class MyThread implements Runnable


{
public void run()
{
System.out.println("concurrent thread started running..");
}
}

class MyThreadDemo
{
public static void main( String args[] )
{
MyThread mt = new MyThread();
Thread t = new Thread(mt);
t.start();
}
}
concurrent thread started running..

To call the run() method, start() method is used. On calling start(), a new stack is
provided to the thread and run() method is called to introduce the new thread into the
program.
Note: If you are implementing Runnable interface in your class, then you need to
explicitly create a Thread class object and need to pass the Runnable interface
implemented class object as a parameter in its constructor.

Extending Thread class


This is another way to create a thread by a new class that extends Thread class and
create an instance of that class. The extending class must override run() method which
is the entry point of new thread.
class MyThread extends Thread
{
public void run()
{
System.out.println("concurrent thread started running..");
}
}

classMyThreadDemo
{
public static void main( String args[] )
{
MyThread mt = new MyThread();
mt.start();
}
}

concurrent thread started running..

In this case also, we must override the run() and then use the start() method to run the
thread. Also, when you create MyThread class object, Thread class constructor will also
be invoked, as it is the super class, hence MyThread class object acts as Thread class
object.

What if we call run() method directly without using start()


method ?
In above program if we directly call run() method, without using start() method,
public static void main( String args[] )
{
MyThread mt = new MyThread();
mt.run();
}
Doing so, the thread won't be allocated a new call stack, and it will start running in the
current call stack, that is the call stack of the main thread. Hence Multithreading won't
be there.

Can we Start a thread twice ?


No, a thread cannot be started twice. If you try to do
so, IllegalThreadStateException will be thrown.
public static void main( String args[] )
{
MyThread mt = new MyThread();
mt.start();
mt.start(); //Exception thrown
}
When a thread is in running state, and you try to start it again, or any method try to
invoke that thread again using start() method, exception is thrown.

IO Stream
Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O
system to make input and output operation in java. In general, a stream means
continuous flow of data. Streams are clean way to deal with input/output without having
every part of your code understand the physical.
Java encapsulates Stream under java.io package. Java defines two types of streams.
They are,

1. Byte Stream : It provides a convenient means for handling input and output of byte.
2. Character Stream : It provides a convenient means for handling input and output of
characters. Character stream uses Unicode and therefore can be internationalized.

Byte Stream Classes


Byte stream is defined by using two abstract class at the top of hierarchy, they are
InputStream and OutputStream.

These two abstract classes have several concrete classes that handle various devices
such as disk files, network connection etc.

Some important Byte stream classes.

Stream class Description

BufferedInputStream Used for Buffered Input Stream.

BufferedOutputStream Used for Buffered Output Stream.

DataInputStream Contains method for reading java standard datatype


DataOutputStream An output stream that contain method for writing java standard data
type

FileInputStream Input stream that reads from a file

FileOutputStream Output stream that write to a file.

InputStream Abstract class that describe stream input.

OutputStream Abstract class that describe stream output.

PrintStream Output Stream that contain print() and println() method

These classes define several key methods. Two most important are

1. read() : reads byte of data.


2. write() : Writes byte of data.

Character Stream Classes


Character stream is also defined by using two abstract class at the top of hierarchy, they
are Reader and Writer.

These two abstract classes have several concrete classes that handle unicode
character.
Some important Charcter stream classes.

Stream class Description

BufferedReader Handles buffered input stream.

BufferedWriter Handles buffered output stream.

FileReader Input stream that reads from file.

FileWriter Output stream that writes to file.

InputStreamReader Input stream that translate byte to character

OutputStreamReader Output stream that translate character to byte.

PrintWriter Output Stream that contain print() and println() method.

Reader Abstract class that define character stream input

Writer Abstract class that define character stream output

Reading Console Input


We use the object of BufferedReader class to take inputs from the keyboard.
Reading Characters
read() method is used with BufferedReader object to read characters. As this function
returns integer type value has we need to use typecasting to convert it into char type.
int read() throws IOException
Below is a simple example explaining character input.
class CharRead
{
public static void main( String args[])
{
BufferedReader br = new Bufferedreader(new InputstreamReader(System.in));
char c = (char)br.read(); //Reading character
}
}

Reading Strings
To read string we have to use readLine() function with BufferedReader class's object.
String readLine() throws IOException

Program to take String input from Keyboard in Java


import java.io.*;
class MyInput
{
public static void main(String[] args)
{
String text;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
text = br.readLine(); //Reading String
System.out.println(text);
}
}

Program to read from a file using BufferedReader class


import java. Io *;
class ReadTest
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/myfile.txt");
BufferedReader br = new BufferedReader(new FileReader(fl)) ;
String str;
while ((str=br.readLine())!=null)
{
System.out.println(str);
}
br.close();
fl.close();
}
catch (IOException e)
{ e.printStackTrace(); }
}
}

Program to write to a File using FileWriter class


import java. Io *;
class WriteTest
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/myfile.txt");
String str="Write this string to my file";
FileWriter fw = new FileWriter(fl) ;
fw.write(str);
fw.close();
fl.close();
}
catch (IOException e)
{ e.printStackTrace(); }
}
}

Applet in Java

 Applets are small Java applications that can be accessed on an Internet server, transported
over Internet, and can be automatically installed and run as apart of a web document.
 After a user receives an applet, the applet can produce a graphical user interface. It has
limited access to resources so that it can run complex computations without introducing
the risk of viruses or breaching data integrity.
 Any applet in Java is a class that extends the java.applet.Applet class.
 An Applet class does not have any main() method. It is viewed using JVM. The JVM can
use either a plug-in of the Web browser or a separate runtime environment to run an
applet application.
 JVM creates an instance of the applet class and invokes init() method to initialize an
Applet.

A Simple Applet
import java.awt.*;
import java.applet.*;
public class Simple extends Applet
{
public void paint(Graphics g)
{
g.drawString("A simple Applet", 20, 20);
}
}

Every Applet application must import two packages - java.awt and java.applet.
java.awt.* imports the Abstract Window Toolkit (AWT) classes. Applets interact with the
user (either directly or indirectly) through the AWT. The AWT contains support for a
window-based, graphical user interface. java.applet.* imports the applet package, which
contains the class Applet. Every applet that you create must be a subclass of Applet class.
The class in the program must be declared as public, because it will be accessed by code that
is outside the program.Every Applet application must declare a paint() method. This method
is defined by AWT class and must be overridden by the applet. The paint() method is called
each time when an applet needs to redisplay its output. Another important thing to notice
about applet application is that, execution of an applet does not begin at main() method. In
fact an applet application does not have any main() method.

Advantages of Applets

1. It takes very less response time as it works on the client side.


2. It can be run on any browser which has JVM running in it.

Applet class
Applet class provides all necessary support for applet execution, such as initializing and
destroying of applet. It also provide methods that load and display images and methods that
load and play audio clips.
An Applet Skeleton
Most applets override these four methods. These four methods forms Applet lifecycle.

 init() : init() is the first method to be called. This is where variable are initialized. This
method is called only once during the runtime of applet.
 start() : start() method is called after init(). This method is called to restart an applet after
it has been stopped.
 stop() : stop() method is called to suspend thread that does not need to run when applet is
not visible.
 destroy() : destroy() method is called when your applet needs to be removed completely
from memory.

Note: The stop() method is always called before destroy() method.

Example of an Applet Skeleton


import java.awt.*;
import java.applet.*;
public class AppletTest extends Applet
{
public void init()
{
//initialization
}
public void start ()
{
//start or resume execution
}
public void stop()
{
//suspend execution
{
public void destroy()
{
//perform shutdown activity
}
public void paint (Graphics g)
{
//display the content of window
}
}

Example of an Applet
import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet
{
int height, width;
public void init()
{
height = getSize().height;
width = getSize().width;
setName("MyApplet");
}
public void paint(Graphics g)
{
g.drawRoundRect(10, 30, 120, 120, 2, 3);
}
}
How to run an Applet Program
An Applet program is compiled in the same way as you have been compiling your console
programs. However there are two ways to run an applet.

 Executing the Applet within Java-compatible web browser.


 Using an Applet viewer, such as the standard tool, applet viewer. An applet viewer
executes your applet in a window

For executing an Applet in an web browser, create short HTML file in the same directory.
Inside bodytag of the file, include the following code. (applet tag loads the Applet class)
< applet code = "MyApplet" width=400 height=400 >

< /applet >

Run the HTML file


Running Applet using Applet Viewer
To execute an Applet with an applet viewer, write short HTML file as discussed above. If
you name it as run.htm, then the following command will run your applet program.
f:/>appletviewer run.htm

Event Handling
Any program that uses GUI (graphical user interface) such as Java application written
for windows, is event driven. Event describes the change in state of any object. For
Example : Pressing a button, Entering a character in Textbox, Clicking or Dragging a
mouse, etc.

Components of Event Handling


Event handling has three main components,

 Events : An event is a change in state of an object.


 Events Source : Event source is an object that generates an event.
 Listeners : A listener is an object that listens to the event. A listener gets notified
when an event occurs.

How Events are handled ?


A source generates an Event and send it to one or more listeners registered with the
source. Once event is received by the listener, they process the event and then return.
Events are supported by a number of Java packages,
like java.util, java.awt and java.awt.event.

Important Event Classes and Interface

Event Classes Description Listener Interface

ActionEvent generated when button is pressed, menu-item ActionListener


is selected, list-item is double clicked

MouseEvent generated when mouse is dragged, MouseListener


moved,clicked,pressed or released and also
when it enters or exit a component

KeyEvent generated when input is received from KeyListener


keyboard

ItemEvent generated when check-box or list item is ItemListener


clicked

TextEvent generated when value of textarea or textfield TextListener


is changed

MouseWheelEvent generated when mouse wheel is moved MouseWheelListener

WindowEvent generated when window is activated, WindowListener


deactivated, deiconified, iconified, opened or
closed

ComponentEvent generated when component is hidden, ComponentEventListener


moved, resized or set visible

ContainerEvent generated when component is added or ContainerListener


removed from container

AdjustmentEvent generated when scroll bar is manipulated AdjustmentListener

FocusEvent generated when component gains or loses FocusListener


keyboard focus

Steps to handle events:

1. Implement appropriate interface in the class.


2. Register the component with the listener.

Example of Event Handling


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.applet.*;
import java.awt.event.*;
import java.awt.*;

public class Test extends Applet implements KeyListener


{
String msg="";
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent k)
{
showStatus("KeyPressed");
}
public void keyReleased(KeyEvent k)
{
showStatus("KeyRealesed");
}
public void keyTyped(KeyEvent k)
{
msg = msg+k.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg, 20, 40);
}
}
HTML code :
< applet code="Test" width=300, height=100 >

Abstract Window Toolkit(AWT)


AWT contains large number of classes and methods that allows you to create and
manage graphical user interface ( GUI ) applications, such as windows, buttons, scroll
bars,etc. The AWT was designed to provide a common set of tools for GUI design that
could work on a variety of platforms. The tools provided by the AWT are implemented
using each platform's native GUI toolkit, hence preserving the look and feel of each
platform. This is an advantage of using AWT.But the disadvantage of such an approach
is that GUI designed on one platform may look different when displayed on another
platform.
AWT is the foundation upon which Swing is made i.e Swing is a set of GUI interfaces
that extends the AWT. But now a days AWT is merely used because most GUI Java
programs are implemented using Swing because of its rich implementation of GUI
controls and light-weighted nature.
AWT Hierarchy

Component class
Component class is at the top of AWT hierarchy. Component is an abstract class that
encapsulates all the attributes of visual component. A component object is responsible
for remembering the current foreground and background colors and the currently
selected text font.

Container
Container is a component in AWT that contains another component like button, text
field, tables etc. Container is a subclass of component class. Container class keeps
track of components that are added to another component.

Panel
Panel class is a concrete subclass of Container. Panel does not contain title bar, menu
bar or border. It is container that is used for holding components.

Window class
Window class creates a top level window. Window does not have borders and menubar.
Frame
Frame is a subclass of Window and have resizing canvas. It is a container that contain
several different components like button, title bar, textfield, label etc. In Java, most of the
AWT applications are created using Frame window. Frame class has two different
constructors,
Frame() throws HeadlessException

Frame(String title) throws HeadlessException

Creating a Frame
There are two ways to create a Frame. They are,

1. By Instantiating Frame class


2. By extending Frame class

Creating Frame Window by Instantiating Frame class


import java.awt.*;
public class Testawt
{
Testawt()
{
Frame fm=new Frame(); //Creating a frame.
Label lb = new Label("welcome to java graphics"); //Creating a label
fm.add(lb); //adding label to the frame.
fm.setSize(300, 300); //setting frame size.
fm.setVisible(true); //set frame visibilty true.
}
public static void main(String args[])
{
Testawt ta = new Testawt();
}
}
Creating Frame window by extending Frame class
package testawt;

import java.awt.*;
import java.awt.event.*;

public class Testawt extends Frame


{
public Testawt()
{

Button btn=new Button("Hello World");


add(btn); //adding a new Button.
setSize(400, 500); //setting size.
setTitle("StudyTonight"); //setting title.
setLayout(new FlowLayout()); //set default layout for frame.
setVisible(true); //set frame visibilty true.

}
public static void main (String[] args)
{
Testawt ta = new Testawt(); //creating a frame.
}
}

Points to Remember:

1. While creating a frame (either by instantiating or extending Frame class), Following


two attributes are must for visibility of the frame:
o setSize(int width, int height);
o setVisible(true);

2. When you create other components like Buttons, TextFields, etc. Then you need to
add it to the frame by using the method - add(Component's Object);
3. You can add the following method also for resizing the frame - setResizable(true);

Swing
Swing Framework contains a set of classes that provides more powerful and flexible GUI
components than those of AWT. Swing provides the look and feel of modern Java GUI.
Swing library is an official Java GUI tool kit released by Sun Microsystems. It is used to
create graphical user interface with Java.
Swing classes are defined in javax.swing package and its sub-packages.

Main Features of Swing Toolkit

1. Platform Independent
2. Customizable
3. Extensible
4. Configurable
5. Lightweight
6. Rich Controls
7. Pluggable Look and Feel

Swing and JFC


JFC is an abbreviation for Java Foundation classes, which encompass a group of features for
building Graphical User Interfaces(GUI) and adding rich graphical functionalities and
interactivity to Java applications. Java Swing is a part of Java Foundation Classes (JFC).

Features of JFC

 Swing GUI components.


 Look and Feel support.
 Java 2D.

AWT and Swing Hierarchy


Introduction to Swing Classes
JPanel : JPanel is Swing's version of AWT class Panel and uses the same default layout,
FlowLayout. JPanel is descended directly from JComponent.
JFrame : JFrame is Swing's version of Frame and is descended directly from Frame class.
The component which is added to the Frame, is refered as its Content.
JWindow : This is Swing's version of Window and has descended directly
from Window class. Like Window it uses BorderLayout by default.
JLabel : JLabel has descended from JComponent, and is used to create text labels.
JButton : JButton class provides the functioning of push button. JButton allows an icon,
string or both associated with a button.
JTextField : JTextFields allow editing of a single line of text.

Creating a JFrame
There are two ways to create a JFrame Window.

1. By instantiating JFrame class.


2. By extending JFrame class.

Creating JFrame window by Instantiating JFrame class


import javax.swing.*; //importing swing package
import java.awt.*; //importing awt package
public class First
{
JFrame jf;
public First() {
jf = new JFrame("MyWindow"); //Creating a JFrame with name
MyWindow
JButton btn = new JButton("Say Hello");//Creating a Button named Say Hello
jf.add(btn); //adding button to frame
jf.setLayout(new FlowLayout()); //setting layout using FlowLayout
object
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //setting close
operation.
jf.setSize(400, 400); //setting size
jf.setVisible(true); //setting frame visibility
}
public static void main(String[] args)
{
new First();
}
}
Creating JFrame window by extending JFrame class
import javax.swing.*; //importing swing package
import java.awt.*; //importing awt package
public class Second extends JFrame
{
public Second()
{
setTitle("MyWindow"); //setting title of frame as MyWindow
JLabel lb = new JLabel("Welcome to My Second Window");//Creating a label
named Welcome to My Second Window
add(lb); //adding label to frame.
setLayout(new FlowLayout()); //setting layout using FlowLayout object.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //setting close
operation.
setSize(400, 400); //setting size
setVisible(true); //setting frame visibility
}
public static void main(String[] args)
{
new Second();
}
}

Points To Remember

1. Import the javax.swing and java.awt package to use the classes and methods of Swing.
2. While creating a frame (either by instantiating or extending Frame class), following two
attributes are must for visibility of the frame:
3. setSize(int width, int height);
setVisible(true);

4. When you create objects of other components like Buttons, TextFields, etc. Then you
need to add it to the frame by using the method - add(Component's Object);
5. You can add the following method also for resizing the frame - setResizable(true);

Swing Components and Containers


A component is an independent visual control. Swing Framework contains a large set of
components which provide rich functionalities and allow high level of customization. They
all are derived from JComponent class. All these components are lightweight components.
This class provides some common functionality like pluggable look and feel, support for
accessibility, drag and drop, layout, etc.
A container holds a group of components. It provides a space where a component can be
managed and displayed. Containers are of two types:

1. Top level Containers


o It inherits Component and Container of AWT.
o It cannot be contained within other containers.
o Heavyweight.
o Example: JFrame, JDialog, JApplet
2. Lightweight Containers
o It inherits JComponent class.
o It is a general purpose container.
o It can be used to organize related components together.
o Example: JPanel

JButton
JButton class provides functionality of a button. JButton class has three constuctors,
JButton(Icon ic)

JButton(String str)

JButton(String str, Icon ic)


It allows a button to be created using icon, a string or both. JButton supports ActionEvent.
When a button is pressed an ActionEvent is generated.

Example using JButton


import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class testswing extends JFrame
{
testswing()
{
JButton bt1 = new JButton("Yes"); //Creating a Yes Button.
JButton bt2 = new JButton("No"); //Creating a No Button.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) //setting close
operation.
setLayout(new FlowLayout()); //setting layout using FlowLayout
object
setSize(400, 400); //setting size of Jframe
add(bt1); //adding Yes button to frame.
add(bt2); //adding No button to frame.

setVisible(true);
}
public static void main(String[] args)
{
new testswing();
}
}

JTextField
JTextField is used for taking input of single line of text. It is most widely used text
component. It has three constructors,
JTextField(int cols)
JTextField(String str, int cols)
JTextField(String str)
cols represent the number of columns in text field.

Example using JTextField


import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class MyTextField extends JFrame
{
public MyTextField()
{
JTextField jtf = new JTextField(20);//creating JTextField.
add(jtf); //adding JTextField to frame.
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args)
{
new MyTextField();
}
}
JCheckBox
JCheckBox class is used to create checkboxes in frame. Following is constructor for
JCheckBox,
JCheckBox(String str)

Example using JCheckBox


import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Test extends JFrame
{
public Test()
{
JCheckBox jcb = new JCheckBox("yes"); //creating JCheckBox.
add(jcb); //adding JCheckBox to frame.
jcb = new JCheckBox("no"); //creating JCheckBox.
add(jcb); //adding JCheckBox to frame.
jcb = new JCheckBox("maybe"); //creating JCheckBox.
add(jcb); //adding JCheckBox to frame.
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args)
{
new Test();
}
}

JRadioButton
Radio button is a group of related button in which only one can be selected. JRadioButton
class is used to create a radio button in Frames. Following is the constructor for
JRadioButton,
JRadioButton(String str)

Example using JRadioButton


import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Test extends JFrame
{
public Test()
{
JRadioButton jcb = new JRadioButton("A"); //creating JRadioButton.
add(jcb); //adding JRadioButton to
frame.
jcb = new JRadioButton("B"); //creating JRadioButton.
add(jcb); //adding JRadioButton to
frame.
jcb = new JRadioButton("C"); //creating JRadioButton.
add(jcb); //adding JRadioButton to
frame.
jcb = new JRadioButton("none");
add(jcb);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args)
{
new Test();
}
}

JComboBox
Combo box is a combination of text fields and drop-down list.JComboBox component is
used to create a combo box in Swing. Following is the constructor for JComboBox,
JComboBox(String arr[])

Example using JComboBox


import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Test extends JFrame
{
String name[] = {"Abhi","Adam","Alex","Ashkay"}; //list of name.
public Test()
{
JComboBox jc = new JComboBox(name); //initialzing combo box with list of
name.
add(jc); //adding JComboBox to frame.
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args)
{
new Test();
}
}

A program to change background color of a frame (Using


Action Event)
import java.awt.*; //importing awt package
import javax.swing.*; //importing swing package
import java.awt.event.*; //importing event package
//For an event to occur upon clicking the button, ActionListener interface
should be implemented
class StColor extends JFrame implements ActionListener{

JFrame frame;
JPanel panel;
JButton b1,b2,b3,b4,b5;

StColor(){

frame = new JFrame("COLORS");


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

panel = new JPanel(); //Creating a panel which is a container and will


hold all the buttons
panel.setSize(100, 50);

b1 = new JButton("BLUE"); //Creating a button named BLUE


b1.addActionListener(this); //Registering the button with the listener

b2 = new JButton("RED"); //Creating a button named RED


b2.addActionListener(this); //Registering the button with the listener

b3 = new JButton("CYAN");//Creating a button named CYAN


b3.addActionListener(this);//Registering the button with the listener

b4 = new JButton("PINK"); //Creating a button named PINK


b4.addActionListener(this); //Registering the button with the listener

b5 = new JButton("MAGENTA"); //Creating a button named MAGENTA


b5.addActionListener(this); //Registering the button with the listener

//Adding buttons to the Panel


panel.add(b1);
panel.add(b2);
panel.add(b3);
panel.add(b4);
panel.add(b5);
frame.getContentPane().add(panel); //adding panel to the frame
frame.setSize(500,300);
frame.setVisible(true);
frame.setLayout(new FlowLayout());

}
//The below method is called whenever a button is clicked
@Override
public void actionPerformed(ActionEvent e) {

//This method returns an object of the button on which the Event-


Pressing of button initially occurred
Object see = e.getSource();

if(see ==(b1)){ //Checking if the object returned is of button1


frame.getContentPane().setBackground(java.awt.Color.blue);
//changing the panel color to blue
}
if(see == b2){ //Checking if the object returned is of button2
frame.getContentPane().setBackground(java.awt.Color.red);
//changing the panel color to red
}
if(see == b3){ //Checking if the object returned is of button3

frame.getContentPane().setBackground(java.awt.Color.cyan);//changing the
panel color to cyan
}
if(see == b4){ //Checking if the object returned is of button4
frame.getContentPane().setBackground(java.awt.Color.pink);
//changing the panel color to pink
}
if(see == b5){ //Checking if the object returned is of button5
frame.getContentPane().setBackground(java.awt.Color.magenta);
//changing the panel color to magenta
}
}
}

class Test {
public static void main(String[] args) {
StColor o = new StColor();
}
}

Ouput:

Introduction to JDBC
Java Database Connectivity(JDBC) is an Application Programming Interface(API) used
to connect Java application with Database. JDBC is used to interact with various type of
Database such as Oracle, MS Access, My SQL and SQL Server. JDBC can also be defined as
the platform-independent interface between a relational database and Java programming. It
allows java program to execute SQL statement and retrieve result from database.
What's new in JDBC 4.0
JDBC 4.0 is new and advance specification of JDBC. It provides the following advance
features

 Connection Management
 Auto loading of Driver Interface.
 Better exception handling
 Support for large object
 Annotation in SQL query.

JDBC Driver
JDBC Driver is required to process SQL requests and generate result. The following are the
different types of driver available in JDBC.
 Type-1 Driver or JDBC-ODBC bridge
 Type-2 Driver or Native API Partly Java Driver
 Type-3 Driver or Network Protocol Driver
 Type-4 Driver or Thin Driver

JDBC-ODBC bridge
Type-1 Driver act as a bridge between JDBC and other database connectivity
mechanism(ODBC). This driver converts JDBC calls into ODBC calls and redirects the
request to the ODBC driver.

Advantage

 Easy to use
 Allow easy connectivity to all database supported by the ODBC Driver.

Disadvantage

 Slow execution time


 Dependent on ODBC Driver.
 Uses Java Native Interface(JNI) to make ODBC call.

Native API Driver


This type of driver make use of Java Native Interface(JNI) call on database specific native
client API. These native client API are usually written in C and C++.
Advantage

 faster as compared to Type-1 Driver


 Contains additional features.

Disadvantage

 Requires native library


 Increased cost of Application

Network Protocol Driver


This driver translate the JDBC calls into a database server independent and Middleware
server-specific calls. Middleware server further translate JDBC calls into database specific
calls.
Advantage

 Does not require any native library to be installed.


 Database Independency.
 Provide facility to switch over from one database to another database.

Disadvantage

 Slow due to increase number of network call.

Thin Driver
This is Driver called Pure Java Driver because. This driver interact directly with database. It
does not require any native database library, that is why it is also known as Thin Driver.
Advantage

 Does not require any native library.


 Does not require any Middleware server.
 Better Performance than other driver.

Disadvantage

 Slow due to increase number of network call.

JDBC 4.0 API


JDBC 4.0 API is mainly divided into two package

1. java.sql
2. javax.sql

java.sql package
This package include classes and interface to perform almost all JDBC operation such
as creating and executing SQL Queries.
Important classes and interface of java.sql package

classes/interface Description

java.sql.BLOB Provide support for BLOB(Binary Large Object) SQL type.

java.sql.Connection creates a connection with specific database

java.sql.CallableStateme Execute stored procedures


nt

java.sql.CLOB Provide support for CLOB(Character Large Object) SQL type.

java.sql.Date Provide support for Date SQL type.

java.sql.Driver create an instance of a driver with the DriverManager.

java.sql.DriverManager This class manages database drivers.

java.sql.PreparedStateme Used to create and execute parameterized query.


nt

java.sql.ResultSet It is an interface that provide methods to access the result row-by-


row.

java.sql.Savepoint Specify savepoint in transaction.

java.sql.SQLException Encapsulate all JDBC related exception.

java.sql.Statement This interface is used to execute SQL statements.

javax.sql package
This package is also known as JDBC extension API. It provides classes and interface to
access server-side data.

Important classes and interface of javax.sql package

classes/interface Description

javax.sql.ConnectionEvent Provide information about occurence of event.

javax.sql.ConnectionEventListe Used to register event generated


ner by PooledConnectionobject.

javax.sql.DataSource Represent the DataSource interface used in an


application.

javax.sql.PooledConnection provide object to manage connection pools.

Steps to connect a Java Application to


Database
The following 5 steps are the basic steps involve in connecting a Java application with
Database using JDBC.

1. Register the Driver


2. Create a Connection
3. Create SQL Statement
4. Execute SQL Statement
5. Closing the connection
Register the Driver
Class.forName() is used to load the driver class explicitly.
Example to register with JDBC-ODBC Driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Create a Connection
getConnection() method of DriverManager class is used to create a connection.
Syntax
getConnection(String url)
getConnection(String url, String username, String password)
getConnection(String url, Properties info)
Example establish connection with Oracle Driver
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","username
","password");

Create SQL Statement


createStatement() method is invoked on current Connection object to create a SQL
Statement.
Syntax
public Statement createStatement() throws SQLException
Example to create a SQL statement
Statement s=con.createStatement();

Execute SQL Statement


executeQuery() method of Statement interface is used to execute SQL statements.
Syntax
public ResultSet executeQuery(String query) throws SQLException
Example to execute a SQL statement
ResultSet rs=s.executeQuery("select * from user");
while(rs.next())
{
System.out.println(rs.getString(1)+" "+rs.getString(2));
}

Closing the connection


After executing SQL statement you need to close the connection and release the session.
The close() method of Connection interface is used to close the connection.
Syntax
public void close() throws SQLException
Example of closing a connection
con.close();

Connecting to Access Database using


Type-1 Driver
To connect a Java application with Access database using JDBC-ODBC Bridge(type-1)
Driver. You need to follow the following steps
Create DSN Name

1. Go to control panel

2. Go to Administrative tools

3. Select Data Source(ODBC)


4. Add new DSN name, select add

5. Select Access driver from the list, click on finish

6. Give a DSN name, click ok


NOTE: Here we are showing this example to create DSN in Window 7 os. For other
operating system you need to do small changes.

Example
We suppose that you have created a student table with sid and name column name in access
database.
import java.sql.*;
class Test
{
public static void main(String []args)
{
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:Test", "",
"");
Statement s=con.createStatement(); //creating statement

ResultSet rs=s.executeQuery("select * from student"); //executing


statement

while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}

con.close(); //closing connection

}
catch(Exception e)
{
e.printStackTrace();
}
}
}

Connecting to Oracle Database using Thin


Driver
To connect a Java application with Oracle database using Thin Driver. You need to follow
the following steps

1. Load Driver Class: The Driver Class for oracle database


is oracle.jdbc.driver.OracleDriver and Class.forName("oracle.jdbc.driver.Orac
leDriver") method is used to load the driver class for Oracle database.
2. Create Connection: For creating a connection you will need a Connection URL. The
Connection URL for Oracle is

You will also require Username and Password of your Oracle Database Server for
creating connection.
3. Loading jar file: To connect your java application with Oracle, you will also need to
load ojdbc14.jar file. This file can be loaded into 2 ways.
1. Copy the jar file into C:\Program Files\Java\jre7\lib\ext folder.

or,

2. Set it into classpath. For more detail see how to set classpath

Download ojdbc14.jar file


NOTE: Here we are discussing about Oracle 10g as database. For other version of Oracle
you will be require to do some small changes in the Connection URL.

Example
Create a table in Oracle Database
create table Student(sid number(10),sname varchar2(20));

Insert some record into the table


insert into Student values(101,'adam');

insert into Student values(102,'abhi');

Accessing record from Student table in Java application


import java.sql.*;
class Test
{
public static void main(String []args)
{
try{
//Loading driver
Class.forName("oracle.jdbc.driver.OracleDriver");

//creating connection
Connection con = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:XE","username","password");

Statement s=con.createStatement(); //creating statement

ResultSet rs=s.executeQuery("select * from Student"); //executing statement

while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}

con.close(); //closing connection


}catch(Exception e){
e.printStacktrace();
}
}
}

101 adam

102 abhi

Inserting record into a table using java application


import java.sql.*;
class Test
{
public static void main(String []args)
{
try{
//Loading driver...
Class.forName("oracle.jdbc.driver.OracleDriver");

//creating connection...
Connection con = DriverManager.getConnection

("jdbc:oracle:thin:@localhost:1521:XE","username","password");

PreparedStatement pst=con.prepareStatement("insert into Student


values(?,?)");
pst.setInt(1,104);
pst.setString(2,"Alex");
pst.executeUpdate();

con.close(); //closing connection


}catch(Exception e){
e.printStacktrace();
}
}
}

Connecting to MySQL Database using Thin


Driver
To connect a Java application with MySQL database using Thin Driver. You need to follow
the following steps

1. Load Driver Class: The Driver Class for MySQL database


is com.mysql.jdbc.Driver and Class.forName("com.mysql.jdbc.Driver") method is
used to load the driver class for MySQL database.
2. Create Connection: For creating a connection you will need a Connection URL. The
Connection URL for MySQL is

You will also require Username and Password of your MySQL Database Server for
creating connection.
3. Loading jar file: To connect your java application with MySQL, you will also need to
load mysql-connector.jar file. This file can be loaded into 2 ways.
1. Copy the jar file into C:\Program Files\Java\jre7\lib\ext folder.

or,

2. Set it into classpath. For more detail see how to set classpath

Download mysql-connector.jar file

Example
Create a table in MySQL Database
create table Student(sid int(10),name varchar(20));

Insert some record into the table


insert into Student values(102,'adam');

insert into Student values(103,'abhi');

Accessing record from Student table in Java application


import java.sql.*;
class Test
{
public static void main(String []args)
{
try{
//Loading driver
Class.forName("com.mysql.jdbc.Driver");

//creating connection
Connection con = DriverManager.getConnection
("jdbc:mysql:/
/localhost:3306/test","username","password");
Statement s = con.createStatement(); //creating statement

ResultSet rs = s.executeQuery("select * from Student"); //executing


statement

while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}

con.close(); //closing connection


}catch(Exception e){
e.printStacktrace();
}
}
}

102 adam

103 abhi

Inserting record into a table using java application


import java.sql.*;
class Test
{
public static void main(String []args)
{
try{
//Loading driver
Class.forName("com.mysql.jdbc.Driver");

//creating connection
Connection con = DriverManager.getConnection
("jdbc:mysql:/
/localhost:3306/test","username","password");

PreparedStatement pst=con.prepareStatement("insert into Student


values(?,?)");

pst.setInt(1,104);
pst.setString(2,"Alex");
pst.executeUpdate();

con.close(); //closing connection


}catch(Exception e){
e.printStacktrace();
}
}
}

You might also like