Itp - Core Java PDF
Itp - Core Java PDF
Java is one of the world's most important and widely used computer languages, and it has held
this distinction for many years. Unlike some other computer languages whose influence has
weared with passage of time, while Java's has grown.
As of 2015, Java is one of the most popular programming languages in use, particularly for
client-server web applications, with a reported 9 million developers using and working on it.
History
Java was developed by James Ghosling, Patrick Naughton, Mike Sheridan at Sun Microsystems
Inc. in 1991. It took 18 months to develop the first working version.
The initial name was Oak but it was renamed to Java in 1995 as OAK was a registered
trademark of another Tech company.
Evolution of Java
Java was initially launched as Java 1.0 but soon after its initial release, Java 1.1 was launched.
Java 1.1 redefined event handling, new library elements were added.
In Java 1.2 Swing and Collection framework was added and suspend(), resume() and stop()
methods were deprecated from Thread class.
No major changes were made into Java 1.3 but the next release that was Java 1.4 contained
several important changes. Keyword assert, chained exceptions and channel based I/O System
was introduced.
Java 1.5 was called J2SE 5, it added following major new features :
Generics
Annotations
Autoboxing and autounboxing
Enumerations
For-each Loop
Varargs
Static Import
Formatted I/O
Concurrency utilities
Next major release was Java SE 7 which included many new changes, like :
Now String can be used to control Switch statement.
Multi Catch Exception
try-with-resource statement
Binary Integer Literals
Underscore in numeric literals, etc.
And the latest addition to the lot is, Java SE 8, it was released on March 18, 2014. Some of the
major new features introduced in JAVA 8 are,
Lambda Expressions
New Collection Package java.util.stream to provide Stream API.
Enhanced Security
Nashorn Javascript Engine included
Parallel Array Sorting
The JDBC-ODBC Bridge has been removed etc.
Application of Java
Java is widely used in every corner of world and of human life. Java is not only used in softwares
but is also widely used in designing hardware controlling software components. There are more
than 930 million JRE downloads each year and 3 billion mobile phones run java.
Following are some other usage of Java :
1. Developing Desktop Applications
2. Web Applications like Linkedin.com, Snapdeal.com etc
3. Mobile Operating System like Android
4. Embedded Systems
5. Smart cards
6. Robotics and games etc.
5) Secure
When it comes to security, Java is always the first choice. With java secure features it enable us
to develop virus free, temper free system. Java program always runs in Java runtime environment
with almost null interaction with system OS, hence it is more secure.
6) Multi Threading
Java multithreading feature makes it possible to write program that can do many tasks
simultaneously. Benefit of multithreading is that it utilizes same memory and other resources to
execute multiple threads at the same time, like While typing, grammatical errors are checked
along.
7) Architectural Neutral
Compiler generates bytecodes, which have nothing to do with a particular computer architecture,
hence a Java program is easy to intrepret on any machine.
8) Portable
Java Byte code can be carried to any platform. No implementation dependent features.
Everything related to storage is predefined, example: size of primitive data types
9) High Performance
Java is an interpreted language, so it will never be as fast as a compiled language like C or C++.
But, Java enables high performance with the use of just-in-time compiler.
New Features of JAVA 8
Below mentioned are some of the core upgrades done as a part of Java 8 release.
Enhanced Productivity by providing Optional Classes feature, Lamda Expressions,
Streams etc.
Ease of Use
Improved Polyglot programming. A ploygot is a program or script, written in a form
which is valid in multiple programming languages and it performs the same operations in
multiple programming languages. So Java now supports such type of programming
technique.
Improved Security and performance.
What is JVM?
Java virtual Machine(JVM) is a virtual Machine that provides runtime environment to execute
java byte code. The JVM doesn't understand Java typo, that's why you compile your *.java files
to obtain *.class files that contain the bytecodes understandable by the JVM.
JVM control execution of every Java program. It enables features such as automated exception
handling, Garbage-collected heap.
JVMs are available for many hardware and software platforms. JVM, JRE and JDK are platform
dependent because configuration of each OS differs. But, Java is platform independent.
JVM Architecture
JDK : The JDK also called Java Development Kit is a superset of the JRE, and contains
everything that is in the JRE, plus tools such as the compilers and debuggers necessary for
developing applets and applications.
Integer
This group includes byte, short, int, long
byte : It is 8 bit integer data type. Value range from -128 to 127. Default value zero. example:
byte b=10;
short : It is 16 bit integer data type. Value range from -32768 to 32767. Default value zero.
example: short s=11;
int : It is 32 bit integer data type. Value range from -2147483648 to 2147483647. Default value
zero. example: int i=10;
long : It is 64 bit integer data type. Value range from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807. Default value zero. example: long l=100012;
Floating-Point Number
This group includes float, double
float : It is 32 bit float data type. Default value 0.0f. example: float ff=10.3f;
double : It is 64 bit float data type. Default value 0.0d. example: double db=11.123;
Characters
This group represent char, which represent symbols in a character set, like letters and numbers.
char : It is 16 bit unsigned unicode character. Range 0 to 65,535. example: char c='a';
Boolean
This group represent boolean, which is a special type for representing true/false values. They are
defined constant of the language. example: boolean b=true;
Type 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;
In Java, type casting is classified into two types,
Widening Casting(Implicit)
}
Output :
Int value 100
Long value 100
Float value 100.0
}
Output :
Double value 100.04
Long value 100
Int value 100
Variable
Java Programming language defines mainly three kind of variables.
1. Instance variables
2. Static Variables
3. Local Variables
1) Instance variables
Instance variables are variables that are declare inside a class but outside any method,constructor
or block. Instance variable are also variable of object commonly known as field or property.
class Student
{
String name;
int age;
}
Here name and age are instance variable of Student class.
2) Static variables
Static are class variables declared with static keyword. Static variables are initialized only once.
Static variables are also used in declaring constant along with final keyword.
class Student
{
String name;
int age;
static int instituteCode=1101;
}
Here instituteCode is a static variable. Each object of Student class will share instituteCode
property.
3) Local variables
Local variables are declared in method constructor or blocks. Local variables are initialized when
method or constructor block start and will be destroyed once its end. Local variable reside in
stack. Access modifiers are not used for local variable.
Array Declaration
Syntax :
datatype[] identifier;
or
datatype identifier[];
Both are valid syntax for array declaration. But the former is more readable.
Example :
int[] arr;
char[] arr;
short[] arr;
long[] arr;
int[][] arr; //two dimensional array.
Initialization of Array
new operator is used to initialize an array.
Example :
int[] arr = new int[10]; //10 is the size of array.
or
int[] arr = {10,20,30,40,50};
Arithmetic operators
Arithmetic operators are used in mathematical expression in the same way that are used in
algebra.
operator description
+ adds two operands
- subtract second operands from first
* multiply two operand
/ divide numerator by denumerator
% remainder of division
++ Increment operator increases integer value by one
-- Decrement operator decreases integer value by one
Relation operators
The following table shows all relation operators supported by Java.
operator description
== Check if two operand are equal
!= Check if two operand are not equal.
> Check if operand on the left is greater than operand on the right
< Check operand on the left is smaller than right operand
>= check left operand is greater than or equal to right operand
<= Check if operand on left is smaller than or equal to right operand
Logical operators
Java supports following 3 logical operator. Suppose a=1 and b=0;
operator description example
&& Logical AND (a && b) is false
|| Logical OR (a || b) is true
! Logical NOT (!a) is false
Bitwise operators
Java defines several bitwise operators that can be applied to the integer types long, int, short,
char and byte
operator description
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< left shift
>> right shift
Now lets see truth table for bitwise &, | and ^
aba&ba|ba^b
000 0 0
010 1 1
100 1 1
111 1 0
The bitwise shift operators shifts the bit value. The left operand specifies the value to be shifted
and the right operand specifies the number of positions that the bits in the value are to be shifted.
Both operands have the same precedence.
Example
a = 0001000
b= 2
a << b= 0100000
a >> b= 0000010
Assignment Operators
Assignment operator supported by Java are as follows
operator description example
= assigns values from right side operands to left side operand a=b
a+=b is same as
+= adds right operand to the left operand and assign the result to left
a=a+b
subtracts right operand from the left operand and assign the result a-=b is same as a=a-
-=
to left operand b
mutiply left operand with the right operand and assign the result a*=b is same as
*=
to left operand a=a*b
divides left operand with the right operand and assign the result to a/=b is same as
/=
left operand a=a/b
%= calculate modulus using two operands and assign the result to left a%=b is same as a=a
operand %b
Misc operator
There are few other operator supported by java language.
Conditional operator
It is also known as ternary operator and used to evaluate Boolean expression
epr1 ? expr2 : expr3
If epr1Condition is true? Then value expr2 : Otherwise value expr3
instanceOf operator
This operator is used for object reference variables. The operator checks whether the object is of
particular type (class type or interface type)
Object and Classes
Since Java is an object oriented language, complete java language is build on classes and object.
Java is also known as a strong Object oriented programming language(oops).
OOPS is a programming approach which provides solution to problems with the help of
algorithms based on real world. It uses real world approach to solve a problem. So object
oriented technique offers better and easy way to write program then procedural programming
model such as C, ALGOL, PASCAL.
Main Features of OOPS
Inheritence
Polymorphism
Encapsulation
Abstraction
Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example:
to convense the customer differently, to draw something e.g. shape or rectangle etc.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.
In java, we use method overloading and method overriding to achieve polymorphism
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example:
phone call, we don't know the internal processing.
In java, we use abstract class and interface to achieve abstraction
As an object oriented language Java supports all the features given above.
Class
In Java everything is encapsulated under classes. Class is the core of Java language. Class can be
defined as a template/ blueprint that describe the behaviors /states of a particular entity. A class
defines new data type. Once defined this new type can be used to create object of that type.
Object is an instance of class. You may also call it as physical existence of a logical template
class.
A class is declared using class keyword. A class contain both data and code that operate on that
data. The data or variables defined within a class are called instance variables and the code that
operates on this data is known as methods.
Example of a Method
public String getName(String st)
{
String name="Spark";
name=name+st;
return name;
}
Modifier : Modifier are access type of method. We will discuss it in detail later.
Return Type : A method may return value. Data type of value return by a method is declare in
method heading.
Method name : Actual name of the method.
Parameter : Value passed to a method.
Method body : collection of statement that defines what method does.
Example of call-by-value
public class Test
{
public void callByValue(int x)
{
x=100;
}
public static void main(String[] args)
{
int x=50;
Test t = new Test();
t.callByValue(x); //function call
System.out.println(x);
}
}
Output : 50
Example of call-by-reference
public class Test
{
int x=10;
int y=20;
public void callByReference(Test t)
{
t.x=100;
t.y=50;
}
public static void main(String[] args)
{
}
Output :
Before 10 20
After 100 50
Method overloading
If two or more method in a class have same name but different parameters, it is known as method
overloading.
Method overloading is one of the ways through which java supports polymorphism. Method
overloading can be done by changing number of arguments or by changing the data type of
arguments. If two or more method have same name and same parameter list but differs in
return type are not said to be overloaded method
Constructor Overloading
Like methods, a constructor can also be overloaded. Overloaded constructors are differentiated
on the basis of their type of parameters or number of parameters. Constructor overloading is not
much different than method overloading. In case of method overloading you have multiple
methods with same name but different signature, whereas in Constructor overloading you have
multiple constructor with different signature but only difference is that Constructor doesn't have
return type in Java.
Example of constructor overloading
class Cricketer
{
String name;
String team;
int age;
Cricketer () //default constructor.
{
name ="";
team ="";
age = 0;
}
Cricketer(String n, String t, int a) //constructor overloaded
{
name = n;
team = t;
age = a;
}
Cricketer (Cricketer ckt) //constructor similar to copy constructor of
c++
{
name = ckt.name;
team = ckt.team;
age = ckt.age;
}
public String toString()
{
return "this is " + name + " of "+team;
}
}
Class test:
{
public static void main (String[] args)
{
Cricketer c1 = new Cricketer();
Cricketer c2 = new Cricketer("sachin", "India", 32);
Cricketer c3 = new Cricketer(c2 );
System.out.println(c2);
System.out.println(c3);
c1.name = "Virat";
c1.team= "India";
c1.age = 32;
System .out. print in (c1);
}
}
output:
this is sachin of india
this is sachin of india
this is virat of india
Constructor name must be same as the class name. Method name may or may not be same as class
name.
this keyword
this keyword is used to refer to current object.
this is always a reference to the object on which method was invoked.
this can be used to invoke current class constructor.
this can be passed as an argument to another method.
Example :
class Box
{
Double width, weight, dept;
Box (double w, double h, double d)
{
this.width = w;
this.height = h;
this.depth = d;
}
}
Here the this is used to initialize member of current object.
finalize() method
Sometime an object will need to perform some specific task before it is destroyed such as closing
an open connection or releasing any resources held. To handle such situation finalize() method is
used. finalize() method is called by garbage collection thread before collecting object. Its the last
chance for any object to perform cleanup utility.
Signature of finalize() method
protected void finalize()
{
//finalize-code
}
gc() Method
gc() method is used to call garbage collector explicitly. However gc() method does not guarantee
that JVM will perform the garbage collection. It only request the JVM for garbage collection.
This method is present in System and Runtime class.
Modifiers in Java
Modifiers are keywords that are added to change meaning of a definition. In Java, modifiers are
catagorized into two types,
1. Access control modifier
2. Non Access Modifier
2) Non-access Modifier
Non-access modifiers do not change the accessibility of variables and methods, but they do
provide them special properties. Non-access modifiers are of 5 types,
1. Final
2. Static
3. Transient
4. Synchronized
5. Volatile
Final
The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:
variable
method
class
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
Example:
class Bike
{
final int speedlimit=90;//final variable
void run()
{
speedlimit=400;
}
public static void main(String args[])
{
Bike obj=new Bike();
obj.run();
}
}//end of class
Static Modifier
Static Modifiers are used to create class variable and class methods which can be accessed
without instance of a class. Lets study how it works with variables and member functions.
Static with Variables
Static variables are defined as a class member that can be accessed without any object of that
class. Static variable has only one single storage. All the object of the class having static variable
will have the same instance of static variable. Static variables are initialized only once.
Static variable are used to represent common property of a class. It saves memory. Suppose there
are 100 employee in a company. All employee have its unique name and employee id but
company name will be same all 100 employee. Here company name is the common property. So
if you create a class to store employee detail, company_name field will be mark as static.
Example
class Employee
{
int e_id;
String name;
static String company_name = "Spark";
}
}
Output
104 AbhijitSpark
108 ankitSpark
Static Method
A method can also be declared as static. Static methods do not need instance of its class for being
accessed. main() method is the most common example of static method. main() method is
declared as static because it is called before any object of the class is created.
Example :
class Test
{
Static block
Static block is used to initialize static data member. Static block executes before main() method.
Example
class ST_Employee
{
int eid;
String name;
static String company_name;
static {
company_name ="Spark"; //static block invoked before main() method
}
}
Output
104 AbhijitSpark
Example of accessing non-static variable from a static context
class Test
{
int x;
public static void main(String[] args)
{
x=10;
}
}
Output
compiler error: non-static variable count cannot be referenced from a static
context
Same example using instance of class
class Test
{
int x;
public static void main(String[] args)
{
Test tt=new Test();
tt.x=10; //works fine with instance of class
}
}
Inheritance (IS-A)
Inheritance is one of the key features of Object Oriented Programming. Inheritance provided
mechanism that allowed a class to inherit property of another class. When a Class extends
another class it inherits all non-private members including fields and methods. Inheritance in
Java can be best understood in terms of Parent and Child relationship, also known as Super
class(Parent) and Sub class(child) in Java language.
Inheritance defines is-a relationship between a Super class and its Sub class. extends and
implements keywords are used to describe inheritance in Java.
Types of Inheritance
1. Single Inheritance
2. Multilevel Inheritance
3. Heirarchical Inheritance
NOTE :Multiple inheritance is not supported in java
Example of Child class refering Parent class property using super keyword
class Parent
{
String name;
}
public class Child extends Parent {
String name;
public void details()
{
super.name = "Parent"; //refers to parent class member
name = "Child";
System.out.println(super.name+" and "+name);
}
public static void main(String[] args)
{
Child cobj = new Child();
cobj.details();
}
}
Output
Parent and Child
Example of Child class refering Parent class methods using super keyword
class Parent
{
String name;
public void details()
{
name = "Parent";
System.out.println(name);
}
}
public class Child extends Parent {
String name;
public void details()
{
super.details(); //calling Parent class details() method
name = "Child";
System.out.println(name);
}
public static void main(String[] args)
{
Child cobj = new Child();
cobj.details();
}
}
Output
Parent
Child
Example of Child class calling Parent class constructor using super keyword
class Parent
{
String name;
public Parent(String n)
{
name = n;
}
}
public class Child extends Parent {
String name;
Example
class Student
{
String name;
Address ad;
}
Here you can say that Student has-aAddress.
Student class has an instance variable of type Address. Student code can use Address reference
to invoke methods on the Address, and get Address behavior.
Aggregation allow you to design classes that follow good Object Oriented practices. It also
provide code reusability.
Example of Aggregation
class Author
{
String authorName;
int age;
String place;
Author(String name,int age,String place)
{
this.authorName=name;
this.age=age;
this.place=place;
}
public String getAuthorName()
{
return authorName;
}
public int getAge()
{
return age;
}
public String getPlace()
{
return place;
}
}
class Book
{
String name;
int price;
Author auth;
Book(String n,int p,Author at)
{
this.name=n;
this.price=p;
this.auth=at;
}
public void showDetail()
{
System.out.println("Book is"+name);
System.out.println("price "+price);
System.out.println("Author is "+auth.getAuthorName());
}
}
class Test
{
public static void main(String args[])
{
Author ath=new Author("Me",22,"India");
Book b=new Book("Java",550,ath);
b.showDetail();
}
}
Output:
Book is Java.
price is 550.
Author is me.
Composition in java:
Composition is restricted form of Aggregation. For example a class Car cannot exist without
Engine.
class Car
{
private Engine engine;
Car(Engine en)
{
engine = en;
}
}
Q. When to use Inheritance and Aggregation?
When you need to use property and behaviour of a class without modifying it inside your class.
In such case Aggregation is a better option. Whereas when you need to use and modify property
and behaviour of a class inside your class, its best to use Inheritance.
Method Overriding
When a method in a sub class has same name and type signature as a method in its super class,
then the method is known as overridden method. Method overriding is also referred to as runtime
polymorphism. The key benefit of overriding is the abitility to define method that's specific to
a particular subclass type.
NOTE : Static methods cannot be overridden because, a static method is bounded with class
where as instance method is bounded with object.
Upcasting
When Parent class reference variable refers to Child class object, it is known as Upcasting
Example
class Game
{
public void type()
{ System.out.println("Indoor & outdoor"); }
}
instanceof operator
In Java, instanceof operator is used to check the type of an object at runtime. It is the means by
which your program can obtain run-time type information about an object. instanceof operator
is also important in case of casting object at runtime. instanceof operator return boolean value,
if an object reference is of specified type then it return true otherwise false.
Example of instanceOf
public class Test
{
public static void main(String[] args)
{
Test t= new Test();
System.out.println(t instanceof Test);
}
}
output true
Downcasting
Example of downcasting with instanceof operator
class Parent{ }
Child.show(p);
}
}
Output
Sucessfull Casting
Command line argument in Java
The command line argument is the argument passed to a program at the time when you run it. To
access the command-line argument inside a java program is quite easy, they are stored as string
in String array passed to the args parameter of main() method.
Example
class cmd
{
public static void main(String[] args)
{
for(int i=0;i< args.length;i++)
{
System.out.println(args[i]);
}
}
}
Execute this program as java cmd 10 20 30
Output
10
20
30
Java Package
Package are used in Java, in-order to avoid name conflicts and to control access of class,
interface and enumeration etc. A package can be defined as a group of similar types of classes,
interface, enumeration and sub-package. Using package it becomes easier to locate the related
classes.
Creating a package
Creating a package in java is quite easy. Simply include a package command followed by name
of the package as the first statement in java source file.
package mypack;
public class employee
{
...statement;
}
Java uses file system directory to store package. For example the .class for any classes you to
define to be part of mypack package must be stored in a directory called mypack
class test
{
public static void main(String[] args)
{
Book bk = new Book("java","Herbert");
bk.show();
}
}
create a directory under your current working development directory(i.e. JDK directory), name it
as mypack.
compile the source file
Put the class file into the directory you have created.
Execute the program from development directory.
NOTE : Development directory is the directory where your JDK is install.
Static import
static import is a feature that expands the capabilities of import keyword. It is used to import
static member of a class. We all know that static member are referred in association with its
class name outside the class. Using static import, it is possible to refer to the static member
directly without its class name. There are two general form of static import statement.
The first form of static import statement, import only a single static member of a class
Syntax
import static package.class-name.static-member-name;
Example
import static java.lang.Math.sqrt; //importing static method sqrt of
Math class
The second form of static import statement,imports all the static member of a class
Syntax
import static package.class-type-name.*;
Example
import static java.lang.Math.*; //importing all static member of Math
class
Abstract method
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 (); // No definition
Points to Remember
1. An abstract class must have an abstract method.
2. Abstract classes can have Constructors, Member variables and Normal methods.
3. Abstract classes are never instantiated.
4. When you extend Abstract class with abstract method, you must define the abstract
method in the child class, or make the child class abstract.
}
}
Output
Car engine
Here by casting instance of Car type to Vehicle reference, we are hiding the complexity of Car
type under Vechicle. Now the Vehicle reference can be used to provide the implementation but it
will hide the actual implementation process.
Example of Interface
interface Moveable
{
int AVERAGE-SPEED=40;
void move();
}
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());
}
}
Output:
true
true
Interface extends other Interface
Classes implements interfaces, but an interface extends other interface.
interface NewsPaper
{
news();
}
class Inner
{
public void show()
{
System.out.println("Inside inner");
}
}
}
class Test
{
public static void main(String[] args)
{
Outer ot=new Outer();
ot.display();
}
}
Output:
Inside inner
class Test
{
public static void main(String[] args)
{
Outer ot=new Outer();
ot.display();
}
}
Output:
Inside inner 0
Inside inner 1
Inside inner 2
Inside inner 3
Inside inner 4
class Outer
{
int count;
public void display()
{
Inner in=new Inner();
in.show();
}
class Inner
{
public void show()
{
System.out.println("Inside inner "+(++count));
}
}
}
class Test
{
public static void main(String[] args)
{
Outer ot=new Outer();
Outer.Inner in= ot.new Inner();
in.show();
}
}
Output
Inside inner 1
Annonymous class
A class without any name is called Annonymous class.
interface Animal
{
void type();
}
public class ATest {
public static void main(String args[])
{
Animal an = new Animal(){ //Annonymous class created
public void type()
{
System.out.println("Annonymous animal");
}
};
an.type();
}
}
Output
Annonymous animal
Here a class is created which implements Animal interace and its name will be decided by the
compiler. This annonymous class will provide implementation of type() method.
Introduction to String Handling
String is probably the most commonly used class in java library. String class is encapsulated
under java.lang package. In java, every string that you create is actually an object of type
String. One important thing to notice about string object is that string objects are immutable that
means once a string object is created it cannot be altered.
And, when we create another object with same string, then a reference of the string literal already
present in string pool is returned.
String str2=str;
2) Using + operator
string str = "Rahul";
string str1 = "Dravid";
string str2 = str + str1;
string st = "Rahul"+"Dravid";
String Comparison
String comparison can be done in 3 ways.
1. Using equals() method
2. Using == operator
3. By CompareTo() method
Using == operator
== operator compares two object references to check whether they refer to same instance. This
also, will return true on successful match.
String s1 = "Java";
String s2 = "Java";
String s3 = new string ("Java");
test(Sl == s2) //true
test(s1 == s3) //false
By compareTo() method
compareTo() method compares values and returns an int which tells if the string compared is less
than, equal to or greater than th other string. Its general syntax is,
intcompareTo(String str)
To use this function you must implement the Comparable Interface. compareTo() is the only
function in Comparable Interface.
String s1 = "Abhi";
String s2 = "Viraaj";
String s3 = "Abhi";
s1.compareTo(S2); //return -1 because s1 < s2
s1.compareTo(S3); //return 0 because s1 == s3
s2.compareTo(s1); //return 1 because s2 > s1
equalsIgnoreCase()
equalsIgnoreCase() determines the equality of two Strings, ignoring thier case (upper or lower
case doesn't matters with this fuction ).
String str = "java";
System.out.println(str.equalsIgnoreCase("JAVA"));
Output : true
length()
length() function returns the number of characters in a String.
String str = "Count me";
System.out.println(str.length());
Output : 8
replace()
replace() method replaces occurances of character with a specified new character.
String str = "Change me";
System.out.println(str.replace('m','M'));
Output : Change Me
substring()
substring() method returns a part of the string. substring() method has two forms,
public String substring(int begin);
toLowerCase()
toLowerCase() method returns string with all uppercase characters converted to lowercase.
String str = "ABCDEF";
System.out.println(str.toLowerCase());
Output : abcdef
valueOf()
Overloaded version of valueOf() method is present in String class for all primitive data types and
for type Object.valueOf() function is used to convert primitive data types into Strings.
But for objects, valueOf() method calls toString() function.
toString()
toString() method returns the string representation of the object used to invoke this method.
toString() is used to represent any Java Object into a meaningful string representation. It is
declared in the Object class, hence can be overrided by any java class. (Object class is super
class of all java classes.)
public class Car {
public static void main(String args[])
{
Car c=new Car();
System.out.println(c);
}
public String toString()
{
return "This is my car object";
}
}
Output : This is my car object
Whenever we will try to print any object of class Car, its toString() function will be called.
toString() can also be used with normal string objects.
String str = "Hello World";
System.out.println(str.toString());
Output : Hello World
toUpperCase()
This method returns string with all lowercase character changed to uppercase.
String str = "abcdef";
System.out.println(str.toLowerCase());
Output : ABCDEF
trim()
This method returns a string from which any leading and trailing whitespaces has been removed.
String str = " hello ";
System.out.println(str.trim());
Output : hello
StringBuffer class
StringBuffer class is used to create a mutable string object. It represents growable and writable
character sequence. As we know that String objects are immutable, so if we do a lot of changes
with String objects, we will end up with a lot of memory leak.
So StringBuffer class is used when we have to make lot of modifications to our string. It is also
thread safe i.e multiple threads cannot access it simultaneously. StringBuffer defines 4
constructors. They are,
1. StringBuffer ( )
2. StringBuffer ( int size )
3. StringBuffer ( String str )
4. StringBuffer ( charSequence [ ]ch )
StringBuffer() creates an empty string buffer and reserves room for 16 characters.
stringBuffer(int size) creates an empty string and takes an integer argument to set
capacity of the buffer.
Example showing difference between String and StringBuffer
class Test {
public static void main(String args[])
{
String str = "Spark";
str.concat("institute");
System.out.println(str); // Output: Spark
StringBufferappend(int n)
StringBufferappend(Object obj)
The string representation of each parameter is appended to StringBuffer object.
StringBuffer str = new StringBuffer("test");
str.append(123);
System.out.println(str);
Output : test123
insert()
This method inserts one string into another. Here are few forms of insert() method.
StringBufferinsert(int index, String str)
capacity()
This method returns the current capacity of StringBuffer object.
StringBuffer str = new StringBuffer();
System.out.println( str.capacity() );
Output : 16
ensureCapacity()
This method is used to ensure minimum capacity of StringBuffer object.
StringBuffer str = new StringBuffer("hello");
str.ensureCapacity(10);
StringBuilder class
StringBuilder is identical to StringBuffer except for one important difference it is not
synchronized, which means it is not thread safe. Its because StringBuilder methods are not
synchronised.
StringBuilder Constructors
1. StringBuilder ( ), creates an empty StringBuilder and reserves room for 16 characters.
2. StringBuilder ( int size ), create an empty string and takes an integer argument to set
capacity of the buffer.
3. StringBuilder ( String str ), create a StringBuilder object and initialize it with string str.
Example of StringBuilder
class Test {
public static void main(String args[])
{
StringBuilder str = new StringBuilder("Spark");
str.append( "institute" );
System.out.println(str);
}
}
Output :Sparkinstitute
Exception Handling
Exception Handling is the mechanism to handle runtime malfunctions. We need to handle such
exceptions to prevent abrupt termination of program. The term exception means exceptional
condition, it is a problem that may arise during the execution of program. A bunch of things can
lead to exceptions, including programmer error, hardware failures, files that need to be opened
cannot be found, resource exhaustion etc.
Exception
A Java Exception is an object that describes the exception that occurs in a program. When an
exceptional events occurs in java, an exception is said to be thrown. The code that's responsible
for doing something about the exception is called an exception handler.
Exception class is for exceptional conditions that program should catch. This class is
extended to create user specific exception classes.
RuntimeException is a subclass of Exception. Exceptions under this class are
automatically defined for programs.
Uncaught Exceptions
When we don't handle the exceptions, they lead to unexpected program termination. Lets take an
example for better understanding.
class UncaughtException
{
public static void main(String args[])
{
int a = 0;
int b = 7/a; // Divide by zero, will lead to exception
}
}
This will lead to an exception at runtime, hence the Java run-time system will construct an
exception and then throw it. As we don't have any mechanism for handling exception in the
above program, hence the default handler will handle the exception and will print the details of
the exception on the terminal.
An exception will thrown by this program as we are trying to divide a number by zero inside try
block. The program control is transfered outside try block. Thus the line "This line will not be
executed" is never parsed by the compiler. The exception thrown is handle in catch block. Once
the exception is handled the program controls continue with the next line in the program. Thus
the line "After exception is handled" is printed.
throws Keyword
Any method capable of causing exceptions must list all the exceptions possible during its
execution, so that anyone calling that method gets a prior knowledge about which exceptions to
handle. A method can do so by using the throws keyword.
Syntax :
type method_name(parameter_list)throwsexception_list
{
//definition of method
}
It is necessary for all exceptions, except the exceptions of type Error and RuntimeException,
or any of their subclass.
finally clause
A 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 exception has occurred. Using a finally block, lets you run
any cleanup type statements that you want to execute, no matter what happens in the protected
code. A finally block appears at the end of catch block.
Example demonstrating finally Clause
Class ExceptionTest
{
public static void main(String[] args)
{
int a[]= new int[2];
System.out.println("out of try");
try
{
System.out.println("Access invalid element"+ a[3]);
/* the above statement will throw ArrayIndexOutOfBoundException */
}
finally
{
System.out.println("finally is always executed.");
}
}
}
Output:
Out of try
finally is always executed.
Exception in thread main java. Lang. exception array Index out of bound
exception.
You can see in above example even if exception is thrown by the program, which is not handled
by catch block, still finally block will get executed.
class Test
{
static void sum(int a,int b) throws MyException
{
if(a<0)
{
throw new MyException(a);
}
else
{
System.out.println(a+b);
}
}
Points to Remember
1. Extend the Exception class to create your own ecxeption class.
2. You don't have to implement anything inside it, no methods are required.
3. You can have a Constructor if you want.
4. You can override the toString() function, to display customized message.
Method Overriding with Exception Handling
There are few things to remember when overriding a method with exception handling. If super
class method does not declare any exception, then sub class overriden method cannot declare
checked exception but it can declare unchecked exceptions.
Thread Priorities
Every thread has a priority that helps the operating system determine the order in which threads
are scheduled for execution. In java thread priority ranges between,
MIN-PRIORITY (a constant of 1)
MAX-PRIORITY (a constant of 10)
By default every thread is given a NORM-PRIORITY(5). The main thread always have NORM-
PRIORITY.
Thread Class
Thread class is the main class on which Java's Multithreading system is based. Thread class,
along with its companion interface Runnable will be used to create and run threads for utilizing
Multithreading feature of Java.
Method Description
setName() to give thread a name
getName() return thread's name
getPriority() return thread's priority
isAlive() checks if thread is still running or not
join() Wait for a thread to end
run() Entry point for a thread
sleep() suspend thread for a specified time
start() start a thread by calling run() method
Creating a thread
Java defines two ways by which a thread can be created.
By implementing the Runnable interface.
By extending the Thread class.
class MyThreadDemo
{
public static void main( String args[] )
{
MyThread mt = new MyThread();
Thread t = new Thread(mt);
t.start();
}
}
Output : concurrent thread started running..
To call the run() method, start() method is used. On calling start(), a new stack is provided to
the thread and run() method is called to introduce the new thread into the program.
classMyThreadDemo
{
public static void main( String args[] )
{
MyThread mt = new MyThread();
mt.start();
}
}
Output : concurrent thread started running..
In this case also, as we must override the run() and then use the start() method to start and run
the thread. Also, when you create MyThread class object, Thread class constructor will also be
invoked, as it is the super class, hence MyThread class object acts as Thread class object.
Joining threads
Sometimes one thread needs to know when another thread is ending. In java, isAlive() and join()
are two different methods to check whether a thread has finished its execution.
The isAlive() methods return true if the thread upon which it is called is still running otherwise
it return false.
final boolean isAlive()
But, join() method is used more commonly than isAlive(). This method waits until the thread on
which it is called terminates.
final void join() throws InterruptedException
Using join() method, we tell our thread to wait until the specifid thread completes its execution.
There are overloaded versions of join() method, which allows us to specify time for which you
want to wait for the specified thread to terminate.
final void join(long milliseconds) throws InterruptedException
System.out.println("r2 ");
}
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();
t2.start();
System.out.println(t1.isAlive());
System.out.println(t2.isAlive());
}
}
Output
r1
true
true
r1
r2
r2
System.out.println("r2 ");
}
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();
t2.start();
}
}
Output
r1
r1
r2
r2
In this above program two thread t1 and t2 are created. t1 starts first and after printing "r1" on
console thread t1 goes to sleep for 500 mls.At the same time Thread t2 will start its process and
print "r1" on console and then goes into sleep for 500 mls. Thread t1 will wake up from sleep
and print "r2" on console similarly thread t2 will wake up from sleep and print "r2" on console.
So you will get output like r1 r1 r2 r2
System.out.println("r2 ");
}
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();
try{
t1.join(); //Waiting for t1 to finish
}catch(InterruptedException ie){}
t2.start();
}
}
Output
r1
r2
r1
r2
In this above program join() method on thread t1 ensure that t1 finishes it process before thread
t2 starts.
Specifying time with join()
If in the above program, we specify time while using join() with m1, then m1 will execute for
that time, and then m2 and m3 will join it.
m1.join(1500);
Doing so, initially m1 will execute for 1.5 seconds, after which m2 and m3 will join it.
Synchronization
At times when more than one thread try to access a shared resource, we need to ensure that
resource will be used by only one thread at a time. The process by which this is achieved is
called synchronization. The synchronization keyword in java creates a block of code referred to
as critical section.
Every Java object with a critical section of code gets a lock associated with the object. To enter
critical section a thread need to obtain the corresponding object's lock.
General Syntax :
synchronized (object)
{
//statement to be synchronized
}
Synchronized Keyword
To synchronize above program, we must serialize access to the shared display() method, making
it available to only one thread at a time. This is done by using keyword synchronized with
display() method.
synchronizedvoiddisplay (String msg)
Using Synchronised block
If you have to synchronize access to object of a class that has no synchronized methods, and you
cannot modify the code. You can use synchronized block to use it.
class First
{
public void display(String msg)
{
System.out.print ("["+msg);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println ("]");
}
}
Thread Pooling
Pooling is usually implemented by loop i.e to check some condition repeatedly. Once condition
is true appropriate action is taken. This waste CPU time.
Deadlock
Deadlock is a situation of complete Lock, when no thread can complete its execution because
lack of resources. In the above picture, Thread 1 is holding a resource R1, and need another
resource R2 to finish execution, but R2 is locked by Thread 2, which needs R3, which in turn is
locked by Thread 3. Hence none of them can finish and are stuck in a deadlock.
Example of deadlock
class Pen{}
class Paper{}
}
}
};
Thread t2 = new Thread(){
public void run()
{
synchronized(pr)
{
System.out.println("Thread2 is holding Paper");
try{
Thread.sleep(1000);
}catch(InterruptedException e){}
synchronized(pn)
{ System.out.println("requesting for Pen"); }
}
}
};
t1.start();
t2.start();
}
}
Output
Thread1 is holding Pen
Thread2 is holding Paper
Some New Feature:
Enumerations
Enumerations was added to Java language in JDK5. Enumeration means a list of named
constant. In Java, enumeration defines a class type. An Enumeration can have constructors,
methods and instance variables. It is created using enum keyword. Each enumeration constant is
public, static and final by default. Even though enumeration defines a class type and have
constructors, you do not instantiate an enum using new. Enumeration variables are used and
declared in much a same way as you do a primitive variable.
2. Identifiers Java, Cpp, C and Dbms are called enumeration constants. These are public,
static final by default.
3. Variables of Enumeration can be defined directly without any new keyword.
Subjectsub
Example of Enumeration
enum WeekDays
{ sun, mon, tues, wed, thurs, fri, sat }
class Test
{
public static void main(String args[])
{
WeekDays wk;
wk = WeekDays.sun;
System.out.println("Today is "+wk);
}
}
Output : Today is sun
class EnumDemo
{
public static void main( String args[] )
{
Student S;
System.out.println("Age of Viraaj is " +Student.Viraaj.getage()+ "years");
}
}
Output : Age of Viraaj is 9 years
In this example as soon as we declare an enum variable(Student S), the constructor is called once,
and it initializes age for every enumeration constant with values specified with them in
parenthesis.
type wrapper
Java uses primitive types such as int, double or float to hold the basic data types for the sake of
performance. Despite the performance benefits offered by the primitive types, there are situation
when you will need an object representation. For example, many data structures in Java operate
on objects, so you cannot use primitive types with those data structures. To handle these
situations Java provides type Wrappers which provide classes that encapsulate a primitive type
within an object.
Character : It encapsulates primitive type char within object.
Character (char ch)
Boolean : It encapsulates primitive type boolean within object.
Boolean (boolean boolValue)
Numeric type wrappers : It is the most commonly used type wrapper.
Byte Short Integer Long Float Double
Above mentioned Classes comes under Numeric type wrapper. These classes encapsulate
byte, short, int, long, float, double primitive type.
IO Stream
Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O system to
make input and output operation in java. In general, a stream means continuous flow of data.
Streams are clean way to deal with input/output without having every part of your code
understand the physical.
Java encapsulates Stream under java.io package. Java defines two types of streams. They are,
1. Byte Stream : It provides a convenient means for handling input and output of byte.
2. Character Stream : It provides a convenient means for handling input and output of
characters. Character stream uses Unicode and therefore can be internationalized.
These two abstract classes have several concrete classes that handle various devices such as disk
files, network connection etc.
Some important Byte stream classes.
Stream class Description
BufferedInputStream Used for Buffered Input Stream.
BufferedOutputStream Used for Buffered Output Stream.
DataInputStream Contains method for reading java standard datatype
An output stream that contain method for writing java standard data
DataOutputStream
type
FileInputStream Input stream that reads from a file
FileOutputStream Output stream that write to a file.
InputStream Abstract class that describe stream input.
OutputStream Abstract class that describe stream output.
PrintStream Output Stream that contain print() and println() method
These classes define several key methods. Two most important are
1. read() : reads byte of data.
2. write() : Writes byte of data.
These two abstract classes have several concrete classes that handle unicode character.
Reading Characters
read() method is used with BufferedReader object to read characters. As this function returns
integer type value has we need to use typecasting to convert it into char type.
intread() throws IOException
Below is a simple example explaining character input.
class CharRead
{
public static void main( String args[])
{
BufferedReader br = new Bufferedreader(new InputstreamReader(System.in));
char c = (char)br.read(); //Reading character
}
}
Reading Strings
To read string we have to use readLine() function with BufferedReader class's object.
StringreadLine() throws IOException
Networking in Java
Java is a premier language for network programming. java.net package encapsulate large
number of classes and interface that provides an easy-to use means to access network resources.
Here are some important classes and interfaces of java.net package.
Some Important Classes
CLASSES
CacheRequest
CookieManager
Inet Address
Socket
Proxy
URLConnection
INTERFACES
CookiePolicy
FileNameMap
InetAddress
SocketImplFactory
InetAddress
Inet Address encapsulates both numerical IP address and the domain name for that address. Inet
address can handle both IPv4 and Ipv6 addresses. Inet Address class has no visible constructor.
To create an inet Address object, you have to use Factory methods.
Three commonly used Inet Address factory methods are.
1. static InetAddressgetLocalHost() throws UnknownHostException
2. static InetAddressgetByName (String hostname) throws UnknownHostException
3. static InetAddress[ ]getAllByName (String hostname) throws UnknownHostException
URL class
Java URL Class present in java.net package, deals with URL (Uniform Resource Locator) which
uniquely identify or locate resources on internet.
http://www.spark3e.com:80/index.html
Protocol hostname port number file name
Collection Framework
Collection framework was not part of original Java release. Collections was added to J2SE 1.2.
Prior to Java 2, Java provided adhoc classes such as Dictionary, Vector, Stack and Properties to
store and manipulate groups of objects. Collection framework provides many important classes
and interfaces to collect and organize group of alike objects.
Collection Enables you to work with groups of object; it is at the top of collection hierarchy
Extends collection to handle special kind of list in which element are removed only from the
Queue
head.
Set Extends collection to handle sets, which must contain unique element.
>
1. There are couple of new and interestin methods added by this interface. Some of them are
mentioned in below table.
Methods Description
removes element at the head of the queue and returns null
poll()
if queue is empty
removes element at the head of the queue and throws
remove()
NoSuchElementException if queue is empty
peek() returns the element at the head of the queue without
Methods Description
removing it. Returns null if queue is empty
same as peek(), but throws NoSuchElementException if
element()
queue is empty
offer( E obj ) Adds object to queue.
ArrayList class
1. ArrayList class extends AbstractList class and implements the List interface.
2. ArrayList supports dynamic array that can grow as needed. ArrayList has three
constructors.
ArrayList()
ArrayList( Collection C )
Example of ArrayList
import java.util.*
class Test
{
public static void main(String[] args)
{
ArrayList< String> al = new ArrayList< String>();
al.add("ab");
al.add("bc");
al.add("cd");
system.out.println(al);
}
}
Output : [ab,bc,cd]
}
Output
[Ricky Pointing(999100091), David Beckham(998392819), Virat Kohli(998131319)]
LinkedList class
1. LinkedList class extends AbstractSequentialList and implements List,Deque and
Queue inteface.
2. It can be used as List, stack or Queue as it implements all the related interfaces.
3. It can contain duplicate elements and is not synchronized.
HashSet class
1. HashSet extends AbstractSet class and implements the Set interface.
2. It creates a collection that uses hash table for storage.
3. HashSet does not maintain any order of elements.
LinkedHashSet Class
1. LinkedHashSet class extends HashSet class
2. LinkedHashSet maintains a linked list of entries in the set.
3. LinkedHashSet stores elements in the order in which elements are inserted.
TreeSet Class
1. It extends AbstractSet class and implements the NavigableSet interface.
2. It stores elements sorted ascending order.
3. Uses a Tree structure to store elements.
4. Access and retrieval times are quite fast.
5. It has four Constructors.
TreeSet()
TreeSet( Collection C )
TreeSet( SortedSet ss )
Accessing a Collection
To access, modify or remove any element from any collection we need to first find the element,
for which we have to cycle throught the elements of the collection. There are three possible ways
to cycle through the elements of any collection.
1. Using Iterator interface
2. Using ListIterator interface
3. Using for-each loop
HashMap class
1. HashMap class extends AbstractMap and implements Map interface.
2. It uses a hashtable to store the map. This allows the execution time of get() and put()
to remain same.
3. HashMap has four constructor.
HashMap()
HashMap(Map< ? extends k, ? extends V> m)
HashMap(int capacity)
HashMap(int capacity, float fillratio)
4. HashMap does not maintain order of its element.
Example
import java.util.*;
class HashMapDemo
{
public static void main(String args[])
{
HashMap< String,Integer> hm = new HashMap< String,Integer>();
hm.put("a",new Integer(100));
hm.put("b",new Integer(200));
hm.put("c",new Integer(300));
hm.put("d",new Integer(400));
TreeMap class
1. TreeMap class extends AbstractMap and implements NavigableMap interface.
2. It creates Map, stored in a tree structure.
3. A TreeMap provides an efficient means of storing key/value pair in efficient order.
4. It provides key/value pairs in sorted order and allows rapid retrieval.
Example
import java.util.*;
class TreeMapDemo
{
public static void main(String args[])
{
TreeMap< String,Integer> tm = new TreeMap< String,Integer>();
tm.put("a",new Integer(100));
tm.put("b",new Integer(200));
tm.put("c",new Integer(300));
tm.put("d",new Integer(400));
LinkedHashMap class
1. LinkedHashMap extends HashMap class.
2. It maintains a linked list of entries in map in order in which they are inserted.
3. LinkedHashMap defines the following constructor
LinkedHashMap()
LinkedHashMap(int capacity)
Comparator Interface
In Java, Comparator interface is used to order the object in your own way. It gives you ability to
decide how element are stored within sorted collection and map.
Comparator Interface defines compare() method. This method compare two object and return 0
if two object are equal. It returns a positive value if object1 is greater than object2. Otherwise a
negative value is return. The method can throw a ClassCastException if the type of object are
not compatible for comparison.
Example
Student class
class Student
int roll;
String name;
Student(int r,String n)
{
roll = r;
name = n;
}
public String toString()
{
return roll+" "+name;
}
MyComparator class
This class defines the comparison logic for Student class based on their roll. Student object will
be sotred in ascending order of their roll.
class MyComparator implements Comparator
{
public int compare(Student s1,Student s2)
{
if(s1.roll == s2.roll) return 0;
else if(s1.roll > s2.roll) return 1;
else return -1;
}
}
public class Test
{
}
Output
[ 11 Adam, 19 Alex, 45 Rahul ]
As you can see in the ouput Student object are stored in ascending order of their roll.
Legacy Classes
Early version of java did not include the Collection framework. It only defined several classes
and interface that provide method for storing objects. When Collection framework were added in
J2SE 1.2, the original classes were reengineered to support the collection interface. These classes
are also known as Legacy classes. All legacy claases and interface were redesign by JDK 5 to
support Generics.
The following are the legacy classes defined by java.util package
1. Dictionary
2. HashTable
3. Properties
4. Stack
5. Vector
There is only one legacy interface called Enumeration. All the legacy classes are syncronized
Enumeration interface
1. Enumeration interface defines method to enumerate through collection of object.
2. This interface is suspended by Iterator interface.
3. However some legacy classes such as Vector and Properties defines several method in
which Enumeration interface is used.
4. It specifies the following two methods
boolean hasMoreElements()
Object nextElement()
Vector class
1. Vector is similar to ArrayList which represents a dynamic array.
2. The only difference between Vector and ArrayList is that Vector is synchronised while
Array is not.
3. Vector class has following four constructor
Vector()
Vector(int size)
Example of Vector
import java.util.*;
public class Test
{
public static void main(String[] args)
{
Vector ve = new Vector();
ve.add(10);
ve.add(20);
ve.add(30);
ve.add(40);
ve.add(50);
ve.add(60);
Enumeration en = ve.elements();
while(en.hasMoreElements())
{
System.out.println(en.nextElement());
}
}
}
Output
10
20
30
40
50
60
Hashtable class
1. Like HashMap, Hashtable also stores key/value pair in hashtable. However neither keys
nor values can be null.
2. There is one more difference between HashMap and Hashtable that is Hashtable is
synchronized while HashMap is not.
3. Hashtable has following four constructor
Hashtable()
Hashtable(int size)
Hashtable(int size, float fillratio)
Hashtable(Map< ? extends K, ? extends V> m)
Example of Hashtable
import java.util.*;
class HashTableDemo
{
public static void main(String args[])
{
Hashtable< String,Integer> ht = new Hashtable< String,Integer>();
ht.put("a",new Integer(100));
ht.put("b",new Integer(200));
ht.put("c",new Integer(300));
ht.put("d",new Integer(400));
Set st = ht.entrySet();
Iterator itr=st.iterator();
while(itr.hasNext())
{
Map.Entry m=(Map.Entry)itr.next();
System.out.println(itr.getKey()+" "+itr.getValue());
}
}
}
Output:
a 100
b 200
c 300
d 400
Properties class
1. Properties class extends Hashtable class.
2. It is used to maintain list of value in which both key and value are String
3. Properties class define two constructor
Properties()
Properties(Properties default)
4. One advantage of Properties over Hashtable is that we can specify a default property
that will be useful when no value is associated with a certain key.
}
}
Output
Java was created by James Ghosling
C++ was created by Bjarne Stroustrup
C was created by Dennis Ritchie
C# was created by Microsoft Inc
Applet in Java
Applets are small Java applications that can be accessed on an Internet server, transported
over Internet, and can be automatically installed and run as apart of a web document. Any
applet in Java is a class that extends the java.applet.Applet class.
An Applet class does not have any main() method.
It is viewed using JVM. The JVM can use either a plug-in of the Web browser or a
separate runtime environment to run an applet application.
JVM creates an instance of the applet class and invokes init() method to initialize an
Applet.
A Simple Applet
import java.awt.*;
import java.applet.*;
public class Simple extends Applet
{
public void paint(Graphics g)
{
g.drawString("A simple Applet", 20, 20);
}
}
Every Applet application must declare a paint() method. This method is defined by AWT
class and must be overridden by the applet. paint() method is called each time an applet neede
to redisplay its output. Another important thing to notice about applet application is that,
execution of an applet does not begin at main() method. In fact an applet application does not
have any main() method.
Advantages of Applets
1. Very less response time as it works on the client side.
2. Can be run using any browser, which has JVM running in it.
Applet class
Applet class provides all necessary support for applet execution, such as initializing and
destroying of applet. It also provide methods that load and display images and methods that load
and play audio clips.
An Applet Skeleton
Most applets override these four methods. These four methods forms Applet lifecycle.
init() : init() is the first method to be called. This is where variable are initialized. This
method is called only once during the runtime of applet.
start() : start() method is called after init(). This method is called to restart an applet after
it has been stopped.
stop() : stop() method is called to suspend thread that does not need to run when applet is
not visible.
destroy() : destroy() method is called when your applet needs to be removed completely
from memory.
Example of an Applet
import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet
{
int height, width;
public void init()
{
height = getSize().height;
width = getSize().width;
setName("MyApplet");
}
public void paint(Graphics g)
{
g.drawRoundRect(10, 30, 120, 120, 2, 3);
}
}
Event Handling
Any program that uses GUI (graphical user interface) such as Java application written for
windows, is event driven. Event describes the change of state of any object. Example : Pressing
a button, Entering a character in Textbox.
AWT Hierarchy
Component class
Component class is at the top of AWT hierarchy. Component is an abstract class that
encapsulates all attribute of visual component. A component object is responsible for
remembering the current foreground and background colours and the currently selected text font.
Container
Container is a component in AWT that contains another component like button, text field, tables
etc. Container is a subclass of component class. Conatiner class keeps track of components that
are added to another component.
Panel
Panel class is concrete sub class of Container. Panel does not contain title bar, menu bar or
border.
Window class
Window class creates a top level window. Window does not have borders and menubar.
Frame
Frame is a sub class of Window and have resizing canvas. It is a container that contain several
different components like button, title bar, textfield, label etc. In Java, most of the AWT
applications are created using Frame window. Frame class has two different constructors,
Frame() throws HeadlessException
Creating a Frame
There are two ways to create a Frame. They are,
1. By Instantiating Frame class
2. By extending Frame class
import java.awt.*;
import java.awt.event.*;
JPanel : JPanel is Swing's version of AWT class Panel and uses the same default layout,
FlowLayout. JPanel is descended directly from JComponent.
JFrame : JFrame is Swing's version of Frame and is descended directly from Frame class. The
component which is added to the Frame, is refered as its Content.
JWindow : This is Swing's version of Window and hass descended directly from Window class.
Like Window it uses BorderLayout by default.
JLabel : JLabel descended from Jcomponent, and is used to create text labels.
JButton : JButton class provides the functioning of push button. JButton allows an icon, string
or both associated with a button.
JTextField : JTextFields allow editing of a single line of text.
Creating a JFrame
There are two way to create a JFrame Window.
1. By instantiating JFrame class.
2. By extending JFrame class.
JButton
JButton class provides functionality of a button. JButton class has three constuctors,
JButton(Icon ic)
JButton(String str)
testswing()
{
JButton bt1 = new JButton("Yes"); //Creating a Yes Button.
JButton bt2 = new JButton("No"); //Creating a No Button.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) //setting close
operation.
setLayout(new FlowLayout()); //setting layout using FlowLayout
object
setSize(400, 400); //setting size of Jframe
add(bt1); //adding Yes button to frame.
add(bt2); //adding No button to frame.
setVisible(true);
}
public static void main(String[] args)
{
new testswing();
}
}
JTextField
JTextField is used for taking input of single line of text. It is most widely used text component.
It has three constructors,
JTextField(int cols)
JTextField(String str, int cols)
JTextField(String str)
cols represent the number of columns in text field.
Before JDBC, ODBC API was the database API to connect and execute query with the database.
But, ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and
unsecured). That is why Java has defined its own API (JDBC API) that uses JDBC drivers
(written in Java language).
JDBC Driver
JDBC Driver is a software component that enables java application to interact with the database.
JDBC Driver is required to process SQL requests and generate result. The following are the
different types of driver available in JDBC.
Type-1 Driver or JDBC-ODBC bridge
Type-2 Driver or Native API Partly Java Driver
Type-3 Driver or Network Protocol Driver
Type-4 Driver or Thin Driver
JDBC-ODBC bridge
Type-1 Driver act as a bridge between JDBC and other database connectivity
mechanism(ODBC). This driver converts JDBC calls into ODBC calls and redirects the request
to the ODBC driver.
Advantage
Easy to use
Allow easy connectivity to all database supported by the ODBC Driver.
Disadvantage
Slow execution time
Dependent on ODBC Driver.
Uses Java Native Interface(JNI) to make ODBC call.
Advantage
Does not require any native library to be installed.
Database Independency.
Provide facility to switch over from one database to another database.
Disadvantage
Slow due to increase number of network call.
Thin Driver
This is Driver called Pure Java Driver because. This driver interact directly with database. It does
not require any native database library, that is why it is also known as Thin Driver.
Advantage
Does not require any native library.
Does not require any Middleware server.
Better Performance than other driver.
Disadvantage
Slow due to increase number of network call.