Java
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 a task to develop a language for digital devices such as set-top boxes,
televisions etc.
JAVA (1995) : All the team members decided to change the name to java
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.
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.
program.
They are:-
Stack memory:-
Heap area:-
PC register:-
Execution Engine:-
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
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
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
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:
DATA 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++.
1. Numeric.
2. Non numeric.
Numeric:-
The numeric data types are used to defined and declared the number type values in the
program.
1. Integer type.
2. Floating point.
Integer Type:-
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.
Type casting
Type casting is the process of converting one data type to another data type.
Int a;
a=b;
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.
1. Simple if statement.
2. If else statement.
3. Nested if statement.
4. Else if ladder.
Simple if statement:-
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
IF ELSE STATEMENT:-
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
NESTED IF CONDITION:-
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
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.
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:-
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:-
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.
Syntax:-
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.
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.
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.
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="";
}
}
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.
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.
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.
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();
}
}
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,
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.
Child method
Parent method
sports Car
Types of Inheritance
1. Single Inheritance
2. Multilevel Inheritance
3. Heirarchical Inheritance
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
Child
public Parent(String n)
{
name = n;
}
}
public class Child extends Parent {
String name;
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.
Variables
import java.util.*;
import java.lang.*;
import java.io.*;
class stud {
stud() {
val = 60;
void method() {
System.out.println(val);
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.
Parameter must be different and Both name and parameter must be same.
name must be same.
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.
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");
}
}
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
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
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.*;
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:
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
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
this is callme.
this is callme.
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 {
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();
}
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
StringBuffer append(int n)
insert()
This method inserts one string into another. Here are few forms of insert() method.
StringBuffer insert(int index, String 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.
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
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 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".
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.
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
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.
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.
Divided by zero
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.
divide by zero
Generic exception
divide by zero
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.
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
new NullPointerException("test");
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
}
caughtjava.lang.ArithmeticException: demo
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.
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
}
}
}
Points to Remember
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.
class MainThread
{
public static void main(String[] args)
{
Thread t=Thread.currentThread();
t.setName("MainThread");
System.out.println("Name of thread is "+t);
}
}
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.
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
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.
Creating a thread
Java defines two ways by which a thread can be created.
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:-
t.start;
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.
classMyThreadDemo
{
public static void main( String args[] )
{
MyThread mt = new MyThread();
mt.start();
}
}
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.
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.
These two abstract classes have several concrete classes that handle various devices
such as disk files, network connection etc.
These classes define several key methods. Two most important are
These two abstract classes have several concrete classes that handle unicode
character.
Some important Charcter stream classes.
Reading Strings
To read string we have to use readLine() function with BufferedReader class's object.
String readLine() throws IOException
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
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.
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.
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 >
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.
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
Creating a Frame
There are two ways to create a Frame. They are,
import java.awt.*;
import java.awt.event.*;
}
public static void main (String[] args)
{
Testawt ta = new Testawt(); //creating a frame.
}
}
Points to Remember:
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.
1. Platform Independent
2. Customizable
3. Extensible
4. Configurable
5. Lightweight
6. Rich Controls
7. Pluggable Look and Feel
Features of JFC
Creating a JFrame
There are two ways to create a JFrame Window.
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);
JButton
JButton class provides functionality of a button. JButton class has three constuctors,
JButton(Icon ic)
JButton(String str)
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.
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)
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[])
JFrame frame;
JPanel panel;
JButton b1,b2,b3,b4,b5;
StColor(){
}
//The below method is called whenever a button is clicked
@Override
public void actionPerformed(ActionEvent e) {
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
Disadvantage
Disadvantage
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
Disadvantage
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
javax.sql package
This package is also known as JDBC extension API. It provides classes and interface to
access server-side data.
classes/interface Description
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");
1. Go to control panel
2. Go to Administrative tools
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
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
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
Example
Create a table in Oracle Database
create table Student(sid number(10),sname varchar2(20));
//creating connection
Connection con = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:XE","username","password");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
101 adam
102 abhi
//creating connection...
Connection con = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:XE","username","password");
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
Example
Create a table in MySQL Database
create table Student(sid int(10),name varchar(20));
//creating connection
Connection con = DriverManager.getConnection
("jdbc:mysql:/
/localhost:3306/test","username","password");
Statement s = con.createStatement(); //creating statement
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
102 adam
103 abhi
//creating connection
Connection con = DriverManager.getConnection
("jdbc:mysql:/
/localhost:3306/test","username","password");
pst.setInt(1,104);
pst.setString(2,"Alex");
pst.executeUpdate();