S4 Java Full
S4 Java Full
S4 Java Full
Name : ……………………………………………………………………………………………
MODULE 1
History of Java
• Java Programming Language was written by James Gosling along with two other person ‘Mike
Sheridan‘ and ‘Patrick Naughton‘, while they were working at Sun Microsystems.
• It was Initially it was named oak .
• The latest Releases is : Java Version 1.8 is the current stable release which was released this
year (2015).
• Java is implemented over a number of places in modern world. It is implemented as Standalone
Application, Web Application, Enterprise Application and Mobile Application. Games, Smart
Card, Embedded System, Robotics, Desktop, etc.
Five Goals which were taken into consideration while developing Java:
Java capabilities are not limited to any specific application domain rather it can be used in various
application domain and hence it is called General Purpose Programming Language.
2.Class based
Java is a class based/oriented programming language which means Java supports inheritance feature of
object-oriented Programming Language.
3.Object oriented
Java is object-oriented means software developed in Java are combination of different types of object.
4.Platform Independent
A Java code will run on any JVM (Java Virtual Machine). Literally you can run same Java code on
Windows JVM, Linux JVM, Mac JVM or any other JVM practically and get same result every time
5.Architecturally Neutral
A Java code is not dependent upon Processor Architecture. A Java Application compiled on 64 bit
architecture of any platform will run on 32 bit (or any other architecture) system without any issue.
6.Multithreaded
A thread in Java refers to an independent program. Java supports multithread which means Java is
capable of running many tasks simultaneously, sharing the same memory.
7.Dynamic
Java is a Dynamic programming language which means it executes many programming behavior at
Runtime and don’t need to be passed at compile time as in the case of static programming.
8.Distributed
Java Supports distributed System which means we can access files over Internet just by calling the
methods.
9.Portable
A Java program when compiled produce bytecodes. Bytecodes are magic. These bytecodes can be
transferred via network and can be executed by any JVM, hence came the concept of ‘Write once, Run
Anywhere(WORA)’.
10.Robust
Java is a robust programming Language which means it can cope with error while the program is
executing as well as keep operating with abnormalities to certain extent. Automatic Garbage collection,
strong memory management, exception handling and type checking further adds to the list.
11.Interpreted
Java is a compiled programming Language which compiles the Java program into Java byte codes. This
JVM is then interpreted to run the program.
12.Security
Unlike other programming Language where Program interacts with OS using User runtime environment
of OS, Java provides an extra layer of security by putting JVM between Program and OS.
13.Simple Syntax
Java is an improved c++ which ensures friendly syntax but with removed unwanted features and
inclusion of Automatic Garbage collection.
Java is a High Level Programming Language the syntax of which is human readable. Java lets
programmer to concentrate on what to achieve and not how to achieve. The JVM converts a Java
Program to Machine understandable language.
15.High Performance
Java make use of Just-In-Time compiler for high performance. Just-In-Time compiler is a computer
program that turns Java byte codes into instructions that can directly be sent to compilers.
1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float
and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.
DataType
Integers Floating
• In Java language, primitive data types are the building blocks of data manipulation. These are
1.1 Booleans
A boolean data type is declared with the boolean keyword and can only take the values true or false:
Example :
boolean a= true;
boolean b= false;
System.out.println(a); // Outputs true
System.out.println(b); // Outputs false
Boolean values are mostly used for conditional testing, which you will learn more about in a later
chapter.
1.2 Numbers
• Integer types stores whole numbers, positive or negative (such as 123 or -456), without
decimals. Valid types are byte, short, int and long. Which type you should use, depends on the
numeric value.
• Floating point types represents numbers with a fractional part, containing one or more
decimals. There are two types: float and double.
( I )Integer Types
1.Byte
The byte data type can store whole numbers from -128 to 127. This can be used instead of int or other
integer types to save memory when you are certain that the value will be within -128 and 127:
Example: byte a = 100;
2.Short
The short data type can store whole numbers from -32768 to 32767:
Example : short a = 5000;
3.Int
The int data type can store whole numbers from -2147483648 to 2147483647.In general, and in our
tutorial, the int data type is the preferred data type when we create variables with a numeric value.
int a= 100000;
4.Long
The long data type can store whole numbers from -9223372036854775808 to 9223372036854775807.
This is used when int is not large enough to store the value. Note that you should end the value with an
"L":
You should use a floating point type whenever you need a number with a decimal, such as 9.99 or
3.14515.
1.Float
The float data type can store fractional numbers from 3.4e−038 to 3.4e+038. Note that you should end
the value with an "f":
Eg:float a= 5.75f;
2.Double
The double data type can store fractional numbers from 1.7e−308 to 1.7e+038. Note that you should
end the value with a "d":
Eg:double a= 19.99d;
1.3 Characters
1.char
The char data type is used to store a single character. The character must be surrounded by single
quotes, like 'A' or 'c':
char a = 'B';
2.Strings
The String data type is used to store a sequence of characters (text). String values must be surrounded
by double quotes:
Example
String greeting = "Hello World";
Non-primitive data types are called reference types because they refer to objects.
The main difference between primitive and non-primitive data types are:
• Primitive types are predefined (already defined) in Java. Non-primitive types are created by the
programmer and is not defined by Java (except for String).
• Non-primitive types can be used to call methods to perform certain operations, while primitive
types cannot.
• A primitive type has always a value, while non-primitve types can be null.
• A primitive type starts with a lowercase letter, while non-primitive types starts with an
uppercase letter.
• The size of a primitive type depends on the data type, while non-primitive types have all the
same size.
Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc. You will learn more about
these in a later chapter.
1.Widening Casting
Widening casting is done automatically when passing a smaller size type to a larger size type:
int a = 9;
double b = a; // Automatic casting: int to double
System.out.println(a); // Outputs 9
System.out.println(b); // Outputs 9.0
2.Narrowing Casting
Narrowing casting must be done manually by placing the type in parantheses in front of the value:
double a = 9.78;
int b= (int) a; // Manual casting: double to int
Java Operators
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into
the following groups −
1. Arithmetic Operators
2. Relational Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Misc Operators
Show Examples
Checks if the values of two operands are equal or not, if yes (A == B) is not
== (equal to)
then condition becomes true. true.
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13; now in
binary format they will be as follows −
a = 0011 1100
b = 0000 1101
-----------------
~a = 1100 0011
Assume Boolean variables A holds true and variable B holds false, then −
Show Examples
Show Examples
6.Miscellaneous Operators
There are few other operators supported by Java Language.
If the object referred by the variable on the left side of the operator passes the IS-A check for the
class/interface type on the right side, then the result will be true. Following is an example −
Java Syntax
In the previous chapter, we created a Java file called MyClass.java, and we used the following code to
print "Hello World" to the screen:
MyClass.java
{
public static void main(String[] args)
{
System.out.println("Hello World");
}
}
Control Structures
I .Conditional Statements
1.1 The if Statement
Use the if statement to specify a block of Java code to be executed if a condition is true.
Syntax:
if (condition)
{
// block of code to be executed if the condition is true
}
Example:
if (20 > 18)
{
System.out.println("20 is greater than 18");
}
1.2 If else Statement
Use the else statement to specify a block of code to be executed if the condition is false inside the if
block.
Syntax:
if (condition)
{
// block of code to be executed if the condition is true
}
else
{
// block of code to be executed if the condition is false
}
Example :
int time = 20;
if (time < 18)
{
System.out.println("Good day.");
}
else
{
System.out.println("Good evening.");
}
Use the else if statement to specify a new condition if the first condition is false.
Syntax
if (condition1)
{
// block of code to be executed if condition1 is true
} else if (condition2)
{
// block of code to be executed if the condition1 is false and condition2 is true
}
else
{
// block of code to be executed if the condition1 is false and condition2 is false
}
Example :
int time = 22;
if (time < 10)
{
System.out.println("Good morning.");
} else if (time < 20)
{
System.out.println("Good day.");
}
Else
{
System.out.println("Good evening.");
}
// Outputs "Good evening."
1.4 Switch Statements
Use the switch statement to select one of many code blocks to be executed.
switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
The example below uses the weekday number to calculate the weekday name:
int day = 4;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
}
// Outputs "Thursday" (day 4)
Java Loops
Loops can execute a block of code as long as a specified condition is reached.
The while loop loops through a block of code as long as a specified condition is true:
Syntax
while (condition)
{
// code block to be executed
}
In the example below, the code in the loop will run, over and over again, as long as a variable (i) is less
than 5:
Example
int i = 0;
while (i < 5)
{
System.out.println(i);
i++;
}
The do/while loop is a variant of the while loop. This loop will execute the code block once, before
checking if the condition is true, then it will repeat the loop as long as the condition is true.
Syntax
do
{
// code block to be executed
}
while (condition);
Example
int i = 0;
do
{
System.out.println(i);
i++;
}
while (i < 5);
When you know exactly how many times you want to loop through a block of code, use the for loop
instead of a while loop:
Syntax
for (statement 1; statement 2; statement 3)
{
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 3 is executed (every time) after the code block has been executed.
Example
for (int i = 0; i < 5; i++)
{
System.out.println(i);
}
Example explained
Statement 1 sets a variable before the loop starts (int i = 0).
Statement 2 defines the condition for the loop to run (i must be less than 5). If the condition is true, the loop will
start over again, if it is false, the loop will end.
Statement 3 increases a value (i++) each time the code block in the loop has been executed.
4.For-Each Loop
There is also a "for-each" loop, which is used exclusively to loop through elements in an array:
{
// code block to be executed
}
The following example outputs all elements in the cars array, using a "for-each" loop:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars)
{
System.out.println(i);
}
You have already seen the break statement used in an earlier chapter of this tutorial. It was used to
"jump out" of a switch statement.
Example
for (int i = 0; i < 10; i++)
{
if (i == 4)
{
break;
}
System.out.println(i);
}
Java Continue
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues
with the next iteration in the loop.
Example
for (int i = 0; i < 10; i++)
{
if (i == 4) {
continue;
}
System.out.println(i);
}
Java Arrays
• Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value.
• To declare an array, define the variable type with square brackets:
• String[] cars;
• We have now declared a variable that holds an array of strings. To insert values to it, we can use
an array literal - place the values in a comma-separated list, inside curly braces:
Array Length
To find out how many elements an array has, use the length property:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length);
// Outputs 4
You can loop through the array elements with the for loop, and use the lengthproperty to specify how
many times the loop should run.
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++)
{
System.out.println(cars[i]);
}
Multidimensional Arrays
Example
int[][] a= { {1, 2, 3, 4}, {5, 6, 7} };
To access the elements of the a array, specify two indexes: one for the array, and one for the element
inside that array. This example accesses the third element (2) in the second array (1) of a:
Example
int[][] a = { {1, 2, 3, 4}, {5, 6, 7} };
int x = a[1][2];
System.out.println(x); // Outputs 7
Constructor
Constructor in java is a special type of method that is used to initialize the object.Java constructor is
invoked at the time of object creation. It constructs the values i.e. provides data for the object that is
why it is known as constructor.
class_name()
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of
object creation.
class Bike1
{
Bike1()
{
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike1 b=new Bike1();
}
}
Output:
Bike is created
Default constructor provides the default values to the object like 0, null etc. depending on the type.
class Student3
{
int id;
String name;
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display();
}
}
Output:
0 null
0 null
Explanation:In the above class,you are not creating any constructor so compiler provides you a default
constructor.Here 0 and null values are provided by default constructor.
class Student4
{
int id;
String name;
Student4(int i,String n)
{
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);
}
class Student5
{
int id;
String name;
int age;
Student5(int i,String n)
{
id = i;
name = n;
}
Student5(int i,String n,int a)
{
id = i;
name = n;
age=a;
}
void display()
{
System.out.println(id+" "+name+" "+age);
}
public static void main(String args[])
{
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
Output:
111 Karan 0
222 Aryan 25
class Student6
{
int id;
String name;
Student6(int i,String n)
{
id = i;
name = n;
}
Student6(Student6 s)
{
id = s.id;
name =s.name;
}
void display()
{
System.out.println(id+" "+name);
}
Applet in java
An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java
application because it has the entire Java API at its disposal.
There are some important differences between an applet and a standalone Java application, including
the following −
1. init − This method is intended for whatever initialization is needed for your applet. It is called
after the param tags inside the applet tag have been processed.
2. start − This method is automatically called after the browser calls the init method. It is also
called whenever the user returns to the page containing the applet after having gone off to
other pages.
3. stop − This method is automatically called when the user moves off the page on which the
applet sits. It can, therefore, be called repeatedly in the same applet.
4. destroy − This method is only called when the browser shuts down normally. Because applets
are meant to live on an HTML page, you should not normally leave resources behind after a user
leaves the page that contains the applet.
5. paint − Invoked immediately after the start() method, and also any time the applet needs to
repaint itself in the browser. The paint() method is actually inherited from the java.awt.
Example:
Import java.applet.*;
import java.awt.*;
public class myapplet extends Applet
{
public void paint (Graphics g) {
g.drawString ("Hello World", 25, 50);
}
}
Invoking an Applet
An applet may be invoked by embedding directives in an HTML file and viewing the file through an
applet viewer or Java-enabled browser.
The <applet> tag is the basis for embedding an applet in an HTML file. Following is an example that
invokes the "Hello, World" applet −
<html>
</applet>
</html>
Declaration
Nested Classes
In Java, just like methods, variables of a class too can have another class as its member. Writing a class
within another is allowed in Java. The class written within is called the nested class, and the class that
holds the inner class is called the outer class.
Following is the syntax to write a nested class. Here, the class Outer_Demo is the outer class and the
class Inner_Demo is the nested class.
class Outer_Demo
{
class Nested_Demo
{
}
}
Inner Classes
• Inner Classes (Non-static Nested Classes)
• Inner classes are a security mechanism in Java.
• We know a class cannot be associated with the access modifier private, but if we have the class
as a member of other class, then the inner class can be made private. And this is also used to
access the private members of a class.
• Inner classes are of three types depending on how and where you define them. They are −
• Creating an inner class is quite simple. You just need to write a class within a class. Unlike a
class, an inner class can be private and once you declare an inner class private, it cannot be
accessed from an object outside the class.
• Following is the program to create an inner class and access it. In the given example, we make
the inner class private and access the class through a method.
Example
class Outer_Demo
{
int num;
// inner class
private class Inner_Demo
{
public void print()
{
System.out.println("This is an inner class");
}
}
// Accessing he inner class from the method within
void display_Inner()
{
Inner_Demo inner = new Inner_Demo();
inner.print();
}
}
Output
MODULE 2
Inheritance
Inheritance can be defined as the process where one class acquires the properties (methods and fields)
of another. With the use of inheritance the information is made manageable in a hierarchical order.
The class which inherits the properties of other is known as subclass (derived class, child class) and the
class whose properties are inherited is known as superclass (base class, parent class).
extends Keyword
extends is the keyword used to inherit the properties of a class. Following is the syntax of extends
keyword
Syntax
class A
{
.....
.....
}
class B extends A
{
.....
.....
}
Following is an example demonstrating Java inheritance. In this example, you can observe two classes
namely Calculation and My_Calculation.
Using extends keyword, the My_Calculation inherits the methods addition() and Subtraction() of
Calculation class.
class Calculation
{
int z;
public void addition(int x, int y)
{
z = x + y;
System.out.println("The sum of the given numbers:"+z);
}
public void Subtraction(int x, int y)
{
z = x - y;
System.out.println("The difference between the given numbers:"+z);
}
Super Keyword
• The super keyword is similar to this keyword. Following are the scenarios where the super
keyword is used.
• It is used to differentiate the members of superclass from the members of subclass, if they have
same names.
• It is used to invoke the superclass constructor from subclass.
If a class is inheriting the properties of another class. And if the members of the superclass have the
names same as the sub class, to differentiate these variables we use super keyword as shown below.
super.variable
super.method();
Types of Inheritance
Interface in Java
• An interface in java is a blueprint of a class. It has static constants and abstract methods.
• The interface in java is a mechanism to achieve abstraction. There can be only abstract methods
in the java interface not method body. It is used to achieve abstraction and multiple inheritance
in Java.
• Java Interface also represents IS-A relationship.
• It cannot be instantiated just like abstract class.
Syntax
Interface interfacename
{
Interface methods();
}
Example
interface printable
{
void print();
}
class A6 implements printable
{
public void print()
{
System.out.println("Hello");
}
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as
multiple inheritance.
interface Printable
{
void print();
}
interface Showable
{
void show();
}
class A7 implements Printable,Showable
{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome")
}
As we have explained in the inheritance chapter, multiple inheritance is not supported in case of class
because of ambiguity. But it is supported in case of interface because there is no ambiguity as
implementation is provided by the implementation class. For example:
Method- Overriding
• If a class inherits a method from its superclass, then there is a chance to override the method
provided that it is not marked final.
• The benefit of overriding is: ability to define a behavior that's specific to the subclass type, which
means a subclass can implement a parent class method based on its requirement.
• In object-oriented terms, overriding means to override the functionality of an existing method.
Example
class Animal
{
public void move()
{
System.out.println("Animals can move");
}
}
class Dog extends Animal
{
public void move() {
System.out.println("Dogs can walk and run");
}
}
Output
Animals can move
Dogs can walk and run
Method Overloading
Method overloading is the way of implementing static/compile time polymorphism in java. Method
overloading means more than one methods in a class with same name but different parameters.
Parameters can be differing in types, numbers or order.
• In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.
• In this example, we are creating static methods so that we don't need to create instance for
calling methods.
class Adder
{
static int add(int a,int b)
{
return a+b;
}
static int add(int a,int b,int c)
{
return a+b+c;
}
}
class TestOverloading1
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}
Output:
22
33
In this example, we have created two methods that differs in data type. The first add method receives
two integer arguments and second add method receives two double arguments.
class Adder
{
static int add(int a, int b)
{
return a+b;
}
Abstraction in Java
• Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
• Another way, it shows only essential things to the user and hides the internal details, for
example, sending SMS where you type the text and send the message. You don't know the
internal processing about the message delivery.
• Abstraction lets you focus on what the object does instead of how it does it.
1. Abstract class
2. Interface
A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract
methods. It needs to be extended and its method implemented. It cannot be instantiated.
In this example, Bike is an abstract class that contains only one abstract method run. Its implementation
is provided by the Honda class.
Interface in Java
• An interface in java is a blueprint of a class. It has static constants and abstract methods.
• The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods
in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance
in Java.
• In other words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body.
• Java Interface also represents the IS-A relationship.
• It cannot be instantiated just like the abstract class.
There are mainly three reasons to use interface. They are given below.
An interface is declared by using the interface keyword. It provides total abstraction; means all the
methods in an interface are declared with the empty body, and all the fields are public, static and final
by default. A class that implements an interface must implement all the methods declared in the
interface.
Syntax:
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}
In this example, the Printable interface has only one method, and its implementation is provided in the
A6 class.
interface printable
{
void print();
}
class A6 implements printable
{
public void print()
{
System.out.println("Hello");
}
Java Package
• A java package is a group of similar types of classes, interfaces and sub-packages.
• Package in java can be categorized in two form, built-in package and user-defined package.
• There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
• Here, we will have the detailed learning of creating and using user-defined packages.
//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
________________________________________
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output:Hello
MODULE 3
• The core advantage of exception handling is to maintain the normal flow of the application. An
exception normally disrupts the normal flow of the application that is why we use exception
handling.
Keyword Description
try The "try" keyword is used to specify a block where we should place exception code. The
try block must be followed by either catch or finally. It means, we can't use try block
alone.
catch The "catch" block is used to handle the exception. It must be preceded by try block which
means we can't use catch block alone. It can be followed by finally block later.
finally The "finally" block is used to execute the important code of the program. It is executed
whether an exception is handled or not.
throws The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It
specifies that there may occur an exception in the method. It is always used with method
signature.
Let's see an example of Java Exception Handling where we using a try-catch statement to handle the
exception.
public class A
{
public static void main(String args[])
{
Try
{
//code that may raise exception
int data=100/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
//rest code of the program
System.out.println("rest of the code...");
}
}
There are mainly two types of exceptions: checked and unchecked. Here, an error is considered as the
unchecked exception. According to Oracle, there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
1) Checked Exception
The classes which directly inherit Throwable class except RuntimeException and Error are known as
checked exceptions e.g. IOException, SQLException etc. Checked exceptions are checked at compile-
time.
2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked
exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
A try block can be followed by one or more catch blocks. Each catch block must contain a different
exception handler. So, if you have to perform different tasks at the occurrence of different exceptions,
use java multi-catch block.
o At a time only one exception occurs and at a time only one catch block is executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
try
{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Java finally block
• Java finally block is a block that is used to execute important code such as closing connection,
stream etc.
• Java finally block is always executed whether exception is handled or not.
• Java finally block follows try or catch block.
class TestFinallyBlock
{
public static void main(String args[])
{
try
{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output:
finally block is always executed
rest of the code...
Thread in java
As shown in the above figure, thread is executed inside the process. There is context-switching between
the threads. There can be multiple processes inside the OS and one process can have multiple threads.
A thread can be in one of the five states. According to sun, there is only 4 states in thread life cycle in
javanew, runnable, non-runnable and terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
1) New
The thread is in new state if you create an instance of Thread class but before the invocation of
start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not
selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
1. Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.Thread
class extends Object class and implements Runnable interface.
o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)
2.Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread. Runnable interface have only one method named run().
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following tasks:
o A new thread starts(with new callstack).
o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.
Next Topi
MODULE IV
API Packages
Java APl(Application Program Interface) provides a large numbers of classes grouped into different
packages according to functionality Following figure shows the system packages that are frequently
used in the programs.
java.lang Language support classes. They include classes for primitive types, string, math functions,
thread and exceptions.
java.util Language utility classes such as vectors, hash tables, random numbers, data, etc.
java.io Input/output support classes. They provide facilities for the input and output of data.
java.net Classes for networking. They include classes for communicating with local computers as
well as with internet servers.
java.awt Set of classes for implementing graphical user interface. They include classes for windows,
buttons, lists, menus and so on.
Java I/O
Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of stream to make I/O operation fast. The java.io package contains all the classes
required for input and output operations.
Stream
A stream is a sequence of data.In Java a stream is composed of bytes. It's called a stream because it is
like a stream of water that continues to flow.
In java, 3 streams are created for us automatically. All these streams are attached with console.
OutputStream vs InputStream
OutputStream
Java application uses an output stream to write data to a destination, it may be a file, an array,
peripheral device or socket.
InputStream
Java application uses an input stream to read data from a source, it may be a file, an array, peripheral
device or socket.
OutputStream class
OutputStream class is an abstract class. It is the super class of all classes representing an output stream
of bytes. An output stream accepts output bytes and sends them to some sink.
Method Description
1) public void write(int)throws IOException is used to write a byte to the current output stream.
2) public void write(byte[])throws is used to write an array of byte to the current output
IOException stream.
3) public void flush()throws IOException flushes the current output stream.
4) public void close()throws IOException is used to close the current output stream.
OutputStream Hierarchy
InputStream class
InputStream class is an abstract class. It is the super class of all classes representing an input stream of
bytes.
Java AWT
Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications in java.
Java AWT components are platform-dependent i.e. components are displayed according to the view of
operating system. AWT is heavyweight i.e. its components are using the resources of OS.
The java.awt package provides classes for AWT api such as TextField, Label, TextArea, RadioButton,
CheckBox, Choice, List etc.
Container
The Container is a component in AWT that can contain another components like buttons, textfields,
labels etc. The classes that extends Container class are known as container such as Frame, Dialog and
Panel.
Window
The window is the container that have no borders and menu bars. You must use frame, dialog or
another window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other components
like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other components
like button, textfield etc.
AWT Example
Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing Button
component on the Frame.
import java.awt.*;
First()
Output
Java Swing
Java Swing tutorial is used to create window-based applications. It is built on the top of AWT (Abstract
Windowing Toolkit) API and entirely written in java.
The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu, JColorChooser etc.
There are many differences between java awt and swing that are given below.
3) AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.
5) AWT doesn't follows MVC(Model View Controller) where Swing follows MVC.
model represents data, view represents presentation and
Types of Event
• Foreground Events - Those events which require the direct interaction of user.They are
generated as consequences of a person interacting with the graphical components in Graphical
User Interface. For example, clicking on a button, moving the mouse, entering a character
through keyboard,selecting an item from list, scrolling the page etc.
• Background Events - Those events that require the interaction of end user are known as
background events. Operating system interrupts, hardware or software failure, timer expires, an
operation completion are the example of background events.
Event Handling is the mechanism that controls the event and decides what should happen if an event
occurs. This mechanism have the code which is known as event handler that is executed when an event
occurs. Java Uses the Delegation Event Model to handle the events. This model defines the standard
mechanism to generate and handle the events.Let's have a brief introduction to this model.
The Delegation Event Model has the following key participants namely:
• Source - The source is an object on which event occurs. Source is responsible for providing
information of the occurred event to it's handler. Java provide as with classes for source object.
• Listener - It is also known as event handler.Listener is responsible for generating response to an
event. From java implementation point of view the listener is also an object. Listener waits until
it receives an event. Once the event is received , the listener process the event an then returns.
The benefit of this approach is that the user interface logic is completely separated from the logic that
generates the event. The user interface element is able to delegate the processing of an event to the
separate piece of code. In this model ,Listener needs to be registered with the source object so that the
listener can receive the event notification. This is an efficient way of handling the event because the
event notifications are sent only to those listener that want to receive them.
• Now the object of concerned event class is created automatically and information about the
source and the event get populated with in same object.
• Event object is forwarded to the method of registered listener class.
• the method is now get executed and returns.
Java JDBC
Java JDBC is a java API to connect and execute query with the database. JDBC API uses jdbc drivers to
connect with the database.
Before JDBC, ODBC API was the database API to connect and execute query with the database. But,
ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and unsecured).
That is why Java has defined its own API (JDBC API) that uses JDBC drivers (written in Java language).
• DriverManager: This class manages a list of database drivers. Matches connection requests from
the java application with the proper database driver using communication sub protocol. The first
driver that recognizes a certain subprotocol under JDBC will be used to establish a database
Connection.
• Driver: This interface handles the communications with the database server. You will interact
directly with Driver objects very rarely. Instead, you use DriverManager objects, which manages
objects of this type. It also abstracts the details associated with working with Driver objects.
• Connection: This interface with all methods for contacting a database. The connection object
represents communication context, i.e., all communication with database is through connection
object only.
• Statement: You use objects created from this interface to submit the SQL statements to the
database. Some derived interfaces accept parameters in addition to executing stored
procedures.
• ResultSet: These objects hold data retrieved from a database after you execute an SQL query
using Statement objects. It acts as an iterator to allow you to move through its data.
• SQLException: This class handles any errors that occur in a database application.