Sunteți pe pagina 1din 42

Tutorial on Java

Page |1

What is data abstraction?


Object Oriented Programming has a special feature called Data Abstraction. Data abstraction
means to, providing only essential features and to hide its background details. That is to represent
the needed information in program without presenting the details. While defining a class, both
member data and member functions are described. However while using an object the built in data
types and the members in the class are ignored. This is known as data abstraction.

Features of Object Oriented Programming


The main features of object oriented programming are data abstraction, encapsulation,
inheritance and polymorphism. They are described below:
Abstraction: Data abstraction refers to, providing only essential information to the outside world
and hiding their background details, i.e., to represent the needed information in program without
presenting the details.
Encapsulation: In general, encapsulation is the inclusion of one thing within another thing so that
the included thing is not visible. Encapsulation is an Object Oriented Programming concept that
binds together the data and functions that manipulate the data. Thus the data and functions can
be kept safely from outside interference and misuse. Data encapsulation means data hiding also.
Inheritance: One of the most useful aspects of object-oriented programming is code reusability.
As the name suggests Inheritance is the process of forming a new class from an existing class.
The existing class called as base class and the new class formed from the base class is called as
derived class. As a result the properties of the base class are not re-written in the child class. This
is a very important concept of object-oriented programming since this feature helps to reduce the
code size. Inheritance defines relationship among classes in an object-oriented language.
Polymorphism: The ability to use an operator or function in different ways is called
polymorphism. In other words giving different meaning or functions to the operators or functions is
called polymorphism. Poly means many. In OOP we can define more than one functions by the
same name is a class or in base class and child class. Though the name of the functions is same
but they can perform different tasks. This feature is called polymorphism.

Why Is Java Called Pure Object Oriented Programming Language?


Java is a programming language that uses Object in each of its programs. In each java program
we have to create classes and in the main function of java we have to create objects of the
classes. You can write a C++ program without creating a class but we have to create class and
objects in each java program. Moreover, all concepts of object oriented programming language,
like inheritance, polymorphism, and encapsulation are supported by java. Thats why java is called
"purely" object oriented programming language.

What is Byte Code?


After compilation of a java program, a .class file is created which is written in bytecode. Bytecode
is an intermediate code which is produced by the Java compiler by compiling that source code.
This byte code is a machine independent code. It is not completely a compiled code but it is an
intermediate code which is later interpreted and executed by JVM.

What is JVM?
JVM is a platform-independent execution environment that converts Java bytecode into machine
language and executes it. Java was designed to write programs that can be executed on any

Tutorial on Java

Page |2

platform without compiling for each separate platform. A Java virtual machine makes it possible
because it is aware of the particular platform and translates the byte code into machine code
according to that platform. Once a Java virtual machine has been implemented for a given
platform, any Java program can run on that platform.

Why java is called platform independent language?


Java is a platform independent programming language. It means that, after compilation, the same
java program can be executed on any platform or operating system without any change. The java
compiler compiles a java program and produces a .class file which is written in byte code. Byte
code is not executable code. The byte code is interpreted and executed by the java runtime
system which is called Java Virtual Machine (JVM). The .class file (written in byte code) can be
interpreted and executed by any computer under any operating system, only if JVM is installed
there. That is once compiled; the .class file can be executed in any platform. Hence java is called
a platform independent language.

WHAT

IS A CLASS?

A class is a blueprint or skeleton of a real entity. A class can be defined as a template /blue print
that describe the behaviors/states of object of that type. Technically speaking, defining a class
means to define a new data type. That is a class is a user defined data type. A class is virtual in
nature.
While defining a class we have to define some variables and some methods within the class.
Those variables and methods are called the members of the class.

WHAT

IS AN

OBJECT?

The real implementation of a class is called an object. An object is the real thing which possesses
all the features declared in a class. All the objects of a class are identical. In fact an object is a
class type variable. The term object, is also known as instance of a class.
After compilation of a java program, a .class file is created. A java program can have several user
defined classes and individual .class file is created for each of the classes. Let a java program
contains four user defined classes named class A, class B, class C and class D. after compilation
of the program four .class file named, A.class, B.class, C.class, D.class will be created. All the
classes can have their own main () method also.

COMPILATION AND EXECUTION OF A JAVA PROGRAM


In java, both compiler and interpreter are used. At first the program is compiled and then the .class
file is interpreted by an interpreter.
Compiler javac.exe
Interpreter java.exe
1) Write a Java in Notepad and save it with the extension .java
2) Compile he program using the java compiler javac as below:
>javac <file name.java>

Tutorial on Java

Page |3

That is if the name of the file is Asansol.java then it has to be compiled as


>javac Asansol.java
3) After successful compilation .class file will be created. The program will be executed using
the interpreter of java.exe as below:
>java <name of the .class file containing the main () method>

PACKAGE
A Package can be defined as a collection of related classes and interfaces for better organization.
It is also useful to avoid naming conflict and to control access to various classes and interfaces.
Some of the predefined packages in java are given below:
java.lang
java.io
java.net
java.util
java.applet
java.awt
java.awt.event
java.sql etc.
If we want to use any particular class or interface from a package, then we have to include that
package to our program using the import statement. In C language, if we want to use a function
then we have to include the entire header file. But in Java either we can import a particular class
from a package or we can import the entire package.
1) To import a particular class from a package, the syntax is: import packagename
.classname;
For example; if we want to import the Button class from the java.awt package, then we have
to write:
import java.awt.Button;
2) To import an entire package, the syntax is: import packagename.*;
For example; if we want to import the java.awt package, then we have to write: import
java.awt.*;

ADVANTAGE

OF

PACKAGE

Package is used to categorize the classes and interfaces so that they can be easily
maintained.
Package provides access protection.
Package removes naming collision.
The java.lang package is automatically imported in all java programs

FILE

CREATION

RULES

We can define several classes in a java program and those user-defined classes can be
organized in a user defined package. If the user-defined classes are stored in a package,
then all the user-defined classes of a java program must be stored in a single package.
That is the user defined classes of a java program cannot be stored in different packages. If
the use defined classes are stored in a package, then the very first statement of the
program must be,
package package-name;
If we dont want to store the user defined classes of a java program in a package, then the
package statement is not required. So, the package keyword is optional in a java program

Tutorial on Java

Page |4

and if it is used then it can be used only once and it must be the first statement of the
program.
As already stated, the java.lang package is automatically imported in all java programs. If
any other package is required then that package is included using the import statement
which must appear just after the package statement (if the package statement exists at all).
If the package statement does not appear in a program then the import statement will be
the first statement of the program. That is import statement is also optional as it may not be
required to import any other package other than java.lang. But one can import as many
packages as needed and they can be imported in any order.
After the package and the import statement, we have to define the classes required.
That is the basic skeleton of a java program is as below:
package - Optional
import - Optional
import
------------import
class A
{
}
class B
{
}

FILE NAMING RULES:


A java program can have several user defined classes, but only one of them can be declared as
public. I f a class is declared as public in a program then the name of the file must be same as the
name of that public class. That is if a program contains four classes named, class A, class B, class
C and class D, and class B is declared as public, then the name of the file must be B.java,
otherwise it will be a compilation error.
If none of the classes in a program is public then the program can have any name.

RULES

FOR IDENTIFIER:

An identifier must start with a letter, a currency character ($), or the underscore (_).
Identifiers cannot start with a number.
After the first character, identifiers can contain any combination of letters, currency
characters ($), underscore (_), or numbers.
There is no limit to the number of characters in an identifier.
A Java keyword cannot be used as an identifier.
Identifiers in Java are case-sensitive; rate and RATE are two different identifiers.

ACCESS SPECIFIERS

IN

JAVA

Access Specifiers (also known as Visibility Specifiers) control access to classes, variables and
methods in Java. These Specifiers determine whether a variable or method in a class, can be
used or invoked by another method in another class or sub-class. Access Specifiers can be used
to restrict access. Access Specifiers are an integral part of object-oriented programming. The four
access levels are:
Visible to the package. the default. No modifiers are needed.

Tutorial on Java

Page |5

Visible to the class only (private).


Visible to the all (public).
Visible to the package and all subclasses (protected).

KEYWORDS

IN

JAVA

There are some words that cannot be used as object or variable names in a Java program. These
words are known as reserved words or keywords. They are called keywords as they are
already defined by the Java programming language.
Here is a list of keywords in the Java programming language. We cannot use any of the following
as identifiers in our programs. The keywords const and goto are reserved, even though they are
not currently used. true, false, and null might seem like keywords, but they are actually literals.
Here is a complete list of the keywords in java:
abstract
char
double
For
Int
private
strictfp
throws

DATA

boolean
class
else
goto
interface
protected
super
transient

TYPES IN

break
const
extends
If
long
public
switch
try

byte
continue
final
implements
native
return
synchronized
void

case
default
finally
import
new
short
this
volatile

catch
do
float
instanceof
package
static
throw
while

JAVA

There are eight primitive data types supported by Java. Primitive data types are predefined by the
language and named by a keyword.
Data Type
Byte
Short
Int
Long
Float
Double
Char
boolean

Size(in Byte)
1
2
4
8
4
8
2
1

Default Value
0
0
0
0
0.0
0.0
null
false

Instance variables:
Instance variables are variables within the objects. Every time we create an object from a class, a
new copy of these instance variables is created for this object. So each object has its own copy of
instance variables which exist as long as the object exists.

Default Access Modifier - No keyword:


If a variable or method is declared without any access specifier then it is said to have default
access. A variable or method declared without any access control modifier is available to any
other class in the same package. That is if we do not specify any access specifier, then such a
class, method, or variable will be accessible from inside the same package to which the class,
method, or variable belongs, but not from outside this package.

Private Access Modifier - private:


It is the most restricted access specifier. Methods, Variables and Constructors that are declared
private can only be accessed within the declared class itself. Private access modifier is the most
restrictive access level. Private methods and variables are not visible within subclasses and are
not inherited by subclasses. So, the private access specifier is opposite to the public access

Tutorial on Java

Page |6

specifier. Classes and interfaces cannot be private. Using the private modifier an object
encapsulates data and hides data from the outside world.

Public Access Modifier - public:


A class, method, constructor, interface etc. declared as public can be accessed from any other
classes. Therefore variables, methods, blocks declared inside a public class can be accessed
from any other class belonging to the Java Universe.
However if the public class we are trying to access is in a different package then we have to import
that public class. A public member has maximum accessibility and minimum security.

Protected Access Modifier - protected:


A member declared as protected in a class can be accessed only by
i) Any classes within the same package of the protected members' class and by
ii) The subclasses even if the subclass is in other package.
The protected access modifier cannot be applied to class and interfaces. Methods, variables
can be declared protected, however methods and fields in an interface cannot be declared
protected.
The following table summarizes the given concept:
Access Specifier
default
Accessible inside the class
Yes
Accessible within the subclass inside the Yes
same package
Accessible outside the package
NO
Accessible within the subclass outside the NO
package

private protected public


Yes
Yes
Yes
NO
Yes
Yes
NO
NO

NO
Yes

Yes
Yes

In short the accessibility can be described as below:


private
default
protected
public

Within the same Class only


Within all the classes of the same package Within all the classes of the
same package as well as within the
sub-class also even if the subclass is in other package
Everywhere

So in terms of accessibility, public>protected>default>private.


But in terms of restriction, private>default>protected>public

DECLARING

CLASSES AND OBJECTS:

Let us look at the way of creation of a class and an object. Say we want to create a class named,
Room as below:
class Room
{
int I , b, h;
void volume ()
{
int v;
v=l*b*h;
System.out.println (The volume is +v);
}
}

Tutorial on Java

Page |7

Here Room is a class (that is a data type) which has four members; three variables and a
method. After declaring the class we can create objects from that class as below:
Room r;

Here r is a Room type variable which can store the address (reference) of an
object of Room class. As it can store reference, hence it is called a reference
variable.

r=new Room ()

this statement creates the real object. The new keyword in java is used to
create a new instance of a class (that is an object) or an array. When the new
keyword is used:

A new instance of the given class is created


Memory is allocated for it
a constructor is called

INSTANCE VARIABLE
When a number of objects are created from a class, all of them have their own distinct
copies of instance variables. That is an instance variable is a variable which has its own individual
copy in each objects of that class.
Instance variables are declared in a class, but outside a method, constructor or any block.
When a space is allocated for an object in the heap, memory space for each instance
variable is allocated.
Instance variables are created when an object is created with the use of the keyword new
and destroyed when the object is destroyed.
Access modifiers can be given for instance variables.
The instance variables are visible for all methods, constructors and block in the class.
Normally, it is recommended to make these variables private.
Instance variables are initialized with default values.
Instance variables can be accessed directly by calling the variable name inside the class. However
within different class (when instance variables are given accessibility) should be called using the
fully qualified name, i.e. ObjectName. VariableName.
In the above example, if several objects of the Room class are created, then all of them will have
the variables l, b and h. Here those variables are instance variable. That is memory space for an
instance variable is allocated whenever an object is created.
Hence the pictorial representation of the statement r=new Room () will be as below:

CONSTRUCTOR:
A constructor is a method which is automatically called whenever an object of a class is created. A
constructor has the following features:

It is automatically called when an object is created.


It initializes the instance variables of an object as soon as the object is created.
The name of the constructor must be same as the name of the class.

Tutorial on Java

Page |8

As long as no constructor is defined in a class, JVM will supply a default constructor which
initializes the instance variables with the default values mentioned above. As soon as a
constructor is defined, supply of the default constructor is stopped.
A constructor can be parameterized or without any parameter. A constructor without any
parameter is called an EMPTY CONSTRUCTOR. Be careful of the fact that empty constructor
and default constructor are not the same. A default constructor is supplied by the JVM but an
empty constructor is defined in a class. Even if an empty constructor is defined in a class, JVM will
not supply the default constructor.
Look at the following program to find out the sum of two numbers:
Sumation.java
class A
{
int x, y;
A (int a, int b)
{
x=a;
y=b;
}
void sum()
{
int s;
s=x + y;
System.out.println ("The sum is "+s);
}
}
class B
{
public static void main (String s[])
{
A obj=new A (10, 20);
obj. sum();
}
}
Here the class A contains two instance variables x and y and a method sum (). To initialize the
instances variables, a constructor with two parameters has been defined. When an object is
created, the constructor is called. It initializes the instance variables x and y. the sum method is
called with that object and it finds out the sum of those two variables. The program is compiled as
below:
>javac Summation.java
But it is executed using the class B, as class B contains the main () method.
>java B

STATIC KEYWORD
In java we can declare a variable either in a class or in a method. A variable declared in a method
is called a local variable and it is accessible within that method only. Variables declared in a class
can either be an instance variable or a static variable

Tutorial on Java

Page |9

Static is a very important keyword and can be applied to


Variable, declared in a class
Method
Inner class

STATIC VARIABLE
Static variables also known as Class variables are declared with the static keyword in a class, but
outside a method, constructor or a block. There will only be one copy of each static variable for
each class, irrespective of how many objects are created from it. Memory space for an instance
variable is allocated whenever an object of that class is created and each object will have its own
instance variable. Moreover the instance variables always reside within an object and instance
variables cant exist unless and until an object is created. On contrary, a static variable can exist
without the existence of an object, even a static variable can exist before creation of any object. A
static variable is not a member of an object of a class and it does not reside within an object of the
class. Let us take an example:
class ABC
{
int x, y; //Instance variable
static int p; //Static variable
}
Now create some object of that class.
ABC obj1=new ABC ();
ABC obj2=new ABC ();
Here we have created two objects of the class. The memory representation is like below:

From the diagram it is clear that there are individual copies of each instance variable for each
object, but there will be only one copy for a static variable for the entire class.
Whenever a .class file is loaded by the ClassLoader class, memory space for the static variables
is allocated. A static variable is automatically initialized with the default value according to its data
type.

USING

A STATIC VARIABLE IN THE CLASS IN WHICH IT IS DECLARED:

The following example shows how to use a static variable in a class in which it has been declared:
class A
{
int x, y;
static int p;

Tutorial on Java

void sum()
{
int s=x+y;
System.out.println("The sum is "+s);
}
public static void main(String s[])
{
p=18;
A obj=new A();
obj. x=4;
obj. y=9;
obj. sum();
System.out.println("p= "+p);
System.out.println("x= "+obj. x);
}

P a g e | 10

A static variable declared in a


class can be used by the name of
the variable in the same class.

Instance variables must be used


with the object.

}
In the given example, p is a static variable but x and y is instance variables. The static variable p
can be used in the same class just using the name of the variable, but instance variables must be
used with the object name only.

DECLARING A STATIC VARIABLE IN A CLASS AND USING IN ANOTHER CLASS:


class A
{
int x, y;
static int p;
void sum()
{
int s=x+y;
System.out.println("The sum is "+s);
}
}
class B
{
public static void main(String s[])
{
A.p=18;
A obj=new A();
obj. x=4;
obj. y=9;
obj. sum();
System.out.println("p= "+A. p);
System.out.println("x= "+obj. x);
}
}

A static variable of a class can


be used in another class using
the name of the declaring
class.

Instance variables must be


used with the object.

A static variable declared in a class can be used in another class using the name of its declaring
class. Here the static variable p of class A is used in class B as A. p. But instance variables are
always used with an object name.

Static Method
Normally you can't call a method of a class without creating an object of that class. By declaring a
method as static, we can call it without creating an object because it becomes a class method (i.e.
a method that belongs to a class rather than an object). A static method has the following features:

Tutorial on Java

P a g e | 11

A static method belongs to the class rather than object of a class.


A static method can be invoked without creating an object of a class.
Static method can access static data member and can change the value of it.
A static method cannot use non-static variable or cant call any non-static method.
The this and super keywords cant be used in a static method.

Using a static method in the class in which it is declared:


class Static1
{
int x;
static int p;
static void show()
{
System.out.println(p);
//x=5; compilation error, as static method cant use instance variable.
}
A non-static method can use both
void abc()
static and non-static variables.
{
System.out.println("x= "+x);
System.out.println("p= "+p);
}
A static method called in the
static public void main(String s[])
containing class using the method
{
name only
p=10;
show();
Static1 s1=new Static1();
A non-static method must be called
Static1 s2=new Static1();
with the object of that class.
s1.x=100;
s2.x=50;
s1.abc();
s2.abc();
System.out.println(s1.x);
As there is only one copy of a static
System.out.println(s1.p);
variable for the entire class, so s1.p,
System.out.println(s2.p);
s2.p and p refer to the same
s1.p=s2.p+p;
variable.
System.out.println("Now p= "+s1.p);
}
}
main () of a java program is public and static-Explain.
When a class member is declared as public, then that member can be accessed by code outside
the class in which it is declared. In this case, main must be declared as public, since it must be
called by code outside of its class when the program is started.
A static method can be called without an object. The main () is the starting point of execution of a
java program. That is, main () is always called without an object. Hence main () must be declared
as static.

Method Overloading
Method overloading is a very important concept in Java. It allows Java programmer to declare
more than one method with same name but different behavior. Method overloading is based on
polymorphism. Method overloading is resolved using static binding in Java at compile time.

Tutorial on Java

P a g e | 12

In object oriented programming, it is possible to define more than one method with the same name
in a class. This feature is known as method overloading and those methods are called overloaded
methods.
The return type of the overloaded methods may be same or may not be same. In fact the return
type of the methods has no role to play in method overloading. But eitheri) Number of parameters or
ii) The data type of the parameters or
iii) The sequence of the parameters
Of the overloaded methods must be different. It means that the overloaded methods can
perform similar type of operations on different data type.
The following example demonstrates the concept of method overloading.
class Addition
{
void sum(int x, int y)
{
int s=x+y;
System.out.println ("The sum is "+s);
}
void sum(int x, double y)
{
double s=x+y;
System.out.println ("The sum is "+s);
}
void sum(double x, int y)
{
double s=x+y;
System.out.println ("The sum is "+s);
}
int sum(int x, int y, int z)
{
int s=x+y+z;
return s;
}
}
class OverloadMethod
{
public static void main(String s[])
{
int p;
Addition a1=new Addition ();
p=a1. sum (10,20,30);
(1)
System.out.println ("The sum is "+p);
a1.sum (12.5, 18);
(2)
a1.sum (16, 39);
(3)
a1.sum (10, 2.5);
(4)
}
}
The above example contains four methods called sum (). They are overloaded methods. Among
them return type of three of the methods is void and the return type of the fourth one is int.
(1)
(2)

The sum () method with three integer parameters has been called.
The sum () method with one double and one integer parameter has been called.

Tutorial on Java

(3)
(4)

P a g e | 13

The sum () method with two integer parameters has been called.
The sum () method with one integer and one double type parameter has been called.

The this keyword


The this keyword is used for several purposes in java. There can be a lot of usage of this
keyword. In java, this is a reference variable that refers to the current object. Within an instance
method or a constructor, this is a reference to the current object the object whose method or
constructor is being called. You can refer to any member of the current object from within an
instance method or a constructor by using this.

Usage of this keyword


Here is given the 6 usage of this keyword.
1. this keyword can be used to refer current class instance variable.
2. this () can be used to invoke current class constructor.
3. this keyword can be used to invoke current class method (implicitly)
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this keyword can also be used to return the current class instance.
The this keyword can be used to refer to the instance variable of the

current class
in a class, the name of a parameter of a method may be same as the name of an instance variable
of that class. Then within the method, there will be an ambiguity between the instance variable and
the local variable, i.e. the parameter of the method. This ambiguity can be resolved using the this
keyword. The this keyword will refer to the instance variable of the class. Look at the following
example:
class ThisDemo
{
int x, y;
ThisDemo (int x, int z)
{
this. x=x;
y=z;
}
}
Here the constructor has a parameter x and the class has an instance variable x. so within the
constructor this.x refers to the instance variable x and x refers to the local variable x. in this
fashion this keyword can resolve the ambiguity. If local variables (formal arguments) and
instance variables are different, there is no need to use this keyword.

this() can be used to invoked current class constructor


If a class has several constructors, then this () can call a constructor of the class in another
constructor of the same class. Only this () will call the empty constructor of the same class
whereas this (parameters) will call a parameterized constructor of the same class. The
following example demonstrates it.
class Student
{
String name, add;
int age, roll;
Student (String s1, String s2)
{

Tutorial on Java

P a g e | 14

name=s1;
add=s2;
}
Student (String p, String q, int a, int r)
{

this (p, q);


age=a;
roll=r;
}
void show ()
{
System.out.println ("Name: "+name);
System.out.println ("Address: "+add);
System.out.println ("Age: "+age);
System.out.println ("Roll: "+roll);
}
}
class ThisDemo
{
public static void main (String s[])
{
Student s1=new Student("Amit","Asansol");
Student s2=new Student("Kunal","Kulti",21,34);
s1.show();
s2.show();
}
}
The this (p, q) used in a constructor of Student class will invoke another constructor of the
Student class which accepts two integer parameters. This approach is better if we have many
constructors in the class and want to reuse that constructor.

STRING Class
The String class of java.lang package represents character strings. All string literals in Java
programs, such as "abc", are treated as instances of String class. Strings are constant; their
values cannot be changed after they are created. The String class is final, i.e. we cannot inherit
the String class.
Constructors:
The String class supports several constructors. They are described below:
1 To create an empty String, we call the default constructor. For example,
String s = new String (); will create an object of String class with no characters in it.
2 String (char p[ ]) It will create an object of String class and initializes the object with an array
of characters. For example:
char p[] = { 'a', 'b', 'c' };
String s = new String (p); The constructor initializes the string with abc.
3 You can specify a sub-string of a character array to initialize a string using the following
constructor:
String(char p[ ], int startIndex, int numChars)
Here, startIndex specifies the index at which the sub-string begins, and numChars specifies the
number of characters to use. Here is an example:
char p[] = { 'a', 'b', 'c', 'd', 'e', 'f' };

Tutorial on Java

P a g e | 15

String s = new String(chars, 2, 3);


It creates a string and initializes the string with cde.
4 You can construct a String object that contains the same characters as another String object
using this constructor: String(String strObj);
class MakeString
{
public static void main(String s[])
{
char c[] = {'J', 'a', 'v', 'a'};
String s1 = new String(c);
String s2 = new String(s1);
System.out.println(s1);
System.out.println(s2);
}
}
The output from this program is as follows:
Java
Java
5 A simple String can be created using a string literal enclosed inside double quotes as shown;
String str1 = Learning Java;
String Pool
String Pool is a pool of Strings stored in heap memory. We know that we can create String object
using new operator as well as providing values in double quotes. Here is a diagram which clearly
explains how String Pool is maintained in java heap space and what happens when we use
different ways to create Strings.

When we use double quotes to create a String, it first looks for String with same value in the String
pool, if found it just returns the reference else it creates a new String in the pool and then returns
the reference.
However if a string is created using new operator, then a new string object is created. Here is an
example:
Output of the above program is:
s1 == s2: true
s1 == s3: false
class StringPool
{
public static void main(String[] s)
{
String s1 = "Cat";
String s2 = "Cat";
String s3 = new String ("Cat");

Tutorial on Java

P a g e | 16

System.out.println ("s1 == s2 :"+( s1==s2));


System.out.println ("s1 == s3 :"+( s1==s3));
}
}
Methods:
1. char charAt(int index)
It returns the character at the specified index.
String str ="study to night";
System.out.println (str. charAt (2));
Output: u
2. boolean equalsIgnoreCase(String s)
Determines the equality of two Strings, ignoring their case (upper or lower case doesn't matters
with this function).
String str = "java";
System.out.println (str. equalsIgnoreCase ("JAVA"));
Output: True
3. int length ()
The function returns the number of characters in a String.
String str=This is a String;
int len=str.length();
System.out.println (Length is +len);
Output: Length is 16
4. String concat (String str)
Concatenates the specified string to the end of this string.
class StringDemo1
{
public static void main(String s[])
{
String s1="Java";
String s2=s1.concat ("World");
System.out.println (s1);
System.out.println (s2);
}
}
Output:
Java
JavaWorld
5. int compareTo(String str)
This method compares two Strings and returns an int value. It returns
i)
0, if this string is equal to the string argument
ii)
a value less than 0, if this string is less than the string argument
iii)
a value greater than 0, if this string is greater than the string argument
class StringDemo2
{
public static void main(String s[])
{
String s1="Dog";
String s2="Lion";
int N1=s1.compareTo(s2);
int N2=s2.compareTo(s1);
System.out.println ("N1= "+N1);

Tutorial on Java

P a g e | 17

System.out.println ("N2= "+N2);


}
}
Output:
N1= 8
N2= -8
6. int compareToIgnoreCase(String str)
Compares two strings, ignoring case differences and returns same type of values.
7. String substring(int index)
The method returns a new string which is a substring of this string. The substring begins from the
given index.
class StringDemo3
{
public static void main(String s[])
{
String s1="God is Great";
String s2=s1.substring(4);
System.out.println(s2);
}
}
Output:
is Great.
8. String substring(int beginIndex, int endIndex)
The method returns a new string that is a substring of this string. The sub-string begins from the
index beginIndex and ends at (endIndex-1).
class StringDemo4
{
public static void main(String s[])
{
String s1="God is Great";
String s2=s1.substring(4,8);
System.out.println(s2);
}
}
Output:
is G
9. String toUpperCase()
Converts all of the characters in this String to upper case and returns a new string.
10. String toLowerCase()
Converts all of the characters in this String to lower case and returns a new string.
Concatenation of Strings
Apart from concat() method, two strings can be appended using the + operator also. For example,
String s = "Hello" + "World";
System.out.println(s);
Output:
HelloWorld.
Look at the following example:
String s = "Java";
s = s + "World";

Tutorial on Java

P a g e | 18

From the above example, it looks like the string has been modified. But we know that string cannot
be modified and here practically the string has not been modified. Actually here an object of
StringBuffer class is created. The procedure is given below:
1.
2.
3.
4.
5.
6.

A StringBuffer object is created


The 1st string, i.e., Java is copied to the newly created StringBuffer object.
The 2nd string, i.e., World is appended to the StringBuffer (concatenation)
The result is converted to back to a String object.
Now the reference variable s refers to that new String.
The old String, that s previously referenced, is then made null.

toString () Method
The toString() method of Object class is used when we need a string representation of an object.
This method can be overridden to get the String representation of an Object. Whenever we want
to concatenate any other primitive data type, or object of other classes with a String object,
toString() method is called automatically to change the other object or primitive type into string. For
example:
int age = 10;
String str = "He is" + age+ "years old.";
In above case 10 will be automatically converted into string for concatenation using valueOf()
method.
A number can be converted in to string using the valueOf() method of String class. It can take any
of the primitive data type numbers as an argument and produce a String:
int x= 20;
String s = String. valueOf(x);
It converts the value of x from int to string and stores the string
value in s. We can use the toString method of any of the wrapper classes:
String s = Integer. toString(x);

StringBuffer Class
An object of String class is immutable, i.e., once created, an object of String class cannot be
changed. Thats why the StringBuffer class is introduced. An object of StringBuffer class is
mutable, i.e., after creation, the object can be modified.
An object of StringBuffer class can be changed dynamically. StringBuffer class is preferred when
the string needs several modifications(appending, inserting, deleting, modifying etc.).
Constructor
1 StringBuffer ()
Constructs a string buffer with no characters in it and an initial
capacity of 16 characters.
2 StringBuffer (int capacity)
Constructs a string buffer with no characters in it and the
initial capacity of the string buffer is mentioned.
3 StringBuffer (String str) Constructs an object of StringBuffer class which is initialized
with the contents of the given string and reserves space for 16 more characters.
Methods

capacity()
The capacity() function returns the current capacity of the StringBuffer object. The capacity of an
empty StringBuffer object is 16. But the capacity of a non-empty StringBuffer object is (number of
characters+16). Look at the following example:
class StringBuffer1

Tutorial on Java

P a g e | 19

{
public static void main(String s[])
{
StringBuffer sb1=new StringBuffer();
StringBuffer sb2=new StringBuffer("HELLO");
System.out.println("Capacity is "+sb1.capacity());
System.out.println("Capacity is "+sb2.capacity());
}
}
Output is :
Capacity is 16
Capacity is 21

ensureCapacity (int x):


The method is used to set the capacity to the given value. Look at the following example:
class SB
{
public static void main(String s[])
{
StringBuffer sb=new StringBuffer();
System.out.println("Capacity is "+sb.capacity());
sb.ensureCapacity(40);
System.out.println("Now Capacity is "+sb.capacity());
}
}
Output:
Capacity is 16
Now Capacity is 40
append()
This method will append the string representation of any type of data to the end of the invoking
StringBuffer object. append() method has several overloaded forms. After appending the
parameter with the invoking object, it returns another object of StringBuffer class.
class SB
{
public static void main(String s[])
{
StringBuffer sb=new StringBuffer("Hello");
sb.append("Java");
System.out.println("sb= "+sb);
int x=123;
sb.append(x);
System.out.println("sb= "+sb);
}
}

insert( )
The method inserts one string into another. It is overloaded to accept all primitive types, plus
Strings. It calls String.valueOf ( ) to obtain the string representation of the supplied value. This
string is then inserted into the invoking StringBuffer object. These are a few of its forms:
StringBuffer insert (int index, String str)

Tutorial on Java

P a g e | 20

StringBuffer insert (int index, char ch)


class SB4
{
public static void main(String s[])
{
StringBuffer sb=new StringBuffer("I Indian");
sb.insert(2,"am ");
System.out.println("Now the string is "+sb);
}
}
Output: I am Indian

reverse ( )
We can reverse the characters within a StringBuffer object using reverse ( ). This method returns
the reversed object on which it was called, i.e. the original string is reversed. The prototype is
StringBuffer reverse ( )
class SB5
{
public static void main (String s[])
{
StringBuffer sb=new StringBuffer ("HELLO");
System.out.println ("sb "+sb);
System.out.println ("The reversed string is "+sb.reverse ());
System.out.println ("Now sb= "+sb);
}
}
Output:
sb=HELLO
The reversed string is OLLEH
Now sb= OLLEH

delete ( ) and deleteCharAt ( )


The methods delete ( ) and deleteCharAt ( ) can delete a set of characters or a particular
character from a string buffer object.
StringBuffer delete (int x, int y)
StringBuffer deleteCharAt (int x)
The delete ( ) method deletes a set of characters from the invoking object. It deletes all the
characters from index x to the index (y-1). After deleting the characters, the remaining StringBuffer
object is returned.
The deleteCharAt ( ) method deletes the character at the index specified by x. It returns the
resulting StringBuffer object.

replace( )
It replaces one set of characters with another set of characters inside a StringBuffer object.
StringBuffer replace (int x, int y, String str)
The substring from index x to index (y1) is replaced by the string str. After replacement the new
StringBuffer object is returned.
class SB6

Tutorial on Java

P a g e | 21

{
public static void main(String s[])
{
StringBuffer sb=new StringBuffer("I am Indian");
System.out.println("After replacement the string is "+sb.replace(2,4,"are"));
}
}
Output: After replacement the string is I are Indian.

substring ( )
The substring ( ) method returns a portion of a StringBuffer. It has the following two forms:
String substring (int x)
String substring (int x, int y)
The first form returns the substring that starts at the index x and runs to the end of the invoking
StringBuffer object. The second form returns the substring starting from index x to index (y1).
class SB7
{
public static void main(String s[])
{
StringBuffer sb=new StringBuffer ("I am Indian");
System.out.println ("sb.substring (5) = "+sb. substring (5));
System.out.println ("sb.substring (5,9)= "+sb.substring(5,9));
}
}
Output:
sb.substring (5) = Indian
sb.substring (5, 9) = Indi
Difference between String & StringBuffer
String
It implements the interfaces Serializable,
CharSequence and Comparable
An object of String class is immutable, that is,
once created a string object cannot be
changed.
A string object is stored in the Constant String
Pool.
After creation, the size of a String object cant
be changed.

StringBuffer
It implements the interfaces Serializable,
CharSequence and Appendable
An object of StringBuffer is mutable i.e. we
can change the value of the object.
An object of StringBuffer is stored in the heap.
After creation, the size of a StringBuffer object
can be changed.

What is an interface? How does it differ from a class?


In Java, an interface is like a class, but we can only declare methods and variables in the
interface. In an interface all the methods are public, static and abstract and all the variables are
public and static. Thus an interface is a collection of abstract methods. If a class implements an
interface, then it inherits the abstract methods of the interface. We cannot actually implement the
methods. Interfaces are a way to achieve polymorphism in Java.
An interface also declares variables and methods like a class. But there is several differences
between them. They are as below:

Class

Interface

Tutorial on Java

The variables may be public and static or


may not.
The methods may be public, static and
abstract or may not be.
We can create an object of a class except an
abstract class.
A class may have a constructor.
A class can extend a single class.

P a g e | 22

The variables must be public and static only.


The methods must be public, static and
abstract.
We can never create an object of an
interface.
An interface cant have a constructor.
An interface can extend multiple interfaces.

How do you define and access member of an interface? Explain with an example. 5
The variables declared in an interface are public, static and final by default, and the methods are
public and abstract. That is we can only declare a method in an interface but it cannot be defined.
If a class implements the interface, then the class has to override the methods of the interface.
The variables of the interface can be used with the name of the interface using . (dot) operator. Let
us take an example where the members of an interface have been used by a class:
interface Address
{
They are public static and
String city="Asansol";
final by default
int pin=713305;
void show();
}
class Employee implements Address
{
String name, dept;
Employee (String n, String d)
{
name=n;
dept=d;
}
public void show()
{
System.out.println ("Name is "+name);
System.out.println ("Department is "+dept);
System.out.println ("Lives in "+Address.city);
System.out.println ("Pin code is "+Address.pin);
}
}
class InterfaceDemo
{
public static void main(String s[])
{
Employee e1=new Employee ("Bijay, Sales");
Employee e2=new Employee ("Ravi","Finance");
e1.show ();
e2.show ();
}
}
The interface has two variables. They are public, static and final, though the variables have not
been declared as public, static and final. The Employee class can use the variables as
Address.city and Address.pin as they are static. Similarly, the Employee has overridden the
show () method of the interface and after that the method has been called with object of Employee
class.

Tutorial on Java

P a g e | 23

Inheritance
Inheritance means to acquire the properties of an existing class. If class B inherits from class A,
then A is called super class and B is called subclass. If class B inherits from class A, then class B
can use the variables and methods of class A. But a subclass cant inherit the following properties
of the super class:
1. The private members of the super class
2. Constructors of the super class.
Whenever an object of the subclass is created, before execution of the subclass constructor, the
constructor of the super class must be executed. If class B inherits from class A and class C
inherits from class B and an object of class C is created, then the constructors are executed in the
following order:
i) Constructor of class A
ii) Constructor of class B
iii) Constructor of class C
If the super class and the subclass do not have any constructor, then before execution of the
default constructor of the subclass, the default constructor of the super class is executed.
If the super class has an empty constructor, then before execution of the constructor of the
subclass, the empty constructor of the super class is executed.
If the super class has some constructors but does not have an empty constructor, then before
execution of the subclass constructor, any one of the super class constructors must be called
using the super keyword.
The super keyword
The super keyword is associated with Inheritance. Inheritance is a concept of Object Oriented
Programming where in the sub class inherits characteristics and properties of the super class. The
base class is also called as super class. The various usage of the super keyword is as below:
i) super is used to refer to the instance variable of the immediate parent class.
ii) super() is used to invoke constructor of the immediate parent class.
iii) super is used to invoke method of immediate parent class.
super is used to refer immediate parent class instance variable.
If the subclass has an instance variable with the same name as an instance variable of the super
class, then to resolve the naming conflict within the subclass, the super keyword is used with
the instance variable of the super class. Similarly, the super class method can be called within the
subclass method using the super keyword. let us take an example:
class A
{
int x, y;
A (int p, int q)
{
x=p;
y=q;
}
void sum ()
{
int s=x+ y;
System.out.println (The sum is +s);
}
A ()
{}
}
class B extends A
{

Tutorial on Java

P a g e | 24

int x;
B (int p, int q, int r)
{
super. x=p;
y=q;
this. x=r;
}
void sum ()
{
int m=super.x + y + this.x;
System.out.println (The sum is +s);
}
}
Class B has an instance variable x and the super class A also has an instance variable x. So
within class B, super.x refers to the instance variable x inherited from the super class and this.x
refers to the instance variable x of class B itself.
super is used to invoke parent class constructor
The super keyword can also be used to invoke the parent class constructor as given below:
class Employee
{
String nm;
int basic;
Employee (String n, int b)
{
nm=n;
basic=b;
}
}
class Manager extends Employee
{
String dept;
Manager (String nm, int basic, String d)
{
super (nm, basic);
dept=d;
}
}
class Inherit1
{
public static void main (String s [])
{
Manager m=new Manager ("Anup", 8900,"Acct");
}
}
In the constructor of Manager class, super (nm, basic) will call the constructor of the super class
that is the constructor of Employee class which accepts two integer parameters.
super can be used to invoke parent class method.
The super keyword can also be used to invoke parent class method. It should be used in case
subclass contains the same method as parent class as in the example given below:
Class Person
{
void message ()
{

Tutorial on Java

P a g e | 25

System.out.println ("welcome");
}
}
Class Student extends Person
{
void message ()
{
System.out.println ("Welcome to java");
}
Void display ()
{
message (); //will invoke current class message () method
super. message (); //will invoke parent class message () method
}
public static void main (String s[])
{
Student s=new Student ();
s. display ();
}
}
In the display () method of the Student class (subclass), super.message () will invoke the
message () method of the super class that is of the Person class. In this way a method of the
super class can also be called in a method of the subclass using the super keyword.

Method Overriding
After inheritance, if the super class method is redefined in the sub-class then this feature is called
method overriding and the method of the super class is called overridden method and the method
of the sub-class is called overriding method.
When a method in a subclass has the same name and type signature as a method in its
superclass, then the method in the subclass is said to override the method in the superclass.
When an overridden method is called from within a subclass, it will always refer to the version of
that method defined by the subclass. The version of the method defined by the superclass will be
hidden.
The return type and parameters of the overriding method (method of the subclass) must be same
as the return type and parameters of the overridden method (method of the super class).
Lets take an example:
class A
{
void show()
{
System.out.println("Show() of class A");
}
}
class B extends A
{
void show()
{
System.out.println("Show() of class B");
}
}
class OverrideBasics
{
public static void main(String s[])

Tutorial on Java

P a g e | 26

{
B obj=new B();
obj.show();
}
}
The sum() method of class A has been redefined in class B. It means that the sum() method of
class A has been overridden by the sum() method of class B. When show( ) is invoked on an
object of type B, the version of show( ) defined within B is used. That is, the version of show( )
inside B overrides the version declared in A.
Overriding does not mean to define a new method, but it is actually redefinition of an existing
method of the super class.
Rules for method overriding:
The arguments of the overriding method must be exactly the same as that of the overridden
method.
The return type of the overriding method must be the same or a subtype of the return type
of the overridden method in the superclass.
The accessibility of the overriding method must be same or more than the accessibility of
the overridden method. For example: if the superclass method is declared public then the
overriding method in the sub class cannot be either private or protected.
A method can be overridden only if it is inherited by the subclass.
A method declared as final cannot be overridden.
Constructors are not inherited and hence cannot be overridden.
Discuss different wrapper classes in Java
Java is an object-oriented language and everything is treated as an object. The primitive data
types are not objects. They do not belong to any class. Sometimes, it is required to convert data
types into objects. In Java, a wrapper class is a class in which a primitive value is wrapped up.
These primitive wrapper classes are used to represent primitive data type values as objects.
Java provides wrapper classes for each of the primitive data types. For example, Integer wrapper
class holds primitive int data type value. Similarly, Float wrapper class contain float primitive
values, Character wrapper class holds a char type value, and Boolean wrapper class
represents boolean type value.
The following diagram gives the detail of the various wrapper classes in java:

The Number class is an abstract class. It is the super class for the classes Byte, Short, Integer,
Long, Float and Double. Boolean and Character classes are direct subclass of Object class.
Eight wrapper classes exist in java.lang package that represent 8 data types. Following list gives.
Primitive
Wrapper
Data Type class
byte
Byte
short
Short
int
Integer
long
Long
float
Float
double
Double
char
Character

Tutorial on Java

P a g e | 27

boolean
Boolean
The following two statements illustrate the difference between a primitive data type and an object
of a wrapper class:
int x = 25;
Integer y = new Integer (33);
The first statement declares an int type variable named x and initializes it with the value 25. The
second statement declares an Integer object. The object is initialized with the value 33 and a
reference to the object is assigned to the reference variable y. the similar operation can be done
for all types of data types.
Each of the eight wrapper classes have a method to retrieve the value that was wrapped in the
object. These methods have the form aaaValue () where aaa refers to the corresponding data
type. For example, to retrieve the value stored in the Integer object, we use the following
statement.
Integer y = new Integer (33);
int x = y.intValue();
We have methods for the other seven wrapper classes: byteValue (), shortValue (), longValue (),
floatValue (), doubleValue (), charValue (), booleanValue ().
All the wrapper classes are declared final. That means we cannot create a subclass from any one
of them. All of the wrapper classes except Character class have two constructors. The first one
takes a primitive type value as argument, and the second one takes a String.
What is abstract class?
If a method is declared in a class but not defined in that class, then the method is called an
abstract method. If a class contains at least one abstract method, then the class is known as an
abstract class. We cant create an object of an abstract class.
What is an interface?
An interface is a user defined data type in java with the following properties:
All the variables declared in an interface are public, static and final by default.
All the methods are public and abstract.
A class can implement one or more than one interfaces.

Exception and its types


When something abnormal occurs within a method during execution, the method creates an object
to represent that abnormal situation and hands it off to the runtime system. The object is called an
exception object. This event can be caused by the program itself or by an outside resource the
program wants to use. For example, an exception is thrown if a Java program tries to access an
element of an array which is outside the bounds of the array. Or, let's say a Java application needs
to read the contents of file. If that file does not exist then an exception will be thrown.
There are basically three types of exceptions. They are as below:
Checked exceptions are the exceptions that are checked at compile time. If some code within a
method throws a checked exception, then the method must either handle the exception or it must
throw the exception using throws keyword. If a checked exception is neither handled nor thrown,
then it will be a compilation error.
Unchecked exceptions are the exceptions that are not checked at compiled time. If an unchecked
exception occurs in a method, but it is not handled, still the program will be compiled. All the
exceptions under Error and RuntimeException classes are unchecked exceptions. Everything
else under Throwable class is checked.

Tutorial on Java

P a g e | 28

Errors: These are not exceptions at all. They are problems that are beyond the control of the user
or the programmer. For example, if a stack overflow occurs, an error will arise. They are also
ignored at the time of compilation.

Exception Handling Mechanism


Whenever an exception occurs, the java runtime system supplies a piece of code to handle that
exception. This piece of code is known as default exception handler. The default handler gives
some relevant information about the exception and terminates the execution of the program. So,
while handling an exception, the main objective is to prevent the default handler by providing an
appropriate exception handler.
The exception handling mechanism is based on the following five keywords:
1. try
2. catch
3. finally
4. throw
5. throws
The statement(s) that might generate an exception is written within a try block. The try block is
known as guarded region also. The try keyword must be used within a method and must be
followed by either catch or finally block. The basic syntax of the try-catch-finally block is as below:
try
{
Statements
--------------}
catch (ExceptionType1)
{
Statements
---------------}
catch (ExceptionType2)
{
Statements
---------------}
catch (ExceptionType3)
{
Statements
---------------}
finally
{
---------------// Block of code that is always executed
// No matter whether the exception is handled or not
---------------}
If there is no exception in within the try block, then the entire try block executes normally and the
execution will be transferred to the finally block (if present) or after the try-catch construct. If an
exception occurs anywhere within the try block, then the rest part of the try block is not executed
and the catch blocks are inspected. The catch block is the exception handler. The catch blocks
immediately follow the try block. If there is more than one catch blocks, then they must appear just
after the try block. Additionally, the catch blocks must all follow each other, without any other

Tutorial on Java

P a g e | 29

statements or blocks in between them. If any exception does not occur within the try block then
none of the catch block is executed. The following flowchart will make it clear.

Execute try block

Exception

Find 1st matching catch


block

No catch block found

No Exception

Execute catch block


for Exception1

Execute catch block


for Exception2

Execute catch block


for Exception

Execute finally block

No exception or exception handled


Normal execution continues after try-catch-finally

Exception not handled or rethrown


Execution aborted and exception propagated

The catch statement accepts only one parameter, which is a reference variable of Exception
class or any of its sub-class. More than one catch block cant accept the reference variable of
same class. that is each of the catch blocks must have reference variable of different classes.
Whenever an exception occurs within the try block, the exception object is immediately thrown to
the nearest catch block. The catch block has one parameter which is a reference variable of
Exception class or any subclass of Exception class. In any one of the following two cases a catch
block associated with a try block is executed.
i) If the reference variable within the catch block and the exception generated within the try
block are of the same class.
ii) If the reference variable of the catch block is of a super class and the exception generated
in the try block is of a subclass.
The 2nd point needs some explanation. It is already known that a super class reference variable
can store the reference of a subclass object. The exception object generated in the try block is
checked against the reference variable of the catch block to see whether the object is storable in
that reference variable or not. Let an object of class A is generated in the try block and the catch
block has a reference variable of class B. If A is a subclass of B then that exception object can be
stored in the reference variable of the catch block.
In either of the cases, exception object is stored in the reference variable of the catch block and
that catch block is executed, that is, the exception is handled. If the exception object is not stored
in the reference variable of any one of the catch blocks, then the exception is not handled and the
default handler handles the exception.
The finally block is always executed irrespective of exception. Any one of the three cases may
take place:
i) If no exception occurs, then after the execution of the try block, the finally block is executed.
ii) If an exception occurs and it is handled by a catch block then after handling the exception,
the finally block is executed.

Tutorial on Java

P a g e | 30

iii) If an exception occurs and it is not handled by a catch block then before execution of the
default handler, the finally block is executed.
The runtime environment always executes the code within the finally block irrespective of what
happens in the try block. So it is the ideal place to keep the code which must be executed.
throw and throws
There is another approach of exception handling. A method, capable of throwing an exception,
may not handle the exception. Rather the method can declare that it can throw one or more
exceptions. Any method capable of causing exceptions must list all the possible exceptions at the
time of declaration of the method. So that anyone calling that method gets a prior knowledge
about which exceptions to handle. A method can do so by using the throws keyword. That is the
throws keyword is used in the signature of the function. Following is an example of declaring a
method using throws.
return type method_name (Parameter list) throws Exception1, Exception2, Exception3
{
Method body
}
On the other hand, the throw keyword is used to throw an exception explicitly. Only object of
Throwable class or its sub classes can be thrown. As soon as an exception is throws using the
throw statement, execution is transferred to the nearest catch statement and it is checked for
matching type of exception. Here is a segment of code to demonstrate the usage of throw and
throws:
public void sample () throws ArithmeticException
{
Statements
.....
if (Condition)
{
ArithmeticException exp = new ArithmeticException ();
throw exp;
...
}
}
Difference between throw and throws:
throws clause in used to declare an exception and throw keyword is used to throw an
exception explicitly.
ii) As per syntax throw is followed by an object of Exception class or a subclass of Exception
class throws is followed by exception class names.
iii) The keyword throw is used inside method body to invoke an exception and throws clause
is used in method declaration (signature).
iv) By using throw keyword in java we cannot throw more than one exception but using
throws you can declare multiple exceptions.
i)

Threading
All programmers are familiar with writing sequential programs. We have probably written a
program that displays "Hello World!", or sorts a list of names, or computes a list of prime numbers.
These are sequential programs: each has a beginning, an execution sequence, and an end. At
any given time during the runtime of the program there is a single point of execution.

Tutorial on Java

P a g e | 31

A thread is similar to the sequential programs described above: a single thread also has a
beginning, an end, a sequence, and at any given time during the runtime of the thread there is a
single point of execution. However, a thread itself is not a program. It cannot run on its own, but
runs within a program.
Definition: A thread is a single sequential flow of control within a program.
Threads are sometimes referred to as lightweight processes. Like processes, threads are
independent, concurrent paths of execution through a program, and each thread has its own
stack, its own program counter, and its own local variables. However, threads within a process are
less insulated from each other than separate processes are. They share memory, file handles, and
other per-process state.
Java is a multithreaded application that allows multiple thread execution at any particular time. In a
single-threaded application, only one thread is executed at a time because the application or
program can handle only one task at a time. But a multithreaded application allows performing
more than one task at a time.
Multithreading refers to two or more tasks executing concurrently within a single program. A thread
is an independent path of execution within a program. Many threads can run concurrently within a
program. Every thread in Java is created and controlled by the java.lang.Thread class. A Java
program can have many threads, and these threads can run concurrently, either asynchronously
or synchronously.
Multithreading has several advantages over Multiprocessing such as;
Threads are lightweight compared to processes
Threads share the same address space and therefore can share both data and code
Context switching between threads is usually less expensive than between processes
Cost of thread intercommunication is relatively low that that of process intercommunication
Threads allow different tasks to be performed concurrently.
In java we can create a thread either
i) Extending the Thread class of java.lang package or by
ii) Implementing the Runnable interface
Extending the Thread class:
The Thread class itself implements Runnable interface. A class
can inherit the Thread class and override the run () method according to its need.
public class HelloThread extends Thread
{
public void run ()
{
System.out.println ("Hello from a thread!");
}
public static void main (String s [])
{
HelloThread t=new HelloThread ();
t.start ();
}
}
Implementing the Runnable interface
The Runnable interface defines a single method, run, which contains the code executed in the
thread. The Runnable object is passed to the Thread constructor, as in the HelloRunnable
example:
public class HelloRunnable implements Runnable

Tutorial on Java

P a g e | 32

{
public void run ()
{
System.out.println ("Hello from a thread!");
}
public static void main (String s [])
{
HelloRunnable h=new HelloRunnable ();
Thread t=new Thread (h)
t.start ();
}
}
Note that both examples invoke start () to start the new thread.
Life cycle of a Thread
A thread can be in one of the five states in the thread. According to Sun Microsystem, there are
only 4 states new, runnable, non-runnable and terminated. There is no running state. But for
better understanding the threads, we are explaining it in the 5 states. The life cycle of the thread is
controlled by JVM. The thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Dead

Above-mentioned stages are explained here:


New: A new thread begins its life cycle in the new state. The thread is in new state when
we create an object of Thread class but before the invocation of start () method. It remains
in this state until the program starts the thread. It is also referred to as a born thread.
Runnable: The thread is in runnable state after invocation of start () method, but the
thread scheduler has not selected it to be the running thread. But a thread can return to this
state after either running, waiting, sleeping or coming back from blocked state also. On this
state a thread is waiting for a turn on the processor. The start () allocates the system
resources to the thread.

Tutorial on Java

P a g e | 33

Running:
A thread is in running state that means the thread is currently executing its
task. There are several ways to enter in Runnable state but there is only one way to enter in
Running state: the scheduler select a thread from runnable pool.
Not Runnable or blocked:
A thread becomes Not Runnable when one of these
events occurs:
Its sleep () method is invoked.
The thread calls the wait () method to wait for a specific condition to be satisfied.
The thread is blocking on I/O.
A thread in blocked state is inactive. That is it is not eligible to processor time. This thread can be
brought back to the runnable state at any time. A thread can go a number of times from running
state to blocked state and vice versa in its life cycle.
Dead:
A running thread enters the dead state when it completes its task or otherwise
terminates. A thread is in terminated or dead state when its run () method exits. A thread
also goes to the dead state when the stop () is called. A dead thread can never be
restarted.
Thread 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 unexpected 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 overwrite 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.
Why do we need Synchronization in Java?
If our code is executing in multi-threaded environment, we need synchronization for objects, which
are shared among multiple threads, to avoid any corruption of state or any kind of unexpected
behavior. Synchronization in Java will only be needed if shared object is mutable. If the shared
object is either read only or immutable object, than we don't need synchronization, in spite of
running multiple threads. JVM guarantees that Java synchronized code will only be executed
by one thread at a time. In Summary Java synchronized Keyword provides following functionality
essential for concurrent programming:
Synchronized keyword in Java provides locking, which ensures mutual exclusive access
of shared resource and prevent data race.
Synchronized keyword involve locking and unlocking. Before entering into
synchronized method or block a thread needs to acquire the lock, at this point it reads
data from main memory than cache and when it release the lock, it flushes write
operation into main memory which eliminates memory inconsistency errors.
Understanding the concept of Lock
Synchronization is built around an internal entity known as the lock or monitor. Every object has a
lock associated with it. By convention, a thread that needs consistent access to an object's fields
has to acquire the object's lock before accessing them, and then release the lock when it's done
with them.
Problem without Synchronization
Look at the following which has not used the synchronized method:
class Table

Tutorial on Java

{
void printTable (int n)//method not synchronized
{
for (int i=1; i<=5;i++)
{
System.out.println (n*i);
try
{
Thread.sleep (400);
}
catch (Exception e)
{
System.out.println (e);
}
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1 (Table t)
{
this.t=t;
}
public void run ()
{
t. printTable (5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2 (Table t)
{
this.t=t;
}
public void run ()
{
t. printTable (100);
}
}
class Use
{
public static void main (String s[])
{
Table obj = new Table (); //only one object. It will be used by two threads.
MyThread1 t1=new MyThread1 (obj);
MyThread2 t2=new MyThread2 (obj);
t1. start ();
t2. start ();
}
}
The result of the code is:

P a g e | 34

Tutorial on Java

P a g e | 35

5
100
10
200
15
300
20
400
25
500
It means that both the threads try to access the same object. Hence the values are being printed
in this fashion.
But if the printTable () is declared as synchronized, then the result changes a lot. At first one
thread gets the lock associated with the object, completes its task with the object and then
releases the lock. After that the next thread is allowed to access the object. The code will remain
the same, except that the printTable () method will be declared as below:
synchronized void printTable (int n)
Now the result will be:
5
10
15
20
25
100
200
300
400
500
Synchronized block
Synchronized block can be used to perform synchronization on any specific resource of the
method. Suppose we have 50 lines of code in our method, but we want to synchronize only 5
lines, you can use synchronized block.
If we put all the codes of the method in the synchronized block, it will work same as the
synchronized method.
Points to remember for Synchronized block
Synchronized block is used to lock an object for any shared resource.
Scope of synchronized block is smaller than the method.
Syntax to use synchronized block
synchronized (object reference expression)
{
//code block
}
Here is a synchronized block of Java code inside an unsynchronized Java method:
public void add (int value)
{
synchronized (this)
{
this.count += value;
}
}
Note that a synchronized block takes an object in parentheses. In the example "this" is used,
which is the object on which the add method has been called. The object taken in the parentheses

Tutorial on Java

P a g e | 36

by the synchronized construct is called a monitor object. The code is said to be synchronized on
the monitor object. A synchronized instance method uses the object it belongs to as monitor
object. Only one thread can execute inside a synchronized block on the same monitor object.
Example of synchronized block
Let's see the simple example of synchronized block.
class Table
{
void printTable (int n)//method not synchronized
{
synchronized (this)
{
for (int i=1;i<=5;i++)
{
System.out.println (n*i);
try
{
Thread.sleep (400);
}
catch (Exception e)
{
System.out.println (e);
}
}
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1 (Table t)
{
this.t=t;
}
public void run ()
{
t. printTable (5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2 (Table t)
{
this.t=t;
}
public void run ()
{
t. printTable (100);
}
}
class Use2

Tutorial on Java

P a g e | 37

{
public static void main (String s [])
{
Table obj = new Table (); //only one object
MyThread1 t1=new MyThread1 (obj);
MyThread2 t2=new MyThread2 (obj);
t1. start ();
t2. start ();
}
}
The output will be same as the output with a synchronized method.
Static synchronization
If you make any static method as synchronized, the lock will be on the class not on object. Let us
take an example:
Suppose there are two objects of a shared class (e.g. Table) named object1 and object2. In case
of synchronized method and synchronized block there cannot be interference between t1 and t2 or
t3 and t4 because t1 and t2 both refers to a common object that have a single lock. But there can
be interference between t1 and t3 or t2 and t4 because t1 acquires another lock and t3 acquires
another lock. If we want no interference between t1 and t3 or t2 and t4 then static synchronization
is the solution.
The JVM creates a Class object when the class is loaded that is when it is used for the first time.
Once a class is loaded into a JVM, the same class will not be loaded again. The JVM creates one
instance of Class for each class that is loaded; The Class instances are Objects and can be
synchronized via static synchronized methods.

class Table
{
synchronized static void printTable (int n)
{
for (int i=1;i<=10;i++)
{
System.out.println (n*i);
try
{
Thread.sleep (400);
}
catch (Exception e){}
}
}
}
class MyThread1 extends Thread
{
public void run ()
{

Tutorial on Java

P a g e | 38

Table. printTable (1);


}
}
class MyThread2 extends Thread
{
public void run ()
{
Table. printTable(1);
}
}
class MyThread3 extends Thread
{
public void run ()
{
Table. printTable(1);
}
}
class MyThread4 extends Thread
{
public void run ()
{
Table. printTable(1);
}
}
class Use
{
public static void main (String t[])
{
MyThread1 t1=new MyThread1 ();
MyThread2 t2=new MyThread2 ();
MyThread3 t3=new MyThread3 ();
MyThread4 t4=new MyThread4 ();
t1. start ();
t2. start ();
t3. start ();
t4. start ();
}
}

Java applet
A Java applet is a small dynamic Java program that can be transferred via the Internet and run by
a Java-compatible Web browser. An applet can be a fully functional Java application because it
has the entire Java API at its disposal. An applet is typically embedded inside a web page and
runs in the context of a browser. An applet must be a subclass of the java.applet.Applet class.
The Applet class provides the standard interface between the applet and the browser
environment.
There are some important differences between an applet and a standalone Java application,
including the following:
An applet is a Java class that extends the java.applet.Applet class. But a java application
need not always extend a class.

Tutorial on Java

P a g e | 39

A main () method is not invoked on an applet, and an applet class will not define main (),
but a java application needs a main () method.
Applets are embedded in a web page. But a java application is not embedded in a a
webpage.
When a user views a web page that contains an applet, the code for the applet is
automatically downloaded to the user's machine. A java application is not automatically
executed.
Life Cycle of an Applet:
Four methods in the Applet class give you the framework on which you build any serious applet:
init: This method is like a constructor. It is called by the browser (or applet viewer) to inform
the applet that it has been loaded into the system. Hence, it is called before any of the other
three methods are called, and is used for any initialization that needs to be done. The
Applet class provides a default implementation of this method that does nothing.
start: This method is called after the init method. It is also called after the page has been
maximized or revisited. The purpose of the method is to inform the applet that it should start
executing. The start method can be called more than once and the init method is called only
once.
stop: This method is called when the user changes pages, when the page is minimized,
and just before the applet is destroyed. It is called by the browser (or applet viewer) to
inform the applet to stop executing. If you are explicitly starting an activity with the start
method, you can stop it with the stop method.
destroy: This method is called by the browser or the applet viewer to inform the applet that
it is being destroyed and that it should release any resources that it has allocated. Once
destroyed, an applet cant be started again.
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.

Advantages and Disadvantages of Java Applets


A Java applet can have any or all of the following advantages:
1. Applets are cross platform and can run windows, MAC OS and Linux platform.
2. It is supported by most web browser.
3. It can work all the version of java plugin.
4. An untrusted applet has no access to the local machine and can only access the server it
came from.
5. It can work without security approval.
6. It can have full access to the machine it is running on if the user agrees.
7. It is cached in most web browsers. So, it will be quick to load when returning to a webpage.
8. It can move the work from the server to the client.
9. It is used to make a web solution more scalable with the number of user.
10. It can run at a comparable speed to other compiled languages such as C++, but many
times faster than JavaScript.

Tutorial on Java

P a g e | 40

Disadvantages
1. Java plug-in is required to run applet which is not available by default on all web browsers.
2. Some browsers, particularly mobile browser running apple IOS or Android dont run java
applet at all.
3. Applet cannot start up until the java virtual machine is running and it can take significant
time the first time it is used.
4. If applet is not already cached in the machine it will be downloaded from internet and will
take time.
5. It is difficult to design and built good user interface compare to HTML technology.
6. It may require a specific JRE (Java Runtime Environment).
Java.lang.Object.finalize () Method
Before an object is garbage collected, the runtime system calls its finalize () method. The intent is
for finalize () to release system resources such as open files or open sockets before getting
collected.
To add a finalize() to a class, just declare it as follows:
class Test
{
protected void finalize() throws Throwable
{
// clean up and resource held by this class. Call the super class to clean up resource held by it.
super.finalize ();
}
}
The finalize method is defined in the java.lang.Object class. It is defined as protected in the super
class. It is a best practice to call the super.finalize () after our class has freed up the resources it
was holding. This is because call to finalize are not automatically chained and garbage collector
calls finalize () only once on an instance. If we dont call super.finalize, any resource held by the
super class may never be given the opportunity to free it up. Garbage collector has to inspect all
objects to see whether it has a finalize method defined and if true, it has to invoke it. By Java
Language Specification there is no timely execution of finalize method.
Garbage collection is a mechanism provided by Java Virtual Machine to reclaim heap space from
objects which are eligible for Garbage collection. Garbage Collection in Java is carried by a
thread called Garbage Collector. Before removing an object from memory Garbage collection
thread invokes finalize () method of that object and gives an opportunity to perform any sort of
cleanup required. There are methods like System.gc () and Runtime.gc () which is used to send
request of Garbage collection to JVM but its not guaranteed that garbage collection will
happen.
What is the garbage collector in Java?
Automatic garbage collection is the process of looking at heap memory, identifying which objects
are in use and which are not, and deleting the unused objects. An object is in use means that
some part of our program still maintains a pointer to that object. An unused object, or
unreferenced object, is no longer referenced by any part of our program. So the memory used by
an unreferenced object can be reclaimed.
In a programming language like C, allocating and deallocating memory is a manual process. In
Java, process of deallocating memory is handled automatically by the garbage collector. The basic
process can be described as follows.
Step 1: Marking
The first step in the process is called marking. This is where the garbage collector identifies which
pieces of memory are in use and which are not.

Tutorial on Java

P a g e | 41

Referenced objects are shown in blue. Unreferenced objects are shown in gold. All objects are
scanned in the marking phase to make this determination. This can be a very time consuming
process if all objects in a system must be scanned.
Step 2: Normal Deletion
Normal deletion removes unreferenced objects leaving referenced objects and pointers to free
space.

The memory allocator holds references to blocks of free space where new object can be allocated.
Step 2a: Deletion with Compacting
To further improve performance, in addition to deleting unreferenced objects, we can also compact
the remaining referenced objects. By moving referenced object together, this makes new memory
allocation much easier and faster.

When an Object becomes Eligible for Garbage Collection


An Object becomes eligible for Garbage collection or GC if its not reachable from any live
threads or any static references. In other words we can say that an object becomes eligible for
garbage collection if its all references are null. Cyclic dependencies are not counted as
reference. So if Object A has reference of object B and object B has reference of Object A and
they don't have any other live reference then both Objects A and B will be eligible for Garbage
collection.
Generally an object becomes eligible for garbage collection in Java on following cases:
1. All references of that object explicitly set to null e.g. object = null
2. Object is created inside a block and reference goes out scope once control exit that block.
3. Parent object set to null, if an object holds reference of another object and when we set
container object's reference null, child or contained object automatically becomes eligible
for garbage collection.

Tutorial on Java

P a g e | 42

getCodeBase() and getDocumentBase()


In most of the applets, it is required to load text and images explicitly. Java enables loading data
from two directories. The first one is the directory which contains the HTML file that started the
applet (known as the document base). The other one is the directory from which the class file of
the applet is loaded (known as the code base). These directories can be obtained as URL objects
by using getDocumentBase()and getCodeBase () methods respectively.
getDocumentBase
URL getDocumentBase()
Gets the URL of the document in which the applet is embedded. For example, suppose an applet
is contained within the document:
http://java.sun.com/products/jdk/1.2/index.html
The document base is: http://java.sun.com/products/jdk/1.2/index.html
Returns:
The URL of the document that contains the applet.
getCodeBase
URL getCodeBase()
Gets the base URL. This is the URL of the directory which contains the applet.
Returns:
The base URL of the directory which contains the applet.

S-ar putea să vă placă și