SD Java Notes
SD Java Notes
1|Page
Lecture 1
Introduction to Java
HISTORY OF JAVA
They wanted the language to be small and use efficient code since these devices do not
have powerful CPUs. They also wanted the language to be hardware independent since
different manufacturers would use different CPUs. The project was code-named
Green.
Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
After that, it was called Oak and was developed as a part of the Green project.
However, they soon discovered that there was already a programming language called
Oak, so they changed the name to Java
Sun Microsystems released the first public implementation as Java 1.0 in 1995.
James Gosling
2|Page
EDITION OF JAVA
The Java Development Kit (JDK) is an Oracle Corporation product aimed at Java developers. Since
the introduction of Java, it has been by far the most widely used Java Software Development Kit
(SDK).
The JDK includes the Java Runtime Environment, the Java compiler and the Java APIs. It's easy for
both new and experienced programmers to get started.
A Java virtual machine (JVM) is a virtual machine that can execute Java byte code. It is the code
execution component of the Java software platform.
Java Runtime Environment, is also referred to as the Java Runtime, Runtime Environment Java
Runtime Environment contains JVM, class libraries, and other supporting files. JRE is targeted for
execution of Java files. Java Runtime Environment (JRE) The Java Runtime Environment (JRE)
provides the libraries, the Java Virtual Machine, and other components to run applets and
applications written in the Java programming language
You have to download the JDK from internet and install the software in your machine. For your
practice jdk1.5 or higher version is advisable to install.
You can write the program any one of the text editor say example Notepad.
Now a day’s many text editors are used like eclipse and net beans to run the program.
3|Page
STEPS TO EXECUTE THE JAVA PROGRAM
Lecture 2
BASIC CONCEPTS OF OOPS
The following are the basic concepts applied in object-oriented programming language.
1) Object :
Object is the basic unit of object-oriented programming. Objects are identified by its unique name. An
object represents a particular instance of a class. There can be more than one instance of an object.
Each instance of an object can hold its own relevant data.
An Object is a collection of data members and associated member functions also known as methods.
For example whenever a class name is created according to the class an object should be created
without creating object can’t able to use class.
The class of Dog defines all possible dogs by listing the characteristics and behaviors they can have;
the object Lassie is one particular dog, with particular versions of the characteristics. A Dog has fur;
Lassie has brown-and-white fur.
2) Class:
Classes are data types based on which objects are created. Objects with similar properties and
methods are grouped together to form a Class. Thus a Class represents a set of individual objects.
Characteristics of an object are represented in a class as Properties. The actions that can be
performed by objects become functions of the class and is referred to as Methods.
For example consider we have a Class of Cars under which Santro Xing, Alto and WaganR
represents individual Objects. In this context each Car Object will have its own, Model, Year of
Manufacture, Colour, Top Speed, Engine Power etc., which form Properties of the Car class and the
associated actions i.e., object functions like Start, Move, Stop form the Methods of Car Class.No
memory is allocated when a class is created. Memory is allocated only when an object is created, i.e.,
when an instance of a class is created.
4|Page
3) Data abstraction & Encapsulation :
The wrapping up of data and its functions into a single unit is called Encapsulation.
When using Data Encapsulation, data is not accessed directly, it is only accessible through the
functions present inside the class.
Data Abstraction increases the power of programming language by creating user defined data
types. Data Abstraction also represents the needed information in the program without presenting the
details.
Abstraction refers to the act of representing essential features without including the background
details or explanation between them.
For example, a class Car would be made up of an Engine, Gearbox, Steering objects, and many
more components. To build the Car class, one does not need to know how the different components
work internally, but only how to interface with them, i.e., send messages to them, receive messages
from them, and perhaps make the different objects composing the class interact with each other.
4) Inheritance:
Inheritance is the process of forming a new class from an existing class or base class.
The base class is also known as parent class or super class, the new class that is formed is called
derived class.
Derived class is also known as a child class or sub class. Inheritance helps in reducing the overall
code size of the program, which is an important concept in object-oriented programming.
5) Polymorphism:
Polymorphism allows routines to use variables of different types at different times. An operator or
function can be given different meanings or functions. Polymorphism refers to a single function or
multi-functioning operator performing in different ways.
Poly a Greek term ability to take more than one form. Overloading is one type of Polymorphism. It
allows an object to have different meanings, depending on its context. When an exiting operator or
function begins to operate on new data type, or class, it is understood to be overloaded.
6. Dynamic binding: Binding means linking. It involves linking of function definition to a function call.
1. If linking of function call to function definition, i.e., a place where control has to be transferred is
done at compile time, it is known as static binding.
5|Page
2. When linking is delayed till run time or done during the execution of the program then this type of
linking is known as dynamic binding. Which function will be called in response to a function call is find
out when program executes.
. Message passing: In C++, objects communicate each other by passing messages to each other. A
message contains the name of the member function and arguments to pass. The message passing is
shown below:
Message passing here means object calling the method and passing parameters. Message passing
is nothing but calling the method of the class and sending parameters. The method in turn executes
in response to a message.
Features of java
Object oriented - Java provides the basic object technology of C++ with some enhancements
and some deletions.
Architecture neutral/plat form independent - Java source code is compiled into
architecture-independent object code. The object code is interpreted by a Java Virtual Machine
(JVM) on the target architecture.
Portable - Java implements additional portability standards. For example, ints are always 32-
bit, 2's-complemented integers. User interfaces are built through an abstract window system
that is readily implemented in Solaris and other operating environments.
Distributed - Java contains extensive TCP/IP networking facilities. Library routines support
protocols such as HyperText Transfer Protocol (HTTP) and file transfer protocol (FTP).
Robust - Both the Java compiler and the Java interpreter provide extensive error checking.
Java manages all dynamic memory, checks array bounds, and other exceptions.
Secure - Features of C and C++ that often result in illegal memory accesses are not in the
Java language. The interpreter also applies several tests to the compiled code to check for
illegal code. After these tests, the compiled code causes no operand stack over- or underflows,
performs no illegal data conversions, performs only legal object field accesses, and all opcode
parameter types are verified as legal.
Multithreaded - Multithreading is built into the Java language. It can improve interactive
performance by allowing operations, such as loading an image, to be performed while
continuing to process user actions.
6|Page
Dynamic - Java does not link invoked modules until runtime.
Simple - Java is similar to C++, but with most of the more complex features of C and C++
removed
Lecture 3
Data type
7|Page
ype Casting
Assigning a value of one type to a variable of another type is known as Type Casting.
Example :
int x = 10;
byte y = (byte)x;
Widening Casting(Implicit)
int i = 'A';
Explicit down-casting: a manual conversion is required if there is a potential for a loss of precision,
using the notation: (lowerPrecType) higherPrecValue
8|Page
int i = (int) 123.456;
Declaring Arrays
An array is a simple data structure to hold a series of data elements of the same type.
Declare an array variable in one of two ways:
o With [] after the variable type: int[] values;
o With [] after the variable name: int values[];
Arrays can be single- or multi-dimensional.
o A two dimensional array could be declared with: double values[][];
Array elements are integer indexed.
o Use arrayName.length to get the array length.
o Elements are indexed from 0 to arrayName.length - 1
o Access individual elements with arrayName[index]
Operator
Arithmetic Operators
Relational Operators
Bitwise Operators
Assignment Operators
= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
Other Operators
Operator Precedence
1. [], (), .
2. ++, --, ~, !, (type), new, -
3. *, /, %
10 | P a g e
Lecture 4
In this page, we will learn how to write the simple program of java. We can write a simple hello java
program easily after installing the JDK.
To create a simple java program, you need to create a class that contains the main method. Let's
understand the requirement first.
1. class Simple{
2. public static void main(String args[]){
3. System.out.println("Hello Java");
4. }
5. }
Test it Now
11 | P a g e
To compile: javac Simple.java
To execute: java Simple
Output:Hello Java
Compilation Flow:
When we compile Java program using javac tool, java compiler converts the source code into byte code.
To write the simple program, you need to open notepad by start menu -> All Programs -> Accessories
-> notepad and write a simple program as displayed below:
As displayed in the above diagram, write the simple program of java in notepad and saved it as
Simple.java. To compile and run this program, you need to open the command prompt by start menu
-> All Programs -> Accessories -> command prompt.
To compile and run the above program, go to your current directory first; my current directory is c:\
new. Write here:
12 | P a g e
To compile: javac Simple.java
To execute: java Simple
1) By changing the sequence of the modifiers, method prototype is not changed in Java.
2) The subscript notation in Java array can be used after type, before the variable or after the
variable.
3) You can provide var-args support to the main method by passing 3 ellipses (dots)
Let's see the simple code of using var-args in the main method. We will learn about var-args later in Java
New Features chapter.
1. class A{
2. static public void main(String... args){
3. System.out.println("hello java4");
4. }
5. };
13 | P a g e
4. public static void main(String... args)
5. static public void main(String[] args)
6. public static final void main(String[] args)
7. final public static void main(String[] args)
8. final strictfp public static void main(String[] args)
Example
The following program displays all of the command-line arguments that it is called with -
14 | P a g e
Output
This will produce the following result -
args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100
Selection statements
The if Statement:
Syntax:
If (Boolean expression)
{
//Statements will execute if the Boolean expression is true
}
Example:
public class Test {public static void main(String args[]){
int x = 10;
if( x < 20 ){ System.out.print ("This is if statement");}}} o/p: This is if statement
Syntax:
If (Boolean expression){
//Executes when the Boolean expression is true
} else {
//Executes when the Boolean expression is false
}
Example:
public class Test {public static void main(String args[]){int x = 30;
if( x < 20 ){
System.out.print ("This is if statement"); }else{System.out.print("This is else statement"); }}}
o/p :This is else statement
15 | P a g e
The if...else if...else Statement:.Syntax:
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3){
//Executes when the Boolean expression 3 is true
}else {
//Executes when the none of the above condition is true.
}
Example:
public class Test {
public static void main(String args[]){
int x = 30;
if( x == 10 ){System.out.print("Value of X is 10");
}else if( x == 20 ){
System.out.print("Value of X is 20");
}else if( x == 30 ){
System.out.print("Value of X is 30");
}else{
System.out.print("This is else statement"); } }} o/p: Value of X is 30
Example:
public class Test {
public static void main(String args[]){
int x = 30;
int y = 10;
if( x == 30 ){
if( y == 10 ){
System.out.print ("X = 30 and Y = 10");
} }}}
O/p: X = 30 and Y = 10
16 | P a g e
The switch Statement:A switch statement allows a variable to be tested for equality against a
list of values. Each value is called a case, and the variable being switched on is checked for
each case.
Syntax:
Switch (expression){
case value:
//Statements
break; //optional
case value :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}
The variable used in a switch statement can only be a byte, short, int, or char.
You can have any number of case statements within a switch. Each case is followed by the
value to be compared to and a colon.
The value for a case must be the same data type as the variable in the switch and it must be a
constant or a literal.
When the variable being switched on is equal to a case, the statements following that case will
execute until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow of control jumps to the
next line following the switch statement.
Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true. No
break is needed in the default case.
Example:
public class Test {
public static void main(String args[]){
char grade = 'C';
switch(grade)
{
case 'A' :
System.out.println("Excellent!");
break;
17 | P a g e
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
Well done
Your grade is a C
Loop in java
There may be a situation when we need to execute a block of code several number of times, and is
often referred to as a loop.
Java has very flexible three looping mechanisms. You can use one of the following three loops:
while Loop
do...while Loop
for Loop
As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.
A while loop is a control structure that allows you to repeat a task a certain number of times.
Syntax:
while(Boolean expression)
{ //Statements }
When executing, if the boolean_expression result is true, then the actions inside the loop will be
executed. This will continue as long as the expression result is true.
Here, key point of the while loop is that the loop might not ever run. When the expression is tested
and the result is false, the loop body will be skipped and the first statement after the while loop will be
executed.
18 | P a g e
Example:
public class Test {
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at
least one time.
Syntax:
do
{
//Statements
}while(Boolean_expression);
Notice that the Boolean expression appears at the end of the loop, so the statements in the loop
execute once before the Boolean is tested.
If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the
loop execute again. This process repeats until the Boolean expression is false.
Example:
public class Test {
public static void main(String args[]){
int x = 10;
do{
System.out.print( x );
x++;
}while( x < 20 ); }}
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
A for loop is useful when you know how many times a task is to be repeated.
Syntax:
For (initialization; Boolean_expression; update)
19 | P a g e
{
//Statements
}
The initialization step is executed first, and only once. Next, the Boolean expression is
evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does
not execute and flow of control jumps to the next statement past the for loop.
After the body of the for loop executes, the flow of control jumps back up to the update
statement. This statement allows you to update any loop control variables. The Boolean
expression is now evaluated again. If it is true, the loop executes and the process repeats itself
(body of loop, then update step, then Boolean expression). After the Boolean expression is
false, the for loop terminates.
Example:
public class Test {
public static void main(String args[]) {
for(int x = 10; x < 20; x = x+1) {
System.out.print( x );}}}
As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.
Syntax:
For (declaration : expression)
{
//Statements
}
Declaration: The newly declared block variable, which is of a type compatible with the
elements of the array you are accessing. The variable will be available within the for block and
its value would be the same as the current array element.
Expression: This evaluates to the array you need to loop through. The expression can be an
array variable or method call that returns an array.
Java provides a data structure, the array, which stores a fixed-size sequential collection of elements
of the same type. An array is used to store a collection of data, but it is often more useful to think of
an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare
one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to
represent individual variables.
This tutorial introduces how to declare array variables, create arrays, and process arrays using
indexed variables.
20 | P a g e
Declaring Array Variables
To use an array in a program, you must declare a variable to reference the array, and you must
specify the type of array the variable can reference. Here is the syntax for declaring an array variable
−
Syntax
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way.
Note − The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[] comes
from the C/C++ language and was adopted in Java to accommodate C/C++ programmers.
Example
Creating Arrays
You can create an array by using the new operator with the following syntax −
Syntax
arrayRefVar = new dataType[arraySize];
The above statement does two things −
It creates an array using new dataType[arraySize].
It assigns the reference of the newly created array to the variable arrayRefVar.
Declaring an array variable, creating an array, and assigning the reference of the array to the
variable can be combined in one statement, as shown below −
dataType[] arrayRefVar = new dataType[arraySize];
Alternatively you can create arrays as follows −
dataType[] arrayRefVar = {value0, value1, ..., valuek};
The array elements are accessed through the index. Array indices are 0-based; that is, they start
from 0 to arrayRefVar.length-1.
Example
Following statement declares an array variable, myList, creates an array of 10 elements of double
type and assigns its reference to myList −
double[] myList = new double[10];
21 | P a g e
Following picture represents array myList. Here, myList holds ten double values and the indices are
from 0 to 9.
Processing Arrays
When processing array elements, we often use either for loop or foreach loop because all of the
elements in an array are of the same type and the size of the array is known.
Example
Here is a complete example showing how to create, initialize, and process arrays −
public class TestArray {
22 | P a g e
This will produce the following result −
Output
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
Example
The following code displays all the elements in the array myList −
public class TestArray {
Output
1.9
2.9
3.4
3.5
Example:
public class Test {
for(int x : numbers ){
System.out.print( x );
23 | P a g e
System.out.print(",");
}
System.out.print("\n");
String [] names ={"James", "Larry", "Tom", "Lacy"};
for( String name : names ) {
System.out.print( name );
System.out.print(",");}}}
10,20,30,40,50,
James,Larry,Tom,Lacy,
The break keyword is used to stop the entire loop. The break keyword must be used inside any loop
or a switch statement.
The break keyword will stop the execution of the innermost loop and start executing the next line of
code after the block.
Syntax:
break;
Example:
public class Test {
for(int x : numbers ) {
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}
10
20The continue Keyword:
The continue keyword can be used in any of the loop control structures. It causes the loop to
immediately jump to the next iteration of the loop.
24 | P a g e
In a for loop, the continue keyword causes flow of control to immediately jump to the update
statement.
In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression.
Syntax:
continue;
Example:
public class Test {
for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print(x);
System.out.print ("\n"); }}}
10 20 40 50
25 | P a g e
Lecture 5
Declaring Class
The class body (the area between the braces) contains all the code like Field, constructor,
and method declarations
1. Modifiers such as public, private, and a number of others that you will encounter later.
2. The class name, with the initial letter capitalized by convention.
3. The name of the class's parent (superclass), if any, preceded by the keyword extends. A
class can only extend (subclass) one parent.
4. A comma-separated list of interfaces implemented by the class, if any, preceded by the
keyword implements. A class can implement more than one interface.
5. The class body, surrounded by braces, {}.
Creating Objects
To create a Cs class object, you use the new operator, which returns a reference to a new object. A
reference is a kind of pointer to an object, which you can use to invoke methods on the object. In
other words, to send an object a message (by invoking a method on the object), you have to have a
reference to that object. To keep track of references, you can declare variables in which you can
store the references.
Creating Method:
a, b: formal parameters
26 | P a g e
int a, int b: list of parameters
Method definition consists of a method header and a method body. The same is shown below:
Object.methodname();
If a class have multiple methods by same name but different parameters, it is known as Method
Overloading.
Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the
method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for you as
well as other programmers to understand the behaviour of the method because its name differs. So, we perform
method overloading to figure out the program quickly.
here are two ways to overload the method in java
1. By changing number of arguments
In java, Methood Overloading is not possible by changing the return type of the method.
class Calculation{
27 | P a g e
obj.sum(10,10,10); obj.sum(20,20);
} }
1. class Calculation{
2. void sum(int a,int b){System.out.println(a+b);}
3. void sum(double a,double b){System.out.println(a+b);}
4. public static void main(String args[]){
5. Calculation obj=new Calculation();
6. obj.sum(10.5,10.5);
7. obj.sum(20,20);
8.
9. }
10. }
11. Output:21.0
12. 40
Que) Why Method Overloaing is not possible by changing the return type of method?
In java, method overloading is not possible by changing the return type of the method because there
may occur ambiguity. Let's see how ambiguity may occur:because there was problem:
1. class Calculation{
2. int sum(int a,int b){System.out.println(a+b);}
3. double sum(int a,int b){System.out.println(a+b);}
4.
5. public static void main(String args[]){
6. Calculation obj=new Calculation();
7. int result=obj.sum(20,20); //Compile Time Error
8.
9. }
10. }
11. int result=obj.sum(20,20); //Here how can java determine which sum() method should be called
Yes, by method overloading. You can have any number of main methods in a class by method
overloading. Let's see the simple example:
1. class Simple{
2. public static void main(int a){
3. System.out.println(a);
4. }
5.
6. public static void main(String args[]){
7. System.out.println("main() method invoked");
8. main(10);
28 | P a g e
9. }
10. } Output:main() method invoke
Lecture 6
Constructors in Java
1. Types of constructors
1. Default Constructor
2. Parameterized Constructor
2. Constructor Overloading
3. Does constructor return any value?
4. Copying the values of one object into another
5. Does constructor perform other tasks instead of the initialization
In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is
created. At the time of calling constructor, memory for the object is allocated in the memory.
Every time an object is created using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case, Java compiler provides
a default constructor by default.
There are two types of constructors in Java: no-arg constructor, and parameterized constructor.
Note: It is called constructor because it constructs the values at the time of object creation. It is not necessary to
write a constructor for a class. It is because java compiler creates a default constructor if your class doesn't have
any.
Note: We can use access modifiers while declaring a constructor. It controls the object creation. In other words,
we can have private, protected, public or default constructor in Java.
29 | P a g e
1. Default constructor (no-arg constructor)
2. Parameterized constructor
1. <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 creati
1. //Java Program to create and call a default constructor
2. class Bike1{
3. //creating a default constructor
4. Bike1(){System.out.println("Bike is created");}
5. //main method
6. public static void main(String args[]){
7. //calling a default constructor
8. Bike1 b=new Bike1();
9. }
10. }
Test it Now
Output:
Bike is created
The default constructor is used to provide the default values to the object like 0, null, etc., depending on the
type.
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.
The parameterized constructor is used to provide different values to distinct objects. However, you can provide
the same values also.
In this example, we have created the constructor of Student class that have two parameters. We can have any
number of parameters in the constructor.
Output:
111 Karan
222 Aryan
In Java, a constructor is just like a method but without return type. It can also be overloaded like Java methods.
Constructor overloading in Java is a technique of having more than one constructor with different parameter
lists. They are arranged in a way that each constructor performs a different task. They are differentiated by the
compiler by the number of parameters in the list and their types.
Output:
111 Karan 0
222 Aryan 25
There are many differences between constructors and methods. They are given below.
A constructor is used to initialize the state of an object. A method is used to expose the behav
object.
A constructor must not have a return type. A method must have a return type.
The Java compiler provides a default constructor if you don't have any The method is not provided by the com
constructor in a class. any case.
The constructor name must be same as the class name. The method name may or may not be
class name.
33 | P a g e
Java Copy Constructor
There is no copy constructor in Java. However, we can copy the values from one object to another like copy
constructor in C++.
There are many ways to copy the values of one object into another in Java. They are:
o By constructor
o By assigning the values of one object into another
o By clone() method of Object class
In this example, we are going to copy the values of one object into another using Java constructor.
1. //Java program to initialize the values from one object to another object.
2. class Student6{
3. int id;
4. String name;
5. //constructor to initialize integer and string
6. Student6(int i,String n){
7. id = i;
8. name = n;
9. }
10. //constructor to initialize another object
11. Student6(Student6 s){
12. id = s.id;
13. name =s.name;
14. }
15. void display(){System.out.println(id+" "+name);}
16.
17. public static void main(String args[]){
18. Student6 s1 = new Student6(111,"Karan");
19. Student6 s2 = new Student6(s1);
20. s1.display();
21. s2.display();
22. }
23. } Test it Now
Output:
111 Karan
111 Karan
34 | P a g e
We can copy the values of one object into another by assigning the objects values to another object. In this case,
there is no need to create the constructor.
1. class Student7{
2. int id;
3. String name;
4. Student7(int i,String n){
5. id = i;
6. name = n;
7. }
8. Student7(){}
9. void display(){System.out.println(id+" "+name);}
10.
11. public static void main(String args[]){
12. Student7 s1 = new Student7(111,"Karan");
13. Student7 s2 = new Student7();
14. s2.id=s1.id;
15. s2.name=s1.name;
16. s1.display();
17. s2.display();
18. }
19. }
20. 111 Karan
21. 111 Karan
1. Static variable
2. Program of the counter without static variable
3. Program of the counter with static variable
4. Static method
5. Restrictions for the static method
6. Why is the main method static?
7. Static block
8. Can we execute a program without main method?
The static keyword in Java is used for memory management mainly. We can apply static keyword
with variables, methods, blocks and nested classes. The static keyword belongs to the class than an instance of
the class.
35 | P a g e
3. Block
4. Nested class
o The static variable can be used to refer to the common property of all objects (which is not unique for
each object), for example, the company name of employees, college name of students, etc.
o The static variable gets memory only once in the class area at the time of class loading.
1. class Student{
2. int rollno;
3. String name;
4. String college="ITS";
5. }
Suppose there are 500 students in my college, now all instance data members will get memory each time when
the object is created. All students have its unique rollno and name, so instance data member is good in such
case. Here, "college" refers to the common property of all objects. If we make it static, this field will get the
memory only once.
36 | P a g e
12. void display (){System.out.println(rollno+" "+name+" "+college);}
13. }
14. //Test class to show the values of objects
15. public class TestStaticVariable1{
16. public static void main(String args[]){
17. Student s1 = new Student(111,"Karan");
18. Student s2 = new Student(222,"Aryan");
19. //we can change the college of all objects by the single line of code
20. //Student.college="BBDIT";
21. s1.display();
22. s2.display();
23. }
24. }
Test it Now
Output:
In this example, we have created an instance variable named count which is incremented in the constructor.
Since instance variable gets the memory at the time of object creation, each object will have the copy of the
instance variable. If it is incremented, it won't reflect other objects. So each object will have the value 1 in the
count variable.
37 | P a g e
16. }
17. }
Test it Now
Output:
1
1
1
As we have mentioned above, static variable will get the memory only once, if any object changes the value of
the static variable, it will retain its value.
Output:
1
2
3
If you apply static keyword with any method, it is known as static method.
38 | P a g e
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.
39 | P a g e
1. //Java Program to get the cube of a given number using the static method
2.
3. class Calculate{
4. static int cube(int x){
5. return x*x*x;
6. }
7.
8. public static void main(String args[]){
9. int result=Calculate.cube(5);
10. System.out.println(result);
11. }
12. }
Test it Now
Output:125
There are two main restrictions for the static method. They are:
1. The static method can not use non static data member or call non-static method directly.
2. this and super cannot be used in static context.
1. class A{
2. int a=40;//non static
3.
4. public static void main(String args[]){
5. System.out.println(a);
6. }
7. }
Test it Now
Output:Compile Time Error
Ans) It is because the object is not required to call a static method. If it were a non-static method, JVM creates
an object first then call main() method that will lead the problem of extra memory allocation.
Static Class
40 | P a g e
1. Nested static class doesn’t need reference of Outer class
2. A static class cannot access non-static members of the Outer class
class JavaExample1{
private static String str = "BeginnersBook";
//Static class
static class MyNestedClass{
//non-static method
public void disp() {
}
public static void main(String args[])
{
/* To create instance of nested class we didn't need the outer
* class instance but for a regular nested class you would need
* to create an instance of outer class first
*/
JavaExample1.MyNestedClass obj = new JavaExample1.MyNestedClass();
obj.disp();
}
}
Output:
BeginnersBook
A constructor looks more like a method but without return type. Moreover, the name of the
constructor and the class name should be the same. The advantage of constructors over methods is
that they are called implicitly whenever an object is created. In case of methods, they must be
called explicitly. To create an object, the constructor must be called. Constructor gives properties to
41 | P a g e
an object at the time of creation only. Programmer uses constructor to initialize variables, instantiating
objects, and setting colors.
public Demo()
"public" is the access specifier and "Demo()" is the constructor. Notice, it does not have return type
and the name is that of the class name.
In the above statement, d1 is an object of Demo class. To create the object, the constructor "Demo()"
is called. Like this, any number of objects can be created like d2 and for each object the constructor
is called.
Constructor Overloading
Just like method overloading, constructors also can be overloaded. Same constructor declared with different
parameters in the same class is known as constructor overloading. Compiler differentiates which constructor is
to be called depending upon the number of parameters and their sequence of data types.
42 | P a g e
9 System.out.println("Circle perimeter: " + 2*Math.PI*x);
10 }
11 public Perimeter(int x, int y) // III
12 {
13 System.out.println("Rectangle perimeter: " +2*(x+y));
14 }
15 public static void main(String args[])
16 {
17 Perimeter p1 = new Perimeter(); // I
18 Perimeter p2 = new Perimeter(10); // II
19 Perimeter p3 = new Perimeter(10, 20); // III
20 }
21 }
Perimeter constructor is overloaded three times. As per the parameters, an appropriate constructor is
called. To call all the three constructors three objects are created.
Static methods
The static keyword is used in java mainly for memory management. We may apply static keyword
with variables, methods, blocks and nested class. The static keyword belongs to the class than
instance of the class.
43 | P a g e
19. s2.display();
20. }
21. }
static method
If you apply static keyword with any method, it is known as static method
class Student{
int rollno;
String name;
static String college = "ITS";
static void change(){
college = "BBDIT";
}
Student(int r, String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student.change();
Student s1 = new Student (111,"Karan");
Student s2 = new Student (222,"Aryan");
Student s3 = new Student (333,"Sonoo");
s1.display();
s2.display();
s3.display();
}
}
44 | P a g e
1. class A{
2. int a=40;//non static
3.
4. public static void main(String args[]){
5. System.out.println(a);
6. }
7. }
Ans) because object is not required to call static method if it were non-static method, jvm create object
first then call main() method that will lead the problem of extra memory allocation.
Static block
1. class A{
2.
3. static{System.out.println("static block is invoked");}
4.
5. public static void main(String args[]){
6. System.out.println("Hello main");
7. }
8. }
Ans) Yes, one of the way is static block but in previous version of JDK not in JDK 1.7.
1. class A{
2. static{
3. System.out.println("static block is invoked");
4. System.exit(0);
5. }
6. }
6. this keyword can also be used to return the current class instance.
Final Keyword
A java variable can be declared using the keyword final. Then the final variable can be assigned
only once.
Java classes declared as final cannot be extended.
Methods declared as final cannot be overridden. In methods private is equal to final, but in
variables it is not.
There are two types of modifiers in Java: access modifiers and non-access modifiers.
The access modifiers in Java specify the accessibility or scope of a field, method, constructor, or class. We
can change the access level of fields, constructors, methods, and class by applying the access modifier on
it.
1. Private: The access level of a private modifier is only within the class. It cannot be accessed from
outside the class.
46 | P a g e
2. Default: The access level of a default modifier is only within the package. It cannot be accessed
from outside the package. If you do not specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and outside the package
through child class. If you do not make the child class, it cannot be accessed from outside the
package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within the
class, outside the class, within the package and outside the package.
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient,
etc. Here, we are going to learn the access modifiers only.
Access Modifier within class within package outside package by subclass only outside package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
1) Private
The private access modifier is accessible only within the class.
In this example, we have created two classes A and Simple. A class contains private data member and
private method. We are accessing these private members from outside the class, so there is a compile-
time error.
1. class A{
2. private int data=40;
3. private void msg(){System.out.println("Hello java");}
4. }
5.
47 | P a g e
6. public class Simple{
7. public static void main(String args[]){
8. A obj=new A();
9. System.out.println(obj.data);//Compile Time Error
10. obj.msg();//Compile Time Error
11. }
12. }
If you make any class constructor private, you cannot create the instance of that class from outside the
class. For example:
1. class A{
2. private A(){}//private constructor
3. void msg(){System.out.println("Hello java");}
4. }
5. public class Simple{
6. public static void main(String args[]){
7. A obj=new A();//Compile Time Error
8. }
9. }
2) Default
If you don't use any modifier, it is treated as default by default. The default modifier is accessible only
within package. It cannot be accessed from outside the package. It provides more accessibility than
private. But, it is more restrictive than protected, and public.
In this example, we have created two packages pack and mypack. We are accessing the A class from
outside its package, since A class is not public, so it cannot be accessed from outside the package.
1. //save by A.java
2. package pack;
3. class A{
4. void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
48 | P a g e
4. class B{
5. public static void main(String args[]){
6. A obj = new A();//Compile Time Error
7. obj.msg();//Compile Time Error
8. }
9. }
In the above example, the scope of class A and its method msg() is default so it cannot be accessed from
outside the package.
3) Protected
The protected access modifier is accessible within package and outside the package but through
inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It can't be
applied on the class.
In this example, we have created the two packages pack and mypack. The A class of pack package is
public, so can be accessed from outside the package. But msg method of this package is declared as
protected, so it can be accessed from outside the class only through inheritance.
1. //save by A.java
2. package pack;
3. public class A{
4. protected void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B extends A{
6. public static void main(String args[]){
7. B obj = new B();
8. obj.msg();
9. }
10. }
Output:Hello
49 | P a g e
4) Public
The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2.
3. package mypack;
4. import pack.*;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();
9. obj.msg();
10. }
11. }
Output:Hello
1. class A{
2. protected void msg(){System.out.println("Hello java");}
3. }
4.
5. public class Simple extends A{
6. void msg(){System.out.println("Hello java");}//C.T.Error
7. public static void main(String args[]){
8. Simple obj=new Simple();
9. obj.msg();
10. }
11. }
The default modifier is more restrictive than protected. That is why, there is a compile-time error.
50 | P a g e
Lecture 7
A class that is derived from another class is called subclass and inherits all fields and methods of its
superclass. In Java, only single inheritance is allowed and thus, every class can have at most one
direct superclass. A class can be derived from another class that is derived from another class and so
on. Finally, we must mention that each class in Java is implicitly a subclass of the Object class.
Suppose we have declared and implemented a class A. In order to declare a class B that is derived
from A, Java offers the extend keyword that is used as shown below:
class A {
//Members and methods declarations.
}
class B extends A {
//Members and methods from A are inherited.
//Members and methods declarations of B.
}
51 | P a g e
Methode Overriding:-
when a method in a Subclass has the same name and same return-type and same parameters as
that of method in its Superclass, then the method in the Subclass is said to Override the method in
the Superclass"
It should be noted that, method overriding occurs only when the names & type signatures fo the two
methodes are same. If they are not, then the two methodes are simply overloaded. Following
example will explain mehtod overriding in details.
public class A
{
void show(int i){
System.out.println("i inside superclass : " + i);
}
}
//Subclass B
public class B extends A
52 | P a g e
{
//overriedn methode "show(int i)"
void show(int i){
}
}
public class Main
{
public static void main(String[] args)
{
B objB= new B();
objB.show(10);
}
}
Output:-
i inside subclass : 10
i inside superclass : 20
Lecture 8
Using Super to Call Super class constructor
53 | P a g e
this() : to invoke current class constructor
The this() constructor call can be used to invoke the current class constructor. It is used to reuse the
constructor. In other words, it is used for constructor chaining.
54 | P a g e
Calling default constructor from parameterized constructor:
1. class A{
2. A(){System.out.println("hello a");}
3. A(int x){
4. this();
5. System.out.println(x);
6. }
7. }
8. class TestThis5{
9. public static void main(String args[]){
10. A a=new A(10);
11. }}
Test it Now
Output:
hello a
10
1. class A{
2. A(){
3. this(5);
4. System.out.println("hello a");
5. }
6. A(int x){
7. System.out.println(x);
8. }
9. }
10. class TestThis6{
11. public static void main(String args[]){
12. A a=new A();
13. }}
Test it Now
Output:
5
hello a
55 | P a g e
Dynamic method dispatch is one type of mechanism by which a call to an overridden method is
resolved at run time, rather than at compile time. Dynamic method dispatch allow Java to implement
run-time polymorphism.
When an overridden method is called through the obeject of superclass then Java determines
which version of that method to execute, based upon the type of the object being referred to at the
time the call occurs, hence determination is made at run time. Go througn following example to clear
this concept.
class A {
void callme() {
System.out.println("Inside A's callme method");
}
}
class B extends A {
// override callme()
void callme() {
System.out.println("Inside B's callme method");
}
}
class C extends A {
// override callme()
void callme() {
System.out.println("Inside C's callme method");
}
}
class Dispatch {
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
THE JAVA LANGUAGE
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}
}
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
The syntax is
abstract class class_name { }
56 | P a g e
Method that are declared without any body within an abstract class is known as 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 ();
abstract class A
{
abstract void callme();
}
class B extends A
{
void callme()
{
System.out.println("this is callme.");
}
public static void main(String[] args)
{
B b=new B();
b.callme();
}
}
abstract class A
{
abstract void callme();
public void normal()
{
System.out.println("this is concrete method");
}
}
class B extends A
{
void callme()
{
System.out.println("this is callme.");
}
public static void main(String[] args)
{
B b=new B();
b.callme();
57 | P a g e
b.normal();
}
}
Abstract methods are usually declared where two or more subclasses are expected to do a similar
thing in different ways through different implementations. These subclasses extend the same Abstract
class and provide different implementations for the abstract methods Abstract classes are used to
define generic types of behaviors at the top of an object-oriented programming class hierarchy, and
use its subclasses to provide implementation details of the abstract class
Lecture 9
final is used to prevent overriding
You can use final keyword to declare a method, and methods declared with final cannot be
overridden. There are certain situations where we need to prevent method overriding and so final is
used to achieve that.
class Super
{
final void Display()
{
System.out.println (“Display is final method”);
}
}
You can also use final to prevent inheritance as well, you just need to declare a class as final to do
this.
Example:
Java String
In Java, string is basically an object that represents sequence of char values. An array of characters
works same as Java string. For example:
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as:
1. String s="javatpoint";
Java String class provides a lot of methods to perform operations on strings such as compare(), concat(),
equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
59 | P a g e
CharSequence Interface
The CharSequence interface is used to represent the sequence of characters.
String, StringBuffer and StringBuilder classes implement it. It means, we can create strings in java by
using these three classes.
The Java String is immutable which means it cannot be changed. Whenever we change any string, a new
instance is created. For mutable strings, you can use StringBuffer and StringBuilder classes.
We will discuss immutable string later. Let's first understand what is String in Java and how to create the
String object.
1. By string literal
2. By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
1. String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first. If the string already
exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a
new string instance is created and placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance
60 | P a g e
In the above example, only one object will be created. Firstly, JVM will not find any string object with the
value "Welcome" in string constant pool, that is why it will create a new object. After that it will find the
string with the value "Welcome" in the pool, it will not create a new object but will return the reference to
the same instance.
Note: String objects are stored in a special memory area known as the "string constant pool".
2) By new keyword
1. String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal (non-pool) heap memory, and the literal
"Welcome" will be placed in the string constant pool. The variable s will refer to the object in a heap (non-
pool).
61 | P a g e
No. Method Description
4 static String format(Locale l, String format, Object... args) returns formatted string with gi
6 String substring(int beginIndex, int endIndex) returns substring for given begi
and end index.
62 | P a g e
limit.
20 int indexOf(int ch, int fromIndex) returns the specified char value
starting with given index.
Do You Know?
o Why are String objects immutable?
o How to create an immutable class?
o What is string constant pool?
o What code is written by the compiler if you concatenate any string by + (string concatenation
operator)?
o What is the difference between StringBuffer and StringBuilder class?
63 | P a g e
o String Comparison
o String Concatenation
o Concept of Substring
o String class methods and its usage
o StringBuffer class
o StringBuilder class
o Creating Immutable class
o toString() method
o StringTokenizer class
Once string object is created its data or state can't be changed but a new string object is created.
Let's try to understand the immutability concept by the example given below:
1. class Testimmutablestring{
2. public static void main(String args[]){
3. String s="Sachin";
4. s.concat(" Tendulkar");//concat() method appends the string at the end
5. System.out.println(s);//will print Sachin because strings are immutable objects
6. }
7. }
Test it Now
Output:Sachin
Now it can be understood by the diagram given below. Here Sachin is not changed but a new object is
created with sachintendulkar. That is why string is known as immutable.
As you can see in the above figure that two objects are created but s reference variable still refers to
"Sachin" not to "Sachin Tendulkar".
But if we explicitely assign it to the reference variable, it will refer to "Sachin Tendulkar" object.For
example:
1. class Testimmutablestring1{
2. public static void main(String args[]){
3. String s="Sachin";
4. s=s.concat(" Tendulkar");
5. System.out.println(s);
6. }
7. }
64 | P a g e
Test it Now
Output:Sachin Tendulkar
In such case, s points to the "Sachin Tendulkar". Please notice that still sachin object is not modified.
Because java uses the concept of string literal.Suppose there are 5 reference variables,all referes to one object "
one reference variable changes the value of the object, it will be affected to all the reference variables. That is w
objects are immutable in java.
OBJECT CLASS
The java.lang.Object class is the root of the class hierarchy. Every class has Object as a superclass.
All objects, including arrays, implement the methods of this class.
Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects,
including arrays, implement the methods of this class.
clone()
Creates a new object of the same class as this object.
equals(Object)
Compares two Objects for equality.
finalize()
Called by the garbage collector on an object when garbage collection determines that there
are no more references to the object.
getClass()
Returns the runtime class of an object.
hashCode()
Returns a hash code value for the object.
notify()
Wakes up a single thread that is waiting on this object's monitor.
notifyAll()
Wakes up all threads that are waiting on this object's monitor.
toString()
Returns a string representation of the object.
wait()
Waits to be notified by another thread of a change in this object.
wait(long)
Waits to be notified by another thread of a change in this object.
wait(long, int)
Waits to be notified by another thread of a change in this object.
65 | P a g e
Java String compare
It is used in authentication (by equals() method), sorting (by compareTo() method), reference
matching (by == operator) etc.
1. By equals() method
2. By = = operator
3. By compareTo() method
o public boolean equals(Object another) compares this string to the specified object.
o public boolean equalsIgnoreCase(String another) compares this String to another string,
ignoring case.
1. class Teststringcomparison1{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3=new String("Sachin");
6. String s4="Saurav";
7. System.out.println(s1.equals(s2));//true
8. System.out.println(s1.equals(s3));//true
9. System.out.println(s1.equals(s4));//false
10. }
11. }
66 | P a g e
Test it Now
Output:true
true
false
1. class Teststringcomparison2{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="SACHIN";
5.
6. System.out.println(s1.equals(s2));//false
7. System.out.println(s1.equalsIgnoreCase(s2));//true
8. }
9. }
Test it Now
Output:
false
true
Click here for more about equals() method
1. class Teststringcomparison3{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3=new String("Sachin");
6. System.out.println(s1==s2);//true (because both refer to same instance)
7. System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)
8. }
9. }
Test it Now
Output:true
false
o s1 == s2 :0
67 | P a g e
o s1 > s2 :positive value
o s1 < s2 :negative value
1. class Teststringcomparison4{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3="Ratan";
6. System.out.println(s1.compareTo(s2));//0
7. System.out.println(s1.compareTo(s3));//1(because s1>s3)
8. System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
9. }
10. }
Test it Now
Output:0
1
-1
1. class TestStringConcatenation1{
2. public static void main(String args[]){
3. String s="Sachin"+" Tendulkar";
4. System.out.println(s);//Sachin Tendulkar
5. }
6. }
Test it Now
Output:Sachin Tendulkar
In java, String concatenation is implemented through the StringBuilder (or StringBuffer) class and its
append method. String concatenation operator produces a new string by appending the second operand
onto the end of the first operand. The string concatenation operator can concat not only string but
primitive values also. For Example:
68 | P a g e
1. class TestStringConcatenation2{
2. public static void main(String args[]){
3. String s=50+30+"Sachin"+40+40;
4. System.out.println(s);//80Sachin4040
5. }
6. }
Test it Now
80Sachin4040
Note: After a string literal, all the + will be treated as string concatenation operator.
1. class TestStringConcatenation3{
2. public static void main(String args[]){
3. String s1="Sachin ";
4. String s2="Tendulkar";
5. String s3=s1.concat(s2);
6. System.out.println(s3);//Sachin Tendulkar
7. }
8. }
Test it Now
Sachin Tendulkar
Substring in Java
A part of string is called substring. In other words, substring is a subset of another string. In case of
substring startIndex is inclusive and endIndex is exclusive.
You can get substring from the given string object by one of the two methods:
1. public String substring(int startIndex): This method returns new String object containing the
substring of the given string from specified startIndex (inclusive).
2. public String substring(int startIndex, int endIndex): This method returns new String object
containing the substring of the given string from specified startIndex to endIndex.
In case of string:
o startIndex: inclusive
69 | P a g e
o endIndex: exclusive
Let's understand the startIndex and endIndex by the code given below.
1. String s="hello";
2. System.out.println(s.substring(0,2));//he
In the above substring, 0 points to h but 2 points to e (because end index is exclusive).
Lecture 10
Interface is a pure abstract class. They are syntactically similar to classes, but you cannot create
instance of an interface. Interface is used to achieve complete abstraction in Java
interface interface_name { }
interface Moveable
{
int AVG-SPEED = 40;
void move();
}
interface Moveable
{
boolean isMoveable();
}
interface Rollable
{
boolean isRollable
}
boolean isMoveable()
{
return true;
}
boolean isRollable()
{
return true;
}
public static void main(String args[])
{
Tyre tr=new Tyre();
System.out.println(tr.isMoveable());
System.out.println(tr.isRollable());
}
}
interface NewsPaper
{
news();
}
71 | P a g e
interface Magazine extends NewsPaper
{
colorful();
}
Lecture 11
A package can be defined as a group of similar types of classes, interface, enumeration and sub-
package. Using package it becomes easier to locate the related classes"/>
72 | P a g e
Package access protection
Classes within a package can access classes and members declared with default access and class
members declared with the protected access modifier. Default access is enforced when neither the
public, protected, nor private access modifier is specified in the declaration. By contrast, classes in
other packages cannot access classes and members declared with default access. Class members
declared as protected can be accessed from the classes in the same package as well as classes in
other packages that are subclasses of the declaring class.
73 | P a g e
74 | P a g e
Lecture 12
Exception Hierarchy:
All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass
of the Throwable class. Other than the exception class there is another subclass called Error which is
derived from the Throwable class.
Errors are not normally trapped form the Java programs. These conditions normally happen in case
of severe failures, which are not handled by the java programs. Errors are generated to indicate
errors generated by the runtime environment. Example: JVM is out of Memory. Normally programs
cannot recover from errors.
The Exception class has two main subclasses: IOException class and RuntimeException Class.
Runtime exceptions: A runtime exception is an exception that occurs that probably could have
been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are
ignored at the time of compilation.
Catching Exceptions:
A method catches an exception using a combination of the try and catch keywords. A try/catch block
is placed around the code that might generate an exception. Code within a try/catch block is referred
to as protected code, and the syntax for using try/catch looks like the following:
try
{
//Protected code
}catch(ExceptionName e1)
{
//Catch block
}
75 | P a g e
A catch statement involves declaring the type of exception you are trying to catch. If an exception
occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of
exception that occurred is listed in a catch block, the exception is passed to the catch block much as
an argument is passed into a method parameter.
Example:
The following is an array is declared with 2 elements. Then the code tries to access the 3rd element
of the array which throws an exception.
A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like
the following:
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}
76 | P a g e
Lecture 13
The throws/throw Keywords:
If a method does not handle a checked exception, the method must declare it using the throws
keyword. The throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just caught, by
using the throw keyword. Try to understand the different in throws and throw keywords.
The finally keyword is used to create a block of code that follows a try block. A finally block of code
always executes, whether or not an exception has occurred.
Using a finally block allows you to 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 the catch blocks and has the following syntax:
try
{
//Protected code
}catch (ExceptionType1 e1)
{
//Catch block
} finally
{
//The finally block always executes.
}
You can create your own exceptions in Java. Keep the following points in mind when writing your own
exception classes:
If you want to write a runtime exception, you need to extend the RuntimeException class.
New
When we create a new Thread object using new operator, thread state is New Thread. At this point, thread is not
alive and it’s a state internal to Java programming.
Runnable
When we call start () function on Thread object, it’s state is changed to Runnable and the control is given to
Thread scheduler to finish it’s execution. Whether to run this thread instantly or keep it in runnable thread pool
before running it depends on the OS implementation of thread scheduler.
Running
When thread is executing, it’s state is changed to Running. Thread scheduler picks one of the thread from the
runnable thread pool and change it’s state to Running and CPU starts executing this thread. A thread can change
state to Runnable, Dead or Blocked from running state depends on time slicing, thread completion of run()
method or waiting for some resources.
Blocked/Waiting
A thread can be waiting for other thread to finish using thread join or it can be waiting for some resources to
available, for example producer consumer problem or waiter notifier implementation or IO resources, then it’s
state is changed to Waiting. Once the thread wait state is over, its state is changed to Runnable and it’s moved
back to runnable thread pool.
Dead
Once the thread finished executing, it’s state is changed to Dead and it’s considered to be not alive.
78 | P a g e
How to create thread:
There are two ways to create a thread:
Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.Thread class extends
Object class and implements Runnable interface.
Thread()
Thread(String name)
Thread(Runnable r)
19. public static boolean interrupted(): tests if the current thread has been interrupted.
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().
79 | P a g e
1. public void run(): is used to perform action for a thread.
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following tasks:
A new thread starts(with new callstack).
The thread moves from New state to the Runnable state.
When the thread gets a chance to execute, its target run() method will run.
Program Example
Thread Priorities
In Java, thread scheduler can use the thread priorities in the form of integer value to each of its
thread to determine the execution schedule of threads . Thread gets the ready-to-run state according
to their priorities. The thread scheduler provides the CPU time to thread of highest priority during
ready-to-run state.
Priorities are integer values from 1 (lowest priority given by the constant Thread.MIN_PRIORITY) to
10 (highest priority given by the constant Thread.MAX_PRIORITY). The default priority is
5(Thread.NORM_PRIORITY).
Constant Description
The maximum priority of any thread
Thread.MIN_PRIORITY
(an int value of 1)
The minimum priority of any thread
Thread.MAX_PRIORITY
(an int value of 10)
The normal priority of any thread (an
Thread.NORM_PRIORITY
int value of 5)
The methods that are used to set the priority of thread shown as:
Method Description
This is method is used to set the priority
setPriority()
of thread.
This method is used to get the priority of
getPriority()
thread.
When a Java thread is created, it inherits its priority from the thread that created it. At any given time,
when multiple threads are ready to be executed, the runtime system chooses the runnable thread
with the highest priority for execution. In Java runtime system, preemptive scheduling algorithm is
applied. If at the execution time a thread with a higher priority and all other threads are runnable then
the runtime system chooses the new higher priority thread for execution. On the other hand, if two
threads of the same priority are waiting to be executed by the CPU then the round-robin algorithm is
applied in which the scheduler chooses one of them to run according to their round of time-slice.
81 | P a g e
Lecture 17:
Synchronization
When we start two or more threads within a program, there may be a situation when multiple threads
try to access the same resource and finally they can produce unforeseen result due to concurrency
issue. For example if multiple threads try to write within a same file then they may corrupt the data
because one of the threads can overrite data or while one thread is opening the same file at the same
time another thread might be closing the same file.
So there is a need to synchronize the action of multiple threads and make sure that only one thread
can access the resource at a given point in time. This is implemented using a concept called
monitors. Each object in Java is associated with a monitor, which a thread can lock or unlock. Only
one thread at a time may hold a lock on a monitor.
Java programming language provides a very handy way of creating threads and synchronizing their
task by using synchronized blocks. You keep shared resources within this block. Following is the
general form of the synchronized statement:
synchronized(objectidentifier) {
// Access shared variables and other shared resources
}
Here, the objectidentifier is a reference to an object whose lock associates with the monitor that the
synchronized statement represents. Now we are going to see two examples where we will print a
counter using two different threads. When threads are not synchronized, they print counter value
which is not in sequence, but when we print counter by putting inside synchronized() block, then it
prints counter very much in sequence for both the threads.
Here is the same example which prints counter value in sequence and every time we run it, it
produces same result.
class PrintDemo {
public void printCount(){
try {
for(int i = 5; i > 0; i--) {
System.out.println("Counter --- " + i );
}
} catch (Exception e) {
System.out.println("Thread interrupted.");
82 | P a g e
}
}
T1.start();
T2.start();
83 | P a g e
}
}
This produces same result every time you run this program:
Starting Thread - 1
Starting Thread - 2
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 1 exiting.
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 2 exiting.
wo ways exist to determine whether a thread has finished. First, you can call isAlive( ) on the thread.
This method is defined by Thread, and its general form is shown here:
The isAlive( ) method returns true if the thread upon which it is called is still running. It returns false
otherwise. While isAlive( ) is occasionally useful, the method that you will more commonly use to wait
for a thread to finish is called join( ), shown here:
This method waits until the thread on which it is called terminates. Its name comes from the concept
of the calling thread waiting until the specified thread joins it. Additional forms of join( ) allow you to
specify a maximum amount of time that you want to wait for the specified thread to terminate. Here is
an improved version of the preceding example that uses join( ) to ensure that the main thread is the
last to stop. It also demonstrates the isAlive( ) method.
synchronized(b){
try{
System.out.println("Waiting for b to complete...");
b.wait();
}catch(InterruptedException e){
84 | P a g e
e.printStackTrace();
}
Lecture 18:
Creating Strings:
String Length:
int len = palindrome.length();
Concatenating Strings:
string1.concat (string2)
String compare
85 | P a g e
Lecture 19:
How to modify the string
The StringBuffer and StringBuilder classes are used when there is a necessity to make a lot of
modifications to Strings of characters.
Unlike Strings objects of type StringBuffer and Stringbuilder can be modified over and over again with
out leaving behind a lot of new unused objects.
The StringBuilder class was introduced as of Java 5 and the main difference between the StringBuffer
and StringBuilder is that StringBuilders methods are not thread safe(not Synchronised).
Example:
public class Test{
StringBuffer Methods:
SN Methods with Description
public StringBuffer append(String s)
1 Updates the value of the object that invoked the method. The method takes boolean, char, int,
long, Strings etc.
public StringBuffer reverse()
2
The method reverses the value of the StringBuffer object that invoked the method.
public delete(int start, int end)
3
Deletes the string starting from start index until end index.
public insert(int offset, int i)
4
This method inserts an string s at the position mentioned by offset.
replace(int start, int end, String str)
5 This method replaces the characters in a substring of this StringBuffer with characters in the
specified String.
86 | P a g e
Lecture 20:
The java.io.Interfaces provides for system input and output through data streams, serialization and
the file system.
Interface Summary
S.N. Interface & Description
Closeable
1
This is a source or destination of data that can be closed.
DataInput
2 This provides for reading bytes from a binary stream and reconstructing from them data in any
of the Java primitive types.
DataOutput
3 This provides for converting data from any of the Java primitive types to a series of bytes and
writing these bytes to a binary stream.
Externalizable
This provides only the identity of the class of an Externalizable instance is written in the
4
serialization stream and it is the responsibility of the class to save and restore the contents of its
instances.
FileFilter
5
This is a filter for abstract pathnames.
FilenameFilter
6
This is instances of classes that implement this interface are used to filter filenames.
Flushable
7
This is a destination of data that can be flushed.
ObjectInput
8
This extends the DataInput interface to include the reading of objects.
ObjectInputValidation
9
This is the callback interface to allow validation of objects within a graph.
ObjectOutput
10
This is the objectOutput extends the DataOutput interface to include writing of objects.
ObjectStreamConstants
11
The constants written into the Object Serialization Stream.
Serializable
12
This is enabled by the class implementing the java.io.Serializable interface.
A stream can be defined as a sequence of data. The InputStream is used to read data from a source
and the OutputStream is used for writing data to a destination.
Java provides strong but flexible support for I/O related to Files and networks but this tutorial covers
very basic functionality related to streams and I/O. We would see most commonly used example one
by one:
87 | P a g e
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
classes related to byte streams but the most frequently used classes are , FileInputStream and
FileOutputStream. Following is an example which makes use of these two classes to copy an input
file into an output file:
import java.io.*;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
As a next step, compile above program and execute it, which will result in creating output.txt file with
the same content as we have in input.txt. So let's put above code in CopyFile.java file and do the
following:
$javac CopyFile.java
$java CopyFile
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, where as Java Character
streams are used to perform input and output for 16-bit unicode. Though there are many classes
related to character streams but the most frequently used classes are , FileReader and FileWriter..
88 | P a g e
Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here
major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time.
We can re-write above example which makes use of these two classes to copy an input file (having
unicode characters) into an output file:
import java.io.*;
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
As a next step, compile above program and execute it, which will result in creating output.txt file with
the same content as we have in input.txt. So let's put above code in CopyFile.java file and do the
following:
$javac CopyFile.java
$java CopyFile
Standard Streams
All the programming languages provide support for standard I/O where user's program can take input
from a keyboard and then produce output on the computer screen. If you are aware if C or C++
programming languages, then you must be aware of three standard devices STDIN, STDOUT and
STDERR. Similar way Java provides following three standard streams
89 | P a g e
Standard Input: This is used to feed the data to user's program and usually a keyboard is
used as standard input stream and represented as System.in.
Standard Output: This is used to output the data produced by the user's program and usually
a computer screen is used to standard output stream and represented as System.out.
Standard Error: This is used to output the error data produced by the user's program and
usually a computer screen is used to standard error stream and represented as System.err.
90 | P a g e
Lecture 21:
serialization
Java provides a mechanism, called object serialization where an object can be represented as a
sequence of bytes that includes the object's data as well as information about the object's type and
the types of data stored in the object.
After a serialized object has been written into a file, it can be read from the file and deserialized that
is, the type information and bytes that represent the object and its data can be used to recreate the
object in memory.
Most impressive is that the entire process is JVM independent, meaning an object can be serialized
on one platform and deserialized on an entirely different platform.
Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the
methods for serializing and deserializing an object.
The ObjectOutputStream class contains many write methods for writing various data types, but one
method in particular stands out:
The above method serializes an Object and sends it to the output stream. Similarly, the
ObjectInputStream class contains the following method for deserializing an object:
This method retrieves the next Object out of the stream and deserializes it. The return value is Object,
so you will need to cast it to its appropriate data type.
To demonstrate how serialization works in Java, I am going to use the Employee class that we
discussed early on in the book. Suppose that we have the following Employee class, which
implements the Serializable interface:
91 | P a g e
Notice that for a class to be serialized successfully, two conditions must be met:
All of the fields in the class must be serializable. If a field is not serializable, it must be marked
transient.
If you are curious to know if a Java Standard Class is serializable or not, check the documentation for
the class. The test is simple: If the class implements java.io.Serializable, then it is serializable;
otherwise, it's not.
Serializing an Object:
The ObjectOutputStream class is used to serialize an Object. The following SerializeDemo program instantiates
an Employee object and serializes it to a file.
When the program is done executing, a file named employee.ser is created. The program does not generate
any output, but study the code and try to determine what the program is doing.
Note: When serializing an object to a file, the standard convention in Java is to give the file a .ser extension.
import java.io.*;
92 | P a g e
Deserializing an Object:
The following DeserializeDemo program deserializes the Employee object created in the SerializeDemo
program. Study the program and try to determine its output:
import java.io.*;
public class DeserializeDemo
{
public static void main(String [] args)
{
Employee e = null;
try
{
FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
}catch(IOException i)
{
i.printStackTrace();
return;
}catch(ClassNotFoundException c)
{
System.out.println("Employee class not found");
c.printStackTrace();
return;
}
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.SSN);
System.out.println("Number: " + e.number);
}
}
Deserialized Employee...
Name: Reyan Ali
Address:Phokka Kuan, Ambehta Peer
SSN: 0
Number:101
93 | P a g e
The try/catch block tries to catch a ClassNotFoundException, which is declared by the readObject()
method. For a JVM to be able to deserialize an object, it must be able to find the bytecode for the
class. If the JVM can't find a class during the deserialization of an object, it throws a
ClassNotFoundException.
Notice that the return value of readObject() is cast to an Employee reference.
The value of the SSN field was 11122333 when the object was serialized, but because the field is
transient, this value was not sent to the output stream. The SSN field of the deserialized Employee
object is 0.
94 | P a g e
Lecture 22:
What is JDBC?
JDBC stands for Java Database Connectivity, which is a standard Java API for database-
independent connectivity between the Java programming language and a wide range of databases.
The JDBC library includes APIs for each of the tasks commonly associated with database usage:
Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for
portable access to an underlying database. Java can be used to write different types of executables,
such as:
Java Applications
Java Applets
Java Servlets
All of these different executables are able to use a JDBC driver to access a database and take
advantage of the stored data.
JDBC provides the same capabilities as ODBC, allowing Java programs to contain database-
independent code.
JDBC Architecture:
The JDBC API supports both two-tier and three-tier processing models for database access but in general JDBC
Architecture consists of two layers:
95 | P a g e
The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity to
heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to access each data source. The driver manager
is capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases.
Following is the architectural diagram, which shows the location of the driver manager with respect to the
JDBC drivers and the Java application:
DriverManager: This class manages a list of database drivers. Matches connection requests from the
java application with the proper database driver using communication subprotocol. 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.
96 | P a g e
What is JDBC Driver ?
JDBC drivers implement the defined interfaces in the JDBC API for interacting with your database server.
For example, using JDBC drivers enable you to open database connections and to interact with it by sending
SQL or database commands then receiving results with Java.
The Java.sql package that ships with JDK contains various classes with their behaviours defined and their
actual implementaions are done in third-party drivers. Third party vendors implements the java.sql.Driver
interface in their database driver.
Lecture 23:
JDBC Drivers Types:
JDBC driver implementations vary because of the wide variety of operating systems and hardware platforms in
which Java operates. Sun has divided the implementation types into four categories, Types 1, 2, 3, and 4, which
is explained below:
In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client machine. Using
ODBC requires configuring on your system a Data Source Name (DSN) that represents the target database.
When Java first came out, this was a useful driver because most databases only supported ODBC access but
now this type of driver is recommended only for experimental use or when no other alternative is available.
The JDBC-ODBC bridge that comes with JDK 1.2 is a good example of this kind of driver.
97 | P a g e
Type 2: JDBC-Native API:
In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls which are unique to the database.
These drivers typically provided by the database vendors and used in the same manner as the JDBC-ODBC
Bridge, the vendor-specific driver must be installed on each client machine.
If we change the Database we have to change the native API as it is specific to a database and they are mostly
obsolete now but you may realize some speed increase with a Type 2 driver, because it eliminates ODBC's
overhead.
In a Type 3 driver, a three-tier approach is used to accessing databases. The JDBC clients use standard network
sockets to communicate with an middleware application server. The socket information is then translated by the
middleware application server into the call format required by the DBMS, and forwarded to the database server.
This kind of driver is extremely flexible, since it requires no code installed on the client and a single driver can
actually provide access to multiple databases.
98 | P a g e
You can think of the application server as a JDBC "proxy," meaning that it makes calls for the client
application. As a result, you need some knowledge of the application server's configuration in order to
effectively use this driver type.
Your application server might use a Type 1, 2, or 4 driver to communicate with the database, understanding the
nuances will prove helpful.
In a Type 4 driver, a pure Java-based driver that communicates directly with vendor's database through socket
connection. This is the highest performance driver available for the database and is usually provided by the
vendor itself.
This kind of driver is extremely flexible, you don't need to install special software on the client or server.
Further, these drivers can be downloaded dynamically.
99 | P a g e
Lecture 24
Networking basics:
Networking is a concept of connecting two or more computing devices together so that we can share resources.
IP Address
Protocol
Port Number
Socket
IP Address:
IP address is a unique number assigned to a node of a network e.g. 192.168.0.1. It is composed of octets that
range from 0 to 255.
Protocol:
A protocol is a set of rules basically that is followed for communication. For example:
TCP
FTP
Telnet
SMTP
POP etc.
100 | P a g e
Common ports no are reservered
Examples include:
URL class:
The URL class represents a URL. URL is an acronym for Uniform Resource Locator. It points to a resource on the World
Wide Web. For example:
101 | P a g e
1. http://www.javatpoint.com/sonoojaiswal/index.jsp
File Name or directory name: In this case, index.jsp is the file name.
1. //URLDemo.java
2.
3. import java.io.*;
4. import java.net.*;
5.
6. public class URLDemo{
7. public static void main(String[] args){
8. try{
9. URL url=new URL("http://www.javatpoint.com/sonoojaiswal/index.jsp");
10.
11. System.out.print("Protocol: "+url.getProtocol());
12. System.out.print("Host Name: "+url.getHost());
13. System.out.print("Port Number: "+url.getPort());
14. System.out.print("File Name: "+url.getFile());
15.
16. }catch(Exception e){System.out.println(e);}
17. }
18. }
WHOIS (pronounced as the phrase who is) is a query and response protocol that is widely used for querying databases
that store the registered users or assignees of an Internet resource, such as a domain name, an IP address block, or an
autonomous system, but is also used for a wider range of other information.
102 | P a g e
Lecture 26
Socket programming is performed for communication between the machines. Socket programming can be connection-
oriented or connectionless. Socket and ServerSocket classes are used for connection-oriented socket programming. The
client in socket programming must know two information:
1. IPaddress of Server, and
2. Port number.
Socket class:
A socket is simply an endpoint for communications between the machines. The Socket class can be used to create a
socket.
ServerSocket class:
The ServerSocket class can be used to create a server socket. This object is used to establish communication with the
clients.
103 | P a g e
Commonly used methods of ServerSocket class:
1. //MyServer.java
2.
3. import java.io.*;
4. import java.net.*;
5.
6. public class MyServer {
7. public static void main(String[] args){
8. try{
9. ServerSocket ss=new ServerSocket(6666);
10. Socket s=ss.accept();//establishes connection
11.
12. DataInputStream dis=new DataInputStream(s.getInputStream());
13.
14. String str=(String)dis.readUTF();
15. System.out.println("message= "+str);
16.
17. ss.close();
18.
19. }catch(Exception e){System.out.println(e);}
20. }
21. }
1. //MyClient.java
2.
3. import java.io.*;
4. import java.net.*;
5.
6. public class MyClient {
7. public static void main(String[] args) {
8. try{
9. Socket s=new Socket("localhost",6666);
10.
11. DataOutputStream dout=new DataOutputStream(s.getOutputStream());
12.
13. dout.writeUTF("Hello Server");
14. dout.flush();
15.
16. dout.close();
17. s.close();
18.
104 | P a g e
19. }catch(Exception e){System.out.println(e);}
20. }
21. }
Lecture 28
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:
When a user views an HTML page that contains an applet, the code for the applet is downloaded to the
user's machine.
A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser or a separate
runtime environment.
The JVM on the user's machine creates an instance of the applet class and invokes various methods
during the applet's lifetime.
Applets have strict security rules that are enforced by the Web browser. The security of an applet is
often referred to as sandbox security, comparing the applet to a child playing in a sandbox with various
rules that must be followed.
Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file.
Four methods in the Applet class give you the framework on which you build any serious applet:
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.
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.
105 | P a g e
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.
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.
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.
Lecture 29
Passing parameter to applet
import java.awt.*;
import java.applet.*;
106 | P a g e
public void paint(Graphics g)
{
// Shows what was in the HTML param code.
g.drawString("Parameter 1 is: " + parameter1,20,20);
g.drawString("Parameter 2 is: " + parameter2,20,40);
g.drawString("Parameter 3 is: " + parameter3,20,60);
g.drawString("Parameter 2 + parameter 3 is: " + result,20,80);
}
}
/* This only works when those paramters are actually in the HTML code.
That code for this example is :
<APPLET CODE="ParameterExample" WIDTH=200 HEIGHT=100>
<param name="param1" value="Hello">
<param name="param2" value="14">
<param name="param3" value="2">
</APPLET>
If you make applets for others make sure to use parameters, many
will appreciate it.
Lecture 30
delegation event model
The event model is based on the Event Source and Event Listeners. Event Listener is an object that receives the
messages / events. The Event Source is any object which creates the message / event. The Event Delegation
model is based on – The Event Classes, The Event Listeners, Event Objects.
An event occurs (like mouse click, key press, etc) which is followed by the event is broadcasted by the event
source by invoking an agreed method on all event listeners. The event object is passed as argument to the
agreed-upon method. Later the event listeners respond as they fit, like submit a form, displaying a message /
alert etc.
107 | P a g e
Following is the list of commonly used event classes.
Sr.
Control & Description
No.
AWTEvent
1 It is the root event class for all AWT events. This class and its subclasses supercede the original
java.awt.Event class.
ActionEvent
2
The ActionEvent is generated when button is clicked or the item of a list is double clicked.
InputEvent
3
The InputEvent class is root event class for all component-level input events.
KeyEvent
4
On entering the character the Key event is generated.
MouseEvent
5
This event indicates a mouse action occurred in a component.
TextEvent
6
The object of this class represents the text events.
WindowEvent
7
The object of this class represents the change in state of a window.
AdjustmentEvent
8
The object of this class represents the adjustment event emitted by Adjustable objects.
ComponentEvent
9
The object of this class represents the change in state of a window.
ContainerEvent
10
The object of this class represents the change in state of a window.
MouseMotionEvent
11
The object of this class represents the change in state of a window.
108 | P a g e
Lecture 31
EventListener Interfaces
An event listener registers with an event source to receive notifications about the events of a particular type.
Various event listener interfaces defined in the java.awt.event package are given below :
Interface Description
Defines the actionPerformed() method
ActionListener
to receive and process action events.
Defines five methods to receive mouse
events, such as when a mouse is
MouseListener
clicked, pressed, released, enters, or
exits a component
Defines two methods to receive
MouseMotionListener events, such as when a mouse is
dragged or moved.
AdjustmentListner Defines the adjustmentValueChanged()
method to receive and process the
109 | P a g e
adjustment events.
Defines the textValueChanged()
TextListener method to receive and process an
event when the text value changes.
Defines seven window methods to
WindowListener
receive events.
Defines the itemStateChanged()
ItemListener method when an item has been
selected or deselected by the user.
Lecture 32
The Java programming language class library provides a user interface toolkit called the Abstract Windowing Toolkit, or
the AWT.
The user interface is that part of a program that interacts with the user of the program.
Types of containers
The AWT provides four container classes. They are class Window and its two subtypes -- class Frame and class
Dialog -- as well as the Panel class. In addition to the containers provided by the AWT, the Applet class is a
110 | P a g e
container -- it is a subtype of the Panel class and can therefore hold components. Brief descriptions of each
container class provided by the AWT are provided below.
A top-level display surface (a window). An instance of the Window class is not attached to nor
Window
embedded within another container. An instance of the Window class has no border and no title.
A top-level display surface (a window) with a border and title. An instance of the Frame class may
Frame
have a menu bar. It is otherwise very much like an instance of the Window class.
A top-level display surface (a window) with a border and title. An instance of the Dialog class cannot
Dialog
exist without an associated instance of the Frame class.
A generic container for holding components. An instance of the Panel class provides a container to
Panel
which to add components.
Creating a container
Before adding the components that make up a user interface, the programmer must create a container. When
building an application, the programmer must first create an instance of class Window or class Frame. When
building an applet, a frame (the browser window) already exists. Since the Applet class is a subtype of the Panel
class, the programmer can add the components to the instance of the Applet class itself.
The code in Listing 1 creates an empty frame. The title of the frame ("Example 1") is set in the call to the
constructor. A frame is initially invisible and must be made visible by invoking its show() method.
import java.awt.*;
f.show();
Lecture 33
Canvas control represents a rectangular area where application can draw something or can receive inputs
created by user.
111 | P a g e
Class declaration
Class constructors
S.N. Constructor & Description
Canvas()
1
Constructs a new Canvas.
Canvas(GraphicsConfiguration config)
2
Constructs a new Canvas given a GraphicsConfiguration object.
Class methods
S.N. Method & Description
void addNotify()
1
Creates the peer of the canvas.
void createBufferStrategy(int numBuffers)
2
Creates a new strategy for multi-buffering on this component.
void createBufferStrategy(int numBuffers, BufferCapabilities caps)
3
Creates a new strategy for multi-buffering on this component with the required buffer capabilities.
AccessibleContext getAccessibleContext()
4
Gets the AccessibleContext associated with this Canvas.
BufferStrategy getBufferStrategy()
5
Returns the BufferStrategy used by this component.
void paint(Graphics g)
6
Paints this canvas.
void pdate(Graphics g)
7
Updates this canvas.
Methods inherited
java.awt.Component
java.lang.Object
Canvas C1 = new Canvas (); C1.setSize (120,120); C1.setBackground (Color.white); Frame F1 = new Frame
(); F1.add (C1); F1.setLayout (new FlowLayout ()); F1.setSize (250,250); F1.setVisible (true);
Lecture 34
112 | P a g e
What is an Event?
Change in the state of an object is known as event i.e. event describes the change in state of source. Events are
generated as result of user interaction with the graphical user interface components. For example, clicking on a
button, moving the mouse, entering a character through keyboard,selecting an item from list, scrolling the page
are the activities that causes an event to happen.
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.
These mechanisms 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.
1. import java.awt.*;
2. import java.awt.event.*;
3.
4. class AEvent extends Frame implements ActionListener{
5. TextField tf;
6. AEvent(){
7.
8. tf=new TextField();
9. tf.setBounds(60,50,170,20);
10.
11. Button b=new Button("click me");
12. b.setBounds(100,120,80,30);
13.
14. b.addActionListener(this);
15.
16. add(b);add(tf);
17.
18. setSize(300,300);
19. setLayout(null);
20. setVisible(true);
21.
22. }
23.
24. public void actionPerformed(ActionEvent e){
25. tf.setText("Welcome");
26. }
27.
28. public static void main(String args[]){
29. new AEvent();
30. }
31. }
114 | P a g e
Lecture 35
Introduction
Layout means the arrangement of components within the container. In other way we can say that placing the
components at a particular position within the container. The task of layouting the controls is done
automatically by the Layout Manager.
Layout Manager
The layout manager automatically positions all the components within the container. If we do not use layout
manager then also the components are positioned by the default layout manager. It is possible to layout the
controls by hand but it becomes very difficult because of the following two reasons.
Oftenly the width and height information of a component is not given when we need to arrange them.
Java provide us with various layout manager to position the controls. The properties like size,shape and
arrangement varies from one layout manager to other layout manager. When the size of the applet or the
application window changes the size, shape and arrangement of the components also changes in response i.e.
the layout managers adapt to the dimensions of appletviewer or the application window.
The layout manager is associated with every Container object. Each layout manager is an object of the class that
implements the LayoutManager interface.
Sr.
Interface & Description
No.
LayoutManager
1 The LayoutManager interface declares those methods which need to be implemented by the class whose object
will act as a layout manager.
LayoutManager2
2 The LayoutManager2 is the sub-interface of the LayoutManager.This interface is for those classes that know how
to layout containers based on layout constraint object.
Following is the list of commonly used controls while designed GUI using AWT.
Sr.
LayoutManager & Description
No.
BorderLayout
1
The borderlayout arranges the components to fit in the five regions: east, west, north, south and center.
115 | P a g e
CardLayout
2
The CardLayout object treats each component in the container as a card. Only one card is visible at a time.
FlowLayout
3
The FlowLayout is the default layout.It layouts the components in a directional flow.
GridLayout
4
The GridLayout manages the components in form of a rectangular grid.
GridBagLayout
5 This is the most flexible layout manager class.The object of GridBagLayout aligns the component
vertically,horizontally or along their baseline without requiring the components of same size.
GroupLayout
6
The GroupLayout hierarchically groups components in order to position them in a Container.
SpringLayout
7
A SpringLayout positions the children of its associated container according to a set of constraints.
Lecture 36
The java.awt.Graphics is an abstract class, as the actual act of drawing is system-dependent and device-
dependent. Each operating platform will provide a subclass of Graphics to perform the actual drawing under
the platform, but conform to the specification defined in Graphics.
The Graphics class provides methods for drawing three types of graphical objects:
1. Text strings: via the drawString() method. Take note that System.out.println() prints to the system
console, not to the graphics screen.
2. Vector-graphic primitives and shapes: via methods drawXxx() and fillXxx(), where Xxx could be
Line, Rect, Oval, Arc, PolyLine, RoundRect, or 3DRect.
116 | P a g e
3. Bitmap images: via the drawImage() method.
// Drawing lines:
drawLine(int x1, int y1, int x2, int y2);
drawPolyline(int[] xPoints, int[] yPoints, int numPoint);
117 | P a g e
Lecture 37
The RMI provides remote communication between the applications using two objects stub and skeleton.
RMI uses stub and skeleton object for communication with the remote object.
118 | P a g e
A remote object is an object whose method can be invoked from another JVM. Let's understand the stub and
skeleton objects:
stub
The stub is an object, acts as a gateway for the client side. All the outgoing requests are routed through it. It
resides at the client side and represents the remote object. When the caller invokes method on the stub object, it
does the following tasks:
skeleton
The skeleton is an object, acts as a gateway for the server side object. All the incoming requests are routed
through it. When the skeleton receives the incoming request, it does the following tasks:
Lecture 38
s we know that every top-level window has a menu bar associated with it. This menu bar consist of various
menu choices available to the end user. Further each choice contains list of options which is called drop down
menus. Menu and MenuItem controls are subclass of MenuComponent class.
119 | P a g e
Menu Hiearchy
Class declaration
Field
Class constructors
S.N. Constructor & Description
JLabel()
1
Creates a JLabel instance with no image and with an empty string for the title.
JLabel(Icon image)
2
Creates a JLabel instance with the specified image.
JLabel(Icon image, int horizontalAlignment)
3
Creates a JLabel instance with the specified image and horizontal alignment.
JLabel(String text)
4
Creates a JLabel instance with the specified text.
JLabel(String text, Icon icon, int horizontalAlignment)
5
Creates a JLabel instance with the specified text, image, and horizontal alignment.
JLabel(String text, int horizontalAlignment)
6
Creates a JLabel instance with the specified text and horizontal alignment.
120 | P a g e
The class JTextField is a component which allows the editing of a single line of text.
Class declaration
Field
static String notifyAction -- Name of the action to send notification that the contents of the field have
been accepted.
Class constructors
S.N. Constructor & Description
JTextField()
1
Constructs a new TextField.
JTextField(Document doc, String text, int columns)
2
Constructs a new JTextField that uses the given text storage model and the given number of columns.
JTextField(int columns)
3
Constructs a new empty TextField with the specified number of columns.
JTextField(String text)
4
Constructs a new TextField initialized with the specified text.
JTextField(String text, int columns)
5
Constructs a new TextField initialized with the specified text and columns
Introduction
The class JButton is an implementation of a push button. This component has a label and generates an event
when pressed. It can have Image also.
Class declaration
121 | P a g e
Class constructors
S.N. Constructor & Description
JButton()
1
Creates a button with no set text or icon.
JButton(Action a)
2
Creates a button where properties are taken from the Action supplied.
JButton(Icon icon)
3
Creates a button with an icon.
JButton(String text)
4
Creates a button with text.
JButton(String text, Icon icon)
5
Creates a button with initial text and an icon.
Lecture 39
Introduction
The class JComboBox is a component which combines a button or editable field and a drop-down list.
Class declaration
Class constructors
S.N. Constructor & Description
JComboBox()
1
Creates a JComboBox with a default data model.
JComboBox(ComboBoxModel aModel)
2
Creates a JComboBox that takes its items from an existing ComboBoxModel.
JComboBox(Object[] items)
3
Creates a JComboBox that contains the elements in the specified array.
JComboBox(Vector<?> items)
4
Creates a JComboBox that contains the elements in the specified Vector.
Jtable
public JTable() -- creates an instance of the JTable class that is initialized with a default data model, column
model, and selection model.
public JTable(TableModel dm) -- creates an instance of the JTable class that is initialized with a default
column model and selection model, and with the specified data model.
Jtree:
JTree()
JTree(Object[] value)
Lecture 40
IN Java, Memory Management means Garbage Collection and memory allocation.
Memory allocation is very small process as compared to Garbage Collection. Indeed, a well
playing Garbage collection makes everything easy for memory allocation. Only major issue
before memory allocation is Weather sufficient Memory available?. And its Garbage
Collector responsibility to ensure enough memory is available all the time, otherwise ready to a
face biggest obstacle “OutOfMemory” in running application. Writing a efficient Garbage
Collection algorithm is very tedious task. Thanks to JVM, that they come up with several
algorithms, and by default apply the best one. In day to day programming one might never feel
a need to understand those algorithms, unless you have passion for knowing whats going on
under the hood. OR some day after years of programming you face “OutOfMemory” Exception,
and then you check that there are plenty of options which can be used to avoid such situation,
for example JVM comes with several algorithms, and you start googling which one to use. After
so many years of working over Java/J2EE i really need a feel to understand those algorithms,
123 | P a g e
JVM memory management, memory sizing, and defaults.
Memory Management is all about recognizing which objects are no longer needed, freeing the memory used by such
objects, and making it available. In many modern Object oriented languages this process is automatic, and this
automatic process is called Garbage Collection. There are several Algorithms which are used by Garbage Collector.
Objects – Obja, Objb, Objx, and Objy are unreachable objects. But their reference count is one, so they can
never be collected, even though they are unreachable from stack, and they are no longer used. Reference
Counting Algorithm would surely fail in collecting some no longer used objects like Obja, Objb, Objx, and
Objy.
Lecture 41
The Cloneable interface in java is a marker interface. It does have any method. But if we write a class
as below, it gives a message to the jvm that the class can be cloned. The following code shows a
simple object cloning process.
clone() is a method in the Java programming language for object duplication. In Java, objects are
manipulated through reference variables, and there is no operator for copying an object—the
assignment operator duplicates the reference, not the object.
clone() acts like a copy constructor
Class ThreadGroup
java.lang.Object
124 | P a g e
o java.lang.ThreadGroup
All Implemented Interfaces:
Thread.UncaughtExceptionHandler
A thread group represents a set of threads. In addition, a thread group can also include
otherthread groups. The thread groups form a tree in which every thread group except the
initial thread group has a parent.
A thread is allowed to access information about its own thread group, but not to access
information about its thread group's parent thread group or any other thread groups.
o Constructor Summary
Constructors
onstructor and Description
ThreadGroup(String name)
Constructs a new thread group.
ThreadGroup(ThreadGroup parent, String name)
Creates a new thread group.
Runnable:
And already discussed in Thread topics.
125 | P a g e