JavaBy TajendarAroraFinal PDF
JavaBy TajendarAroraFinal PDF
JavaBy TajendarAroraFinal PDF
(Handouts)
2. An overview of Java 7
Setting up Environment
Path and Class Path in JAVA
3. First java program 18
5. Operators 33
8. Inheritance 60
9 Understanding STATIC 73
10 Final Keyword 76
23 Generics 175
(An object takes up space in the memory and has an associated address,
like structure in C.)
The wrapping up of data and methods into a single unit (called class) is
known as Encapsulation.
(The data is not accessible to the outside world and only those methods, which
are wrapped in the class, can access it)
(Classes use the concept of abstraction and are defined as a list of abstract
attributes such as size, weight and cost, and methods that operate on these
attributes.)
3.Inheritance
(The principle behind this sort of division is that each derived class shares
common characteristics with the class from which it is derived)
(For example, consider the operation of addition. For two numbers, the
operation will generate a sum. If the operands are strings, then the operation
would produce a third string by concatenation.)
The Java language has undergone several changes since JDK 1.0 (1996) and
now JSE 8 is latest.
*jdk- Java Development Kit
*JSE- Java Standard Ediiton
JAVA Versions
JDK Alpha and Beta
JDK 1.0
JDK 1.1
J2SE 1.2
J2SE 1.3
J2SE 1.4
J2SE 5.0
Java SE 6
Java SE 7
Java SE 8
Why Java?
Object-oriented
Platform independent
Built-in support for multi-threading, socket communication and
memory management
Supports Web based applications (Applet, Servlets and JSP)
Vast library of predefined objects and operations
Secure
(First, java compiler translates source code into what is known as bytecode
instructions. Bytecodes are not machine instructions and therefore, in the
second stage, Java interpreter generates machine code that can be directly
executed by the machine that is running the Java program.)
(However, the fact that a Java program is executed by the JVM helps solves the
major problems associated with downloading programs over the internet. That
means , JVM is an interpreter for bytecode.)
Translating a Java Program into bytecode helps makes it much easier to run a
program in a wide variety of environments.
Once the run- time package exists for a given system, any java program can
run on it.
(The fact that a java program is interpreted also helps to make it secure.
Because the execution of every program is under the control of the JVM, the
JVM can contain the program and prevent it from generating side effects
outside of the system.)
Java Features
Java ensures portability in two ways. First, Java compiler generates bytecode
instructions that can be implemented on any machine. Secondly, the sizes of
the primitive data types are machine independent.
The Enterprise version of Java has a much larger usage of Java, like
development of web services, networking, server side scripting and other
various web based applications. J2EE uses many components of J2SE, as well
as, has a e features of it s o like Servlets, JavaBeans, Java Message
Services, adding a whole new functionalities to the language.J2EE uses HTML,
C““, Ja a“ ript et ., so as to reate e pages a d e ser i es. It s also o e
of the most widely accepted web development standard.
J2ME(Java Platform, Micro Edition)
PersonalJava was another edition, which was not deployed much, as its
function was fulfilled by further versions of J2ME. Made to support
World Wide Web (and Java applets) and consumer electronics.
Path Variable
Path variable is set for providing path for all java tools like java, javac, javap,
javah, jar, appletviewer which are use in java programming. These all tools are
available in bin folders so we set path upto bin folders.
Classpath Variable
Classpath variable is set for providing path for predefined java classes which
is used in our application. All classes are available in lib/rt.jar so we set
classpath upto lib/rt.jar.
Now one dilog box is appear, now ignore this but do not close.
Note: rt.jar is available in lib folder this jar files contains all classes of jdk.
The best way to learn a new language is to write a few simple example
programs. We begin with a program that prints a line of text as output.
The first thing that you must learn about the java is that the name you give to a
source file is very important. For example, the name of the source file should
be SampleOne.java. In java, a source file is officially called compilation unit.
The java compiler requires that a source file use the .java filename extension.
As you can see by looking at the program, the name of the class defined by the
program is also SampleOne. This is not co-incidence.
In java, all code must de reside inside a class. By convention, the name of that
class should match the name of the file that holds the program.
You should also make sure that the capitalization of the filename matches the
class name. However, this convention makes it easier to maintain and organize
your programs.
Class Declaration:
The first line
Class SampleOne
Opening Brace:
E er lass defi itio i ja a egi s ith a ope i g ra e { and ends with a
at hi g losi g ra e } .
Public:
The keyword public is an access specifier that declares the main method as
unprotected and therefore making it accessible to all other classes.
Static:
It declares this method as one that belongs to the entire class and not a part of
any objects of the class. The main must always be declared as static since the
interpreter uses this method before any objects are created.
Void:
The type modifier void states that the main method does not return any value.
The Output file:
C : \>javac SampleOne.java
The javac compiler creates a file called SampleOne.class that contains the
bytecode version of the program. As discussed earlier, the java bytecode is the
intermediate representation of your program that contains instructions the
Java interpreter will execute. Thus, the output of javac is not code that can be
directly executed.
To actually run the program, you must use the Java interpreter, called
java. To do so, pass the class name SampleOne as a command-line argument,
as shown here:
C : \>java SampleOne
class Example2
{
public static void main(String args[])
{
int num;
num = 100;
“ ste .out.pri tl this is u : + u ;
num=num * 2;
“ ste .out.pri t the alue of u * is ;
System.out.println(num);
}
}
When you run this program, you will see the following output:
This is num : 100
The value of num * 2 is 200
This line declares an integer variable called num. Java requires that variables
be declared before they are used.
C. 2. Java Tokens
Most statements contain expressions, which describe the actions carried out
on data. Small individual units in a program are known as tokens. The
compiler recognizes them for building up expressions and statements.
Whitespace – Java is a free - from language. This means that you do not need
to follow any special indentation rules. In java, whitespace is a space,tab, or
newline.
Identifiers –Identifiers are used for class names, method names, and variable
names. An identifier may be descriptive sequence of uppercase and lowercase
letters, numbers, or the underscore and dollar – sign characters. Again , Java is
case- sensitive, (so VALUE is a different identifier than Value ).
Separators – In java, there are few characters that are used as separators.
The ost o o l used separator i ja a is the se i olo , it is used to
terminate statements.
Data Types
Every variable in java has a data type. Data types specify the size and type of
values that can be stored. Java language is rich in its data types. The variety of
data types available allows the programmer to select the type appropriate to
the needs of the application.
Java defines eight simple types of data: byte, short, int, long, char, float,
double, and Boolean.
These can be put in four groups:
Integer: this group includes byte, short, int, and long, which are for
whole valued signed numbers.
Floating point numbers: this group includes float, and double,
which represent numbers with fractional precision.
Character: this group includes char, which represents symbols in a
character set, like letters and numbers.
Boolean: this group includes Boolean, which is a special type for
representing true/false values.
Integer types:
Integer types can hold whole numbers such as 123,-96, 578. The size of the
values that can be stored depends on the integer data type we choose. Java
supports four types of integers: byte, short, int, and long. Java does not
Here is a short program that uses double variables to compute the area of a
circle
// compute the area of a circle.
Class Area
{
public static void main(String args[])
{
double pi,r,a;
r=10.8;
pi=3.1416;
a=pi*r*r;
“ ste .out.pri tl Area of ir le is + a );
}
}
Character type:
Variables
The variable is the basic unit of storage in a java program. A variable is defined
by the combination of an identifier, a type, and an optional initializer.
Declaring a variable
In java, all variables must be declared before they can be used. The basic form
of a variable declaration is shown here.
type aria le , aria le ……….. aria le N:
1. Assignment Statement
A simple method of giving value to a variable is through the assignment
statement as follows:
type variableName = value;
Examples:
int finalValue = 100;
char es = ;
double total = 75.36;
The process of giving initial values to variables is known as the initialization.
The ones that are not initialized are automatically set to zero.
2. Read statement
We may also give the values to variables interactively through the keyboard
using the readLine() method .
The readLine() method ( which is invoked using an object of the class
DataInputStream ) reads the input from the keyboard as a string which is then
converted to the corresponding data type.
Arrays
An array is a group of like- typed variables that are referred to by a
common name. Arrays of any type can be created and may have one
or more dimensions.
A specific element in an array is accessed by its index.
(# if you are familiar with C/C++ , be careful. Arrays in java work differently than they do in
those language.)
One - dimensional Arrays
A one – dimensional array is, essentially ,a list of like – typed variables. To
create an array, you first must create an array variable of the desired type.
The general form of one – dimensional array declaration is:
type var-name[ ];
Here, type declares the base type of the array. The base type determines the
data type of each element that comprises the array. Thus, the base type for
the array determines what type of data the array will hold. For example, the
following declares an array named month_days ith the t pe arra of i t :
int month_days[ ] ;
new is a special operator that allocates memory. The general form of new as
it applies to one – dimensional array appears as follows:
Here, type specifies the type of data being allocated, size specifies the number
of elements in the array, and array-var is the array variable that is linked to
the array. That is, to use new to allocate an array, you must specify the
number of elements to allocate.
After execution: When you run this program, it prints the number of days in
April. Java array indexes start with zero, so the number of days in April is
month_days[3] or 30.
Here is one more example that uses a one – dimensional array. It finds the
average of a set of numbers.
class Average
{
public static void main(String args[ ])
{
double nums [ ]= { 10.1, 11.2, 12.3, 13.4, 14.5 };
double result = 0;
int i ;
# when you allocate memory for a multidimensional array, you need only
specify the memory for the first ( left most ) dimension. You can allocate the
remaining dimensions separately. For example, this following code allocates
for the first dimension of twoD when it is declared. It allocates the second
dimension manually.
Class TwoDAgain
{
public static void main (String args[ ])
{
int twoD [ ] [ ] = new int [4] [ ] ;
twoD [0] = new int [1] ;
twoD [1] = new int [2] ;
twoD [2] = new int [3] ;
twoD [3] = new int [4] ;
int i , j , k = 0 ;
for ( i = 0 ; i <4 ; i ++ )
{
for ( j = 0; j< i + 1 ; j ++)
“ ste .out.pri t t oD [i] [j] + ;
System.out.println() ;
}
}
}
Java also defines some additional operators that handle certain special
situations.
Arithmetic Operators
Arithmetic operators are used in mathematical expressions in the same way
that they are used in algebra. The following table lists the arithmetic operators:
Operator Result
% Modulus
++ Increment
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
When you run this program , you will see the output:
Integer Arithmetic
a = 2
b = 6
c =1
d = -1
e =1
“ ste .out.pri tl od = + % ;
“ ste .out.pri tl od = + % ;
}
When you run this program you will get the following output :
x mod10 = 2
y mod 10 = 2.25
Bitwise Operators
Java defines several bitwise operators which can be applied to the integer
types, long, int, short, char, and byte. These operators act upon the
i di idual s its of their opera ds. The are su arized i the follo i g ta le:
Operator Result
~ Bitwise unary NOT
& bitwise AND
| bitwise OR
^ bitwise exclusive OR
>> shift right
>>> shift right zero fill
All of the binary bitwise operators have a shorthand form similar to that of the
algebraic operators, which combines the assignment with the bitwise
operation.
For example, the following two statements, which shift the value in a right by
four bits, are equivalent.
a = a >> 4;
a >>= 4;
Relational Operators
Assignment Operator
The assignment operator is the single equal sign, =. The assignment operator
works in Java much as it does in any other computer language.
var = expression;
Here, the type of var must be compatible with the type of expression. Others
are +=,-=,*=,/=,%=.
Syntax
for example
int age=18;
“tri g sg=age>= ? Adult : Not Adult ;
CONTROL STATEMENTS
When a program breaks the sequential flow and jumps to another part of the
code, it is known as branching. When the branching is based on a particular
condition, it is known as conditional branching. If branching takes place
without any decision , it is known as unconditional branching.
Java supports two selection statements : if and switch. These statements allow
ou to o trol the flo of our progra s e e utio ased upo o ditio s
known only during run time.
if
The if statement can be used to route program execution through two
different paths.
Here is the general form of the if statement:
if (condition) statement1 ;
else statement2 ;
The if works like this : if the condition is true, then statement 1 is executed.
Otherwise , statement 2 (if it exists) is executed.
int a , b ;
//
if (a < b ) a =0;
b =0;
Here, if a is less than b, then a is set to zero. Otherwise, b is set to zero.
There is a program that counts the even and odd numbers in a list of
u ers usi g the if…else state e t. Nu er is a arra aria le
containing all the numbers and number.length gives the number of
elements in the array.
// e peri e ti g ith if…else state e t
class IfelseTest
{
public static void main (String args[ ] )
{
int number [ ] = { 50 , 65 , 56, 71, 81 } ;
int even = 0, odd = 0 ;
for ( int i= 0 ; i < number.length; i ++)
{
Output is :
Even number : 2 odd number : 3
Nested ifs
Here is an example:
if ( i == 10 )
{
if ( j < 20 )
a = b;
if ( k > 100 ) // this if is
c=d;
else a = c ; // associated with this else
}
else a = d; // this else refers to if ( i == 10 )
if ( condition )
statement;
else if ( condition )
statement;
else if ( condition )
statement ;
. ..
..
..
else
statement ;
The if statements are executed from the top down. As soon as one of the
conditions controlling the if is true, the statement associated with that if is
executed , and the rest of the ladder is bypassed.
If none of the conditions is true, then the final else statement will be executed.
The final else acts as a default condition; that is, if all other conditional tests
fail, then the last else statement is performed. If there is no final else and all
other conditions are false, then no action will take place.
switch (expression)
{
case value 1:
// statement sequence
break;
case value 2:
// statement sequence
break;
.
.
Case value N:
// statement sequence
break;
default:
// default statement sequence }
The expression must be type byte, short, int, or char; each of the values
specified in the case statements must be of a type compatible with the
expression. Each case value must be a unique literal (that is, it must be a
constant, not a variable). Duplicate case values are not allowed.
The switch statement works like this: the value of the expression is compared
with each of the literal values in the case statements. If a match is found, the
code sequence following that case statement is executed. If none of the
while ( condition )
{
// body of loop
}
The condition can be any Boolean expression. The body of the loop will be
executed as long as the conditional expression is true. When condition
becomes false, control passes to the next line of code immediately following
the loop.
Since the while loop evaluates its conditional expression at the top of the loop,
the body of the loop will not execute even once if the condition is false to
begin with.
Here is a while loop that counts down from 10, printing exactly ten lines of
ti k :
// demonstrate the while loop.
class While
{
public static void main ( String args [ ] )
{
int n = 10 ;
while ( n < 0 )
tick 10
tick 9
tick 8
tick 7
tick 6
tick 5
tick 4
tick 3
tick 2
tick 1
do – while
As you just saw, if the conditional expression controlling a while loop is initially
false, then the body of the loop will not be executed at all.
However, it is desirable to execute the body of a while loop at least once, even
if the conditional expression is false to begin with. The do – while loop always
executes its body at least once, because its conditional expression is at the
bottom of the loop.
Each iteration of the do – while loop first executes the body of the loop and
then evaluates the conditional expression. If this expression is true, the loop
for loop
Here is the general form of the for statement :
for ( initialization ; condition ; iteration )
{
//body
}
If only one statement is being repeated, there is no need for the curly braces.
The for loop operates as follows.
When the loop first starts, the initialization portion of the loop is
executed. Generally, this is an expression that sets the value of the loop
control variable, which acts as a counter that controls the loop.
Again, next is the iteration portion of the loop is executed. This is usually
an expression that increments or decrements the loop control variable.
Nested Loops
(Loop inside a loop) Java allows loops to be nested. That is, one loopmay be
inside another. For example, here is a program that nests for loops:
class Nested {
public static void main(String args[]) {
int i, j;
for(i=0; i<5; i++) {
for(j=1; j<i; j++)
{
System.out.println(j);
}
}
}}
Jump Statements
break
The break statement has three uses.
1. It terminates a statement sequence in a switch statement.
2. It can be used to exit a loop.
3. It a e used as a i ilized for of goto.
Continue Statement
Continue statement cause loop to bypass the current level
class Continue {
public static void main(String args[]) {
for(int i=0; i<10; i++) {
if (i == 5) continue;
System.out.print(i + " ");
}
}
}
Output:- 1 2 3 4 6 7 8 9
The class is at the core of java. It is the logical construct upon which the entire
java language is built because it defines the shape and nature of an object.
Perhaps the most important thing to understand about a class is that it defines
a new data type. (Once defined, this new type can be used to create objects of that type.
)
Defining a class
When you define a class, you declare its exact form and nature. You do this by
specifying the data that it contains and the code that operates on that data.
A class is a user-defined data type with a template that serves to define its
properties. O e the lass t pe has ee defi ed, e a reate aria les of
that type using declarations that are similar to the basic type declarations. In
java, these variables are termed as instances of classes, which are the actual
objects.
A class is declared by use of the class keyword. Classes can get much more
complex.
The general form is:
class classname
{
Type instance-variable1 ;
Type instance-variable2 ;
//
Type methodname 1 (parameter list)
{
// body of method
}
FIELD DECLARATION
Data is encapsulated in a class by placing data fields inside the body of the
class definition. These variables are called instance variables because they are
created whenever an object of the class is instantiated.
Example;
class Rectangle
{
int length ;
int width ;
}
The class Rectangle contains two integer type instance variables. It is allowed
to declare them in one line as
int length , width ;
METHOD DECLARATION
A class with only data fields (and without methods that operate on that data)
has no life. The objects created by such a class cannot respond to any
messages. We must add methods that are necessary for manipulating the data
contained in the class.
Methods are declared inside the body of the class but immediately after the
declaration of instance variables.
Examples:
( int m , float x , float y ) // three parameters
( ) // empty list
Let us consider the Rectangle class again and add a method getData( )
to it.
class Rectangle
{
int length ;
Note that the method has a return type of void because it does not
return any value.We pass two integer values to the method which are
then assigned to the instance variables length and width. The getData
method is basically added to provide values to the instance variables.
CREATING OBJECTS
Objects in java are created using the new operator. The new operator creates
an object of the specified class and returns a reference to that object.
The first statement declares a variable to hold the object reference and the
second one actually assigns the object reference to the variable. The variable
rect1 is now an object of the Rectangle class.
class Rectangle
{
int length , width ; // declaration of variables
void getData ( int x , int y ) // definition of method
{
length = x ;
width = y ;
}
int rectArea ( ) // definition of another method
{
int area = length * width ;
return ( area ) ;
}
}
class RectArea // class with main method
{
public static void main ( String args [ ] )
{
int area1, area 2 ;
Rectangle rect1 = new Rectangle ( ) ; // creating objects
Rectangle rect2 = new Rectangle ( ) ;
Rect1.length = 15 ; // accessing variables
Rect1.width = 10 ;
area1 = rect1.length * rect1.width ; // accessing methods
rect2.getData ( 20,12 ) ;
area2 = rect2.rectArea ( ) ;
“yste .out.pri tl Area = + area ;
Constructors
We know that all objects that are created must be given initial values. Java
supports a special type of method, called a constructor, that enables an object
to itself when it is created.
Constructors have the same name as the class itself. Secondly, they do not
specify a return type, not even void. This is because they return the instance of
the class itself.
We can now replace the getData method by a constructor method as shown
below:
Default Constructor
Parameterized constructor
class Car {
String name ; String model;
Car( ) //Default Constructor
{ name =""; model=""; }
}
Each time a new object is created at least one constructor will be invoked.
Car c = new Car() //Default constructor invoked
Car c = new Car(name); //Parameterized constructor invoked
Constructor Overloading
class Rectangle
{
int length ;
int width ;
Rectangle () // Default constructor
{
length = 0 ;
width = 0 ;
}
}
}
Output:
Area First 0
Area Second 120
Finalize method
JAVA Does t ha e destructor.
To add a finalizer to a class, you simply define the finalize( ) method. The Java
runtime calls that method whenever it is about to recycle an object of that
class.
Inside the finalize( ) method, you will specify those actions that must be
performed before an object is destroyed.
Defining a Subclass
The keyword extends signifies that the properties of the superclassname are
extended to the subclassname. The subclass will now contain its own variables
and methods as well those of the superclass.
The program defines a class Room and extends it to another class BedRoom.
Note that the class BedRoom defines its own data members and methods. The
subclass BedRoom now includes three instance variables, namely , length,
breadth and height and two methods ,area and volume.
Finally, the object room1 of the subclass BedRoom calls the method area
defined in the super class as well as the method volume defined in the subclass
itself.
Example
C
Here is we create object of C class it will go to B and B will move to A for
default constructor call.
class AA
{
public AA()
{
System.out.println("AA Class...");
}}
class BB extends AA
{
public BB()
{
System.out.println("BB Class");
}}
public class InherCons {
public static void main(String[] args) {
BB obj=new BB();
}}
Super Keyword
class Vehicle{
int gears=6;
}
class Bike extends Vehicle{
int gears=5;
void display(){
System.out.println(gears);
//will print gears of Bike
//super.gears will show gears of Vehicle
}
public static void main(String args[]){
Bike b=new Bike();
b.display();
}
The super keyword can also be used to invoke the parent class constructor as
given below:
class MySup
{
public MySup(int x) {
System.out.println("The square from super.."+(x*x));
}
}
class MySub extends MySup
{
public MySub(int y) {
super(y);
System.out.println("The cube from sub.."+(y*y*y));
}
}
public class InherSuper {
public static void main(String[] args) {
MySub obj=new MySub(6);
}
}
Note:
super() is added in each class constructor automatically by compiler. It call
default constructor of class.
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 .
class Student{
void message(){System.out.println("welcome");}
}
class BTechStudent extends Student{
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 args[]){
BTechStudent s=new BTechStudent();
s.display();
}
}
this keyword
Whenever the formal parameter and data member of the class are similar and
JVM gets an ambiguity (no clarity between formal parameter and data
members of the class).
class Employee
{
int id; String name;
Employee(int id,String name)
{
this.id = id;
this.name = name; }
void show()
{ System.out.println(id+" "+name);
}
public static void main(String args[])
{
Employee e1 = new Employee(111,"Harry"); e1.show();
}
}
The this() constructor call can be used to invoke the current class constructor
(constructor chaining). This approach is better if you have many constructors in
the class and want to reuse that constructor.
class Student{
int id;
String name;
Student(){System.out.println("default constructor is invoked");}
The this keyword can be used to invoke current class method (implicitly).
You may invoke the method of the current class by using the this keyword. If
you don't use the this keyword, compiler automatically adds this keyword
while invoking the method
class S{
void m(){
System.out.println("method is invoked");
}
void n(){
this.m();//no need because compiler does it for you.
}
void p(){
n();//complier will add this to invoke n() method as this.n()
}
public static void main(String args[]){
S s1 = new S();
s1.p();
} }
That means, we should override the method defined in the superclass. This is
possible by defining a method in the subclass that has the same name, same
arguments and same return type as a method in the superclass.Then , when
that method is called , the method defined in the subclass is invoked and
executed instead of the one in the superclass. This is known as overriding.
class Super
{
int x ;
Super ( int x )
{
this.x = x ;
}
void display ( ) // method defined
{
“ ste .out.pri tl “uper = + ;
}
}
….
..
.
class Sub extends Super
{
super (x) ;
this.y = y ;
“ ste .out.pri tl “u = + ;
classOverrideTest
s1. display ( ) ;
Output of program:
Super x = 100
Sub y = 200
class Animal{
a.eat(); } }
int id;
String name;
...
The static keyword in java is used for memory management mainly. We can
apply java static keyword with variables, methods, blocks and nested class. The
static keyword belongs to the class than instance of the class.
STATIC VARIABLE
Static variable are class level variable, for the static variable JVM allocate single
memory space which shared by all objects.
class Counter{
static int count=0;//will get memory when instance is created
Counter(){
count++;
System.out.println(count);
}
public static void main(String args[]){
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
} }
Output:
1
2
3
If you apply static keyword with any method, it is known as static method.
A static method belongs to the class rather than object of a class.
A static method can be invoked without the need for creating an instance of a
class.
static method can access static data member and can change the value of it.
class mstatic
{
public static void d()
{
System.out.println("Static call.");
}
public static void main(String args[])
{
d();//direct call
}
}
Output: Static call.
STATIC BLOCK
This block gets executed when the class is loaded in the memory. Static block is
mostly used for changing the default values of static variables.
A class can have multiple Static blocks, which will execute in the same
sequence in which they have been written into the program.
public class SecondStatic {
static
Example:
final int SIZE =100 ;
final void showstatus ( ) ………..
Making a method final ensures that the functionality defined in this method
will never be altered in any way.
Similarly, the value of a final variable can never be changed. Final variables,
behave like class variables and they do not take any space on individual objects
of the class.
class Demo{
final int MAX_VALUE=99;
void myMethod(){
MAX_VALUE=101;
}
public static void main(String args[]){
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The final field Demo.MAX_VALUE cannot be assigned
class XYZ{
final void demo(){
System.out.println("XYZ Class Method");
}
}
class ABC extends XYZ{
void demo(){
System.out.println("ABC Class Method");
}
The above program would throw a compilation error, however we can use the
parent class final method in sub class without any issues. Lets have a look at
this code: This program would run fine as we are not overriding the final
FINAL CLASSES
Sometimes we may like to prevent a class being further subclasses for security
reasons. A class that cannot be subclassed is called a final class. This is
achieved in java using the keyword final as follows:
9) final, finally and finalize are three different terms. finally is used in exception
handling and finalize is a method that is called by JVM during garbage
collection.
InstanceOf Operator
The java instanceof operator is used to test whether the object is an instance
of the specified type (class or subclass or interface).
Example
class Simple{
Output:
true
Example (Syntax)
abstract class <classname>
{
……………….
}
We cannot create object of this class.
abstract class Bike{
public void Hello()
{
System.out.println("Hello Bike");
}
}
public class AbstractFirst
{
public static void main(String args[]){
// Bike obj = new Bike(); // It will show compiler Error if we will create object
}
}
Interface
Using the keyword i terfa e, ou a full a stra t a lass i terfa e fro its
implementation. That is, using interface, you can specify what a class must do,
but not how it does it. Interfaces are syntactically similar to classes, but they
lack instance variables, and their methods are declared without any body.
I pra ti e, this ea s that ou a defi e i terfa es hi h do t ake
assumptions about how they are implemented. Once it is defined, any number
of classes can implement an interface. Also, one class can implement any
number of interfaces.
Example
interface inf {
void hello();
}
Declaring Interface
Interface inf
{ public void hello();
}
class TestIface {
public static void main(String args[]) {
inf c = new Client();
c.hello();
}
}
Variables can be declared inside of interface declarations. They are implicitly
final and static, meaning they cannot be changed by the implementing class.
They must also be initialized with a constant value. All methods and variables
are implicitly public if the interface, itself, is declared as public.
Example--
interface inf {
void hello();
}
class infImpl implements inf
{
public void hello()
{
System.out.println("Infimpl Hello");
}}
public class MyInterfaceOne implements inf
{
public void hello() {
System.out.println("Hello Implementation");
}
public static void main(String[] args) {
inf obj=new MyInterfaceOne(); //created reference of interface
1) Abstract class can have abstract Interface can have only abstract methods.
and non-abstract methods.
3) Abstract class can have final, Interface has only static and final
non-final, static and non-static variables.
variables.
4) Abstract class can have static Interface can't have static methods, main
methods, main method and method or constructor.
constructor.
7) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Inner class
An inner class is declared inside the curly braces of another enclosing class.
Inner class is coded inside a Top level class as shown below:-
class MyOuterClassDemo {
private int myVar= 1;
Inner class acts as a member of the enclosing class and can have any access
modifiers: abstract, final, public, protected, private, static.
class MyOuterClassDemo {
private int x= 1;
public void innerInstance()
{
MyInnerClassDemo inner = new MyInnerClassDemo();
inner. seeOuter();
}
public static void main(String args[]){
MyOuterClassDemo obj = new MyOuterClassDemo();
obj.innerInstance();
}
// inner class definition
class MyInnerClassDemo {
public void seeOuter () {
System.out.println("Outer Value of x is :" + x);
}
} // close inner class definition
} // close Top level class definition
Output:
Outer Value of x is :1
The public static void main code in the above example can be replaced with
this one. It will also give the same output.
A static nested classes are the inner classes marked with static modifier.
Because this is static in nature so this type of inner class does t share any
special kind of relationship with an instance of outer class.A static nested class
cannot access non static members of outer class.
Example:
class Outer{
static class Nested{}
}
A static nested class can be instantiated like this:
Example:-
class Outer{// outer class
static class Nested{}// static nested class
}
class Demo{
public static void main(String[] args){ // use both class names
Outer.Nested n= new Outer.Nested();
}
}
Wrapper class in java are the Object representation of eight primitive types in
java. All the wrapper classes in java are immutable and final. Java 5 auto boxing
and unboxing allows easy conversion between primitive types and their
corresponding wrapper classes in java programs.
Below table shows the primitive types and their wrapper class in java.
The most common methods of the Integer wrapper class are summarized in
below table.
Method Purpose
parseInt(s) returns a signed decimal integer value equivalent to
string s
toString(i) returns a new String object representing the integer i
byteValue() returns the value of this Integer as a byte
doubleValue() returns the value of this Integer as an double
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 student
{ ...statement; }
For example the .class for any classes you to define to be part
of mypack package must be stored in a directory called mypack.
If you declare a method by using the default scope, any method can use it as
long as it resides in the same package. In addition, if you create a class that
hashCode Method
public native int hashCode();
3) If two objects are not equals by equals() method it is not require that there
hash ode ust e differe t. Though it s al a s good pra ti e to retur
different hashCode for unequal object. Different hashCode for distinct object
can improve performance of hashmap or hashtable by reducing collision.
String Handling
Character
String:
String is a sequence of characters enclosed within double quotes (" ") is known
as String.
Example: "Java Programming".
String
StringBuffer
StringBuilder
Creating a String
String literal
In java, Strings can be created like this: Assigning a String literal to a String
instance:
The problem with this approach: As I stated in the beginning that String is an
object in Java. However we have not created any string object using new
keyword above. The compiler does that task for us it creates a string object
ha i g the stri g literal that e ha e pro ided, i this ase it is Wel o e
and assigns it to the provided string instances.
But if the object already exist in the memory it does not create a new Object
rather it assigns the same old object to the new instance, that means even
though we have two string instances above(str1 and str2) compiler only
created on string o je t ha i g the alue Wel o e a d assig ed the sa e
to both the instances. For example there are 10 string instances that have
same value, it means that in memory there is only one object having the value
and all the 10 string instances would be pointing to the same object.
What if we want to have two different object with the same string? For that
we would need to create strings using new keyword.
As we saw above that when we tried to assign the same string object to two
different literals, compiler only created one object and made both of the
literals to point the same object. To overcome that approach we can create
strings like this:
1.Length()
length(): This method is used to get the number of character of any string.
Example
class StringHandling
int l;
l=s.length();
System.out.println("Length: "+l);
Output – Length 4
2.charAt()
Example
class StringHandling
char c;
c=s.charAt(2);
System.out.println("Character: "+c);
Output
Character: v
3.toCharArray( )
If you want to convert all the characters in a String object into a character
array, the easiest way is to call toCharArray( ). It returns an array of characters
for the entire string. It has this
general form:
char[ ] toCharArray( )
String Comparison
The String class includes several methods that compare strings or substrings
within strings
Here, str is the String object being compared with the invoking String object. It returns
Here, str is the String object being compared with the invoking String object. It,
too, returns true if the strings contain the same characters in the same order,
and false otherwise.
class equalsDemo {
String s1 = "Hello";
String s2 = "Hello";
String s4 = "HELLO";
System.out.println(s1.equals(s2)); // true
System.out.println(s1.equalsIgnoreCase(s4)); //true
toUpperCase(): This method is use to convert lower case string into upper case.
Example
class StringHandling
String s="Java";
System.out.println("String: "+s.toUpperCase());
Output
String: JAVA
5. toLowerCase()
toLowerCase(): This method is used to convert lower case string into upper
case.
Example
class StringHandling
String s="JAVA";
Output
String: java
6.concat()
Example
class StringHandling
String s1="RAJ";
String s2="Raddy";
Output
Example
class StringHandling
String s1="Anil";
String s2="Raddy";
int i;
i=s1.compareTo(s2);
if(i==0)
else
}}
Output
Example
class StringHandling
String s1="raj";
String s2="RAJ";
int i;
i=s1.compareToIgnoreCase(s2);
if(i==0)
else
}}}
Output
startsWith(): This method return true if string is start with given another string,
otherwise it returns false.
Example
class StringHandling
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.startsWith("Java"));
}
}
Output
true
10.endsWith()
endsWith(): This method return true if string is end with given another string,
otherwise it returns false.
Example
class StringHandling
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.endsWith("language"));
}
}
Output
true
Example
class StringHandling
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.substring(8)); // 8 is starting index
}
}
Output
programming language
Example
class StringHandling
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.substring(8, 12));
}
}
Output
prog
trim(): This method remove space which are available before starting of string
and after ending of string.
Example
class StringHandling
{
public static void main(String arg[])
{
String s=" Java is programming language ";
System.out.println(s.trim());
}}
Output
13.split()
split(): This method is used to divide the given string into number of parts
based on delimiter (special symbols like @ space , ).
Example
class StringHandling
{
public static void main(String arg[])
{
String s="[email protected]";
String[] s1=s.split("@"); // divide string based on @
for(String c:s1) // foreach loop
{ System.out.println(c);
}}}
Output
contact
@myway.com
Example
class StringHandling
String s1="java";
System.out.println(s2);
}}
Output
kava
Exception Handling
An Exception can be anything which interrupts the normal flow of the
program. When an exception occurs program processing gets terminated and
does t o ti ue further. I su h ases e get a s ste ge erated error
message. The good thing about exceptions is that they can be handled.
Exceptions are conditions within the code. A developer can handle such
conditions and take necessary corrective actions.
Few examples –
DivideByZero exception
NullPointerException
ArithmeticException
ArrayIndexOutOfBoundsException
try
catch
finally
throw
throws
Java try block is used to enclose the code that might throw an exception. It
must be used within the method.
Java catch block is used to handle the Exception. It must be used after the try
block only.
try{
int data=50/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
a[5]=30/0;
Java finally block is a block that is used to execute important code such as
closing connection, stream etc.
throw exception;
In this example, we have created the validate method that takes integer value
as a parameter. If the age is less than 18, we are throwing the
ArithmeticException otherwise print a message welcome to vote.
if(age<18)
else
System.out.println("welcome to vote");
Let's see the example of java throws clause which describes that checked
exceptions can be propagated by throws keyword.
import java.io.IOException;
class Testthrows1{
m();
void p(){
try{
n();
obj.p();
System.out.println("normal flow...");
There are many differences between throw and throws keywords. A list of
differences between throw and throws are given below:
4) Throw is used within the method. Throws is used with the method
signature.
The life cycle of the thread in java is controlled by JVM. The java thread
states are as follows:
New
Runnable
Running
Non-Runnable (Blocked)
Terminated
Starting a thread:
start() method of Thread class is used to start a newly created thread. It
performs following tasks:
A new thread starts(with new call stack).
The thread moves from New state to the Runnable state.
When the thread gets a chance to execute, its target run() method
will run.
1)By extending Thread class:
System.out.println("thread is running...");
t1.start();
Output:thread is running...
System.out.println("thread is running...");
t1.start();
If you are not extending the Thread class,your class object would not be
treated as a thread object.So you need to explicitely create Thread class
object.We are passing the object of your class that implements Runnable so
that your class run() method may execute
The sleep() method of Thread class is used to sleep a thread for the specified
amount of time.
for(int i=1;i<5;i++)
Try
Thread.sleep(500);
catch(InterruptedException e)
System.out.println(e);}
System.out.println(i);
t1.start();
t2.start(); } }
Output:
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start(); } }
There are two sets of Java APIs for graphics programming: AWT
(Abstract Windowing Toolkit) and Swing.
1. AWT API was introduced in JDK 1.0. Most of the AWT components have
become obsolete and should be replaced by newer Swing components.
2. Swing API, a much more comprehensive set of graphics libraries that
enhances the AWT, was introduced as part of Java Foundation Classes
(JFC) after the release of JDK 1.1. JFC consists of Swing, Java2D,
Accessibility, Internationalization, and Pluggable Look-and-Feel Support
APIs. JFC was an add-on to JDK 1.1 but has been integrated into core Java
since JDK 1.2.
3. AWT contains large number of classes and methods that allows you to
create and manage windows GUI application.
AWT Hierarchy
Window class creates a top level window. Window does not have borders and
menubar.
AWT Container
AWT Controls
Frame
Frame is a container, it is java based GUI program. The class Frame is a top
level window with border and title. It will run with help of main function.
Example
import java.awt.*;
public class MyFrame {
public static void main(String[] args) {
Frame f;
f=new Frame("First Frame");
f.setSize(300,300);
f.setVisible(true);
}
}
Method 2
import java.awt.*;
public class MyFrameOne extends Frame{
public MyFrameOne() {
setTitle("My");
setBackground(Color.RED);
setSize(300,300);
setVisible(true);
Applet is initialized.
Applet is started.
Applet is painted.
Applet is stopped.
Applet is destroyed.
java.applet.Applet class
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is
maximized. It is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet
is stop or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only
once.
By html file.
To execute the applet by html file, create an applet and compile it. After that
create an html file and place the applet code in html file. Now click the html
file.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
g.drawString("welcome",150,150);
} }
Note: class must be public because its object is created by Java Plugin
software that resides on the browser.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
g.drawString("welcome to applet",150,150);
} }
/*
</applet>
*/
c:\>javac First.java
c:\>appletviewer First.java
Advantage of Applet
Secured
public abstract void drawString(String str, int x, int y): is used to draw the
specified string.
public void drawRect(int x, int y, int width, int height): draws a rectangle with
the specified width and height.
public abstract void fillRect(int x, int y, int width, int height): is used to fill
rectangle with the default color and specified width and height.
public abstract void drawOval(int x, int y, int width, int height): is used to
draw oval with the specified width and height.
public abstract void fillOval(int x, int y, int width, int height): is used to fill
oval with the default color and specified width and height.
public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line
between the points(x1, y1) and (x2, y2).
public abstract void drawArc(int x, int y, int width, int height, int startAngle,
int arcAngle): is used draw a circular or elliptical arc.
public abstract void fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used to fill a circular or elliptical arc.
public abstract void setFont(Font font): is used to set the graphics current font
to the specified font.
Example
import java.applet.Applet;
import java.awt.*;
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
} }
Labels
Buttons
Check boxes
Choice lists
Lists
TextField
TextArea
Here, compObj is an instance of the control that you want to add. A reference
to compObj is returned. Once a control has been added, it will automatically
be visible whenever its parent window is displayed.
Sometimes you will want to remove a control from a window when the control
is no longer needed. To do this, call remove( ). This method is also defined by
Container.
Label
The easiest control to use is a label. A label is an object of type Label, and it
contains a string, which it displays. Labels are passive controls that do not
support any interaction with the user. Label defines the following constructors:
Label(String str)
You can set or change the text in a label by using the setText( ) method. You
can obtain the current label by calling getText( ).
String getText( )
For setText( ), str specifies the new label. For getText( ), the current label is
returned.
Button
The most widely used control is the push button. A push button is a
component that contains a label and that generates an event when it is
pressed. Push buttons are objects of type Button. Button defines these two
constructors:
Button( )
Button(String str)
The first version creates an empty button. The second creates a button that
contains str as a label.
After a button has been created, you can set its label by calling setLabel. You
can retrieve its label by calling getLabel.
String getLabel( )
Checkbox
Checkbox( )
Checkbox(String str)
boolean getState( )
String getLabel( )
Choice
The Choice class is used to create a pop-up list of items from which the user
may choose. Thus, a Choice control is a form of menu.
int getItemCount( )
TextField
Text fields allow the user to enter strings and to edit the text using the arrow
keys, cut and paste keys, and mouse selections. TextField is a subclass of
TextComponent. TextField defines the following constructors:
TextField( )
TextField(int numChars)
TextField(String str)
String getText( )
Sometimes a single line of text input is not enough for a given task. To handle
these situations, the AWT includes a simple multiline editor called TextArea.
TextArea( )
TextArea(String str)
Here, numLines specifies the height, in lines, of the text area, and numChars
specifies its width, in characters. Initial text can be specified by str. In the fifth
form you can specify the scroll bars that you want the control to have. sBars
must be one of these values:
SCROLLBARS_BOTH , SCROLLBARS_NONE
SCROLLBARS_HORIZONTAL_ONLY
SCROLLBARS_VERTICAL_ONLY
java.awt.FlowLayout
java.awt.BorderLayout
java.awt.GridLayout
java.awt.CardLayout
1.FlowLayout
The FlowLayout is used to arrange the components in a line, one after another
(in a flow). It is the default layout of applet or panel.
FlowLayout(int align): creates a flow layout with the given alignment and a
default 5 unit horizontal and vertical gap.
FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given
alignment and the given horizontal and vertical gap.
2.BorderLayout
BorderLayout.CENTER, BorderLayout.SOUTH
BorderLayout.EAST, BorderLayout.WEST
BorderLayout.NORTH
When adding components, you will use these constants with the following
form of
GridLayout( )
Event Handling
Any program that uses GUI (graphical user interface) such as Java application
written for windows, is event driven.
Example :
Event
Event Listeners
A listener is an object that is notified when an event occurs. It has two major
requirements. First, it must have been registered with one or more sources to
receive notifications about specific types of events. Second, it must implement
methods to receive and process these notifications.
The methods that receive and process events are defined in set of interfaces
found in java.awt.event. For example, the MouseMotionListener interface
defines two methods to receive notifications when the mouse is dragged or
moved.
Event Classes
EventObject(Object src)
Object getSource( )
addListenername(Object)
ie.
btnObject.addActionListener(this)
ActionListener
KeyListener
ItemListener
TextListener
AdjustmentListener
WindowListener
ComponentListener
ContainerListener
FocusListener
Event Handler
Each Listener has one or more event handler function that must be
implemented in order to handle event response
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
Button btn;
add(btn);
btn.addActionListener(this);
setBackground(Color.RED);
} } }
Java uses the concept of stream to make I/O operation fast. The java.io
package contains all the classes required for input and output operations.
Stream
In java, 3 streams are created for us automatically. All these streams are
attached with console.
InputStream
Java application uses an input stream to read data from a source, it may be a
file,an array,peripheral device or socket.
Method Description
Method Description
Character Streams
Reader and Writer are the abstract superclasses for character streams
in java.io. Reader provides the API and partial implementation for readers--
streams that read 16-bit characters--andWriter provides the API and partial
implementation for writers--streams that write 16-bit characters. Subclasses
of Reader and Writer implement specialized streams and are divided into two
categories: those that read from or write to data sinks (shown in gray in the
following figures) and those that perform some sort of processing (shown in
white). The figure shows the class hierarchies for
the Reader and Writer classes.
Byte Streams
To read and write 8-bit bytes, programs should use the byte streams,
descendants
of InputStream and OutputStream. InputStream and OutputStream provide the
API and partial implementation for input streams (streams that read 8-bit
import java.io.IOException;
import java.io.InputStreamReader;
String s = bufferRead.readLine();
System.out.println(s);
catch(IOException e)
e.printStackTrace();
Here, fileName specifies the name of the file that you want to open. When you
create an input stream, if the file does not exist, then FileNotFoundException
Example
import java.io.*;
class MyFileOutputStream {
public static void main(String args[]) throws Exception {
String source = "Now is the time for all good people"
+ " to come to the aid of their country\n";
byte buf[] = source.getBytes();
FileOutputStream f0 = new FileOutputStream("D:\\file1.txt");
for (int i=0; i < buf.length; i += 2) {
f0.write(buf[i]);
}
}
}
File Class
File(String directoryPath)
File(String directoryPath, String filename)
File defines many methods that obtain the standard properties of a File object.
For example, getName( ) returns the name of the file, getParent( ) returns the
name of theparent directory, and exists( ) returns true if the file exists, false if
it does not.
The java.lang.Class class provides many methods that can be used to get
metadata, examine and change the run time behaviour of a class.
The java.lang and java.lang.reflect packages provide classes for java reflection.
The first component of the Reflection API is the mechanism used to fetch
information about a class. This mechanism is built into the class named Class.
The special class Class is the universal type for the meta information that
describes objects within the Java system. Class loaders in the Java system
return objects of type class.
Up until now the three most interesting methods in this class were:
forName, which would load a class of a given name, using the current class
loader
getName, which would return the name of the class as a String object, which
was useful for identifying object references by their class name
newInstance, which would invoke the null constructor on the class (if it exists)
and return you an object instance of that class of object.
To these three useful methods the Reflection API adds some additional
methods to class Class.
Example
import java.lang.reflect.*;
try {
Class c = Class.forName("java.awt.Graphics");
System.out.println("Constructors:");
System.out.println("Fields:");
System.out.println("Methods:");
catch(Exception e)
All the operations that you perform on a data such as searching, sorting,
insertion, manipulation, deletion etc. can be performed by Java Collections.
Algorithm
Collection Framework
Let us see the hierarchy of collection framework.The java.util package contains
all the classes and interfaces for Collection framework.
Iterator interface
List interface
The List interface extends Collection and declares the behaviour of a collection
that stores a sequence of elements. Elements can be inserted or accessed by
their position in the list, using a zero-based index. A list may contain duplicate
elements. A list is an ordered sequence of elements
List implementation
AbstractList Extends AbstractCollection and implements most of the List
interface.
AbstractSequentialList Extends AbstractList for use by a collection that uses
sequential rather than random access of its elements.
ArrayList
The ArrayList class extends AbstractList and implements the List interface.
ArrayList supports dynamic arrays that can grow as needed.
ArrayList( )
ArrayList(Collection c)
ArrayList(int capacity)
Example
import java.util.*;
}
Output
[ABC, 120, Test, true, 123]
[ABC, Test, true, 123]
ABC
Test
true
123
LinkedList
package com.MyCollection;
import java.util.*;
public class MyLinkedList {
/**
* @param args
*/
public static void main(String[] args) {
LinkedList lt=new LinkedList();
lt.add(12);
lt.add("RRRR");
lt.add(99);
System.out.println(lt);
lt.addFirst("WWWW");
System.out.println(lt);
lt.addLast("LLL");
System.out.println(lt);
System.out.println(lt.getLast());
System.out.println(lt.get(2));
Set Interface
The Set interface defines a set. It extends Collection and declares the behavior
of a collection that does not allow duplicate elements. Therefore, the add( )
method returns false if an attempt is made to add duplicate elements to a set.
It does not define any additional methods of its own.
Set Implementations
HashSet implements the Set interface. It creates a collection that uses a hash
table for storage.
HashSet( )
HashSet(Collection c)
HashSet(int capacity)
HashSet(int capacity, float fillRatio)
HashSet does not define any additional methods beyond those provided by its
superclasses and interfaces.
TreeSet provides an implementation of the Set interface that uses a tree for
storage. Objects are stored in sorted, ascending order. Access and retrieval
times are quite fast,which makes TreeSet an excellent choice when storing
large amounts of sorted information that must be found quickly.
import java.util.*;
public class MyTreeSet {
/**
* @param args
*/
public static void main(String[] args) {
TreeSet ts=new TreeSet();
ts.add("FFF");
ts.add("PPP");
ts.add("ZZZ");
ts.add("AAA");
ts.add("MMM");
System.out.println(ts);
Iterator its=ts.iterator();
while(its.hasNext())
{
System.out.println(its.next());
}
}
}
Output
[AAA, FFF, MMM, PPP, ZZZ]
AAA
FFF
MMM
PPP
ZZZ
Example
import java.util.*;
getDateInstance
DateFormat df = DateFormat.getDateInstance();
Converting to a String
You can convert a Date object to a string with the format method. This is
shown in the following demonstration program:
Example
import java.util.*;
import java.text.*;
DateFormat df = DateFormat.getDateInstance();
String s = df.format(now);
}}
Some examples are SHORT, MEDIUM, LONG, and FULL, which are
demonstrated in the program below:
Example
import java.util.*;
import java.text.*;
String s = df.format(now);
String s1 = df1.format(now);
String s2 = df2.format(now);
String s3 = df3.format(now);
String s4 = df4.format(now);
Note that for the month, January is 0, February is 1, and so on, until December,
which is 11. Since those are not the numbers most of us associate with the
months of the year, programs will probably be more readable if they use the
constants of the parent Calendar class: JANUARY, FEBRUARY, and so on. So, to
create an object representing the date that Wilbur and Orville Wright first flew
their motored aircraft (December 17, 1903), you can use:
For clarity's sake, you should use the preceding form. However, you should
also learn how to read the shorter form, below. The following example
represents the same December 17, 1903, date (remember, in the shorter
form 11 represents December):
In the previous section, you learned how to turn Date objects into Strings. You
will do the same again; but first, you need to convert
a GregorianCalendarobject to a Date. To do so, you will use
the getTime() method, which GregorianCalendar inherits from its
parent Calendar class. The getTime()method returns a Date corresponding to
a GregorianCalendar object. You can put the whole process of creating
a GregorianCalendar object, converting it to a Date, and getting and outputting
the corresponding String in the following program:
import java.util.*;
Date d = firstFlight.getTime();
DateFormat df = DateFormat.getDateInstance();
String s = df.format(d);
Example
import java.util.*;
import java.text.*;
class Today {
Date d = thisday.getTime();
DateFormat df = DateFormat.getDateInstance();
String s = df.format(d);
}}
java.util.regex package
It provides following classes and interface for regular expressions. The Matcher
and Pattern classes are widely used in java regular expression.
MatchResult interface
Matcher class
Pattern class
PatternSyntaxException class
Matcher class
3 boolean find(int start) finds the next expression that matches the
pattern from the given start number.
import java.util.regex.*;
public class RegexExample1{
public static void main(String args[]){
//1st way
Pattern p = Pattern.compile(".s");//. represents single character
Matcher m = p.matcher("as");
boolean b = m.matches();
//3rd way
boolean b3 = Pattern.matches(".s", "as");
Regular Expression
Example
import java.util.regex.*;
class RegexExample2
5 [a-z&&[def]] d, e, or f (intersection)
import java.util.regex.*;
class RegexExample3
Regex Quantifiers
The quantifiers specify the number of occurrences of a character.
Regex Description
X? X occurs once or not at all
import java.util.regex.*;
class MyRegExWild {
int c=0;
while(mat.find())
c=c+1;
System.out.print(c);
Pattern pat1 = Pattern.compile("J.P");
Matcher mat1 = pat1.matcher("J JP JSP ASP JAVA");
while(mat1.find())
System.out.println("Match: " + mat1.group());
}
}
Example to show [] usage
import java.util.regex.*;
class MyRegExWildNew {
while(mat.find())
Generics was first introduced in Java5. Now it is one of the most profound
feature of java programming language. It provides facility to write algorithm
independent of any specific type of data. Generics also provide type safety.
Before generics, we can store any type of objects in collection i.e. non-generic.
Now generics, forces the java programmer to store specific type of objects.
list.add("hello");
list.add("hello");
String s = list.get(0);
list.add("hello");
import java.util.*;
class TestGenerics1{
list.add("rahul");
list.add("jai");
Iterator<String> itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
A class that can refer to any type is known as generic class. Here, we are
using T type parameter to create the generic class of specific type.
Let s see the simple example to create and use the generic class.
class MyGen<T>{
T obj;
T get(){return obj;}
The T type indicates that it can refer to any type (like String, Integer, Employee
etc.). The type you specify for the class, will be used to store and retrieve the
data.
class TestGenerics3{
m.add(2);
System.out.println(m.get());
}}
T - Type
E - Element
K - Key
N - Number
V - Value
Generic Method
Like generic class, we can create generic method that can accept any type of
argument.
Let s see a si ple e a ple of ja a ge eri ethod to pri t arra ele e ts. We
are using here E to denote the element.
System.out.println(element );
System.out.println();
printArray( intArray );
printArray( charArray );
Do You Know ?
How can we globalize the messages (or) What is the use of ResourceBundle
class?
Before starting the internationalization, Let's first understand what are the
information that differ from one region to another. There is the list of
culturally dependent data:
Messages
Dates
Times
Numbers
Currencies
Measurements
Phone Numbers
public String getDisplayVariant() it returns the variant code for this locale
object.
public String getISO3Country() it returns the three letter abbreviation for the
current locale's country.
public String getISO3Language() it returns the three letter abbreviation for the
current locale's language.
Example of Local class that prints the informations of the default locale
In this example, we are displaying the informations of the default locale. If you
want to get the informations about any specific locale, comment the first line
statement and uncomment the second line statement in the main method.
Locale locale=Locale.getDefault();
System.out.println(locale.getDisplayCountry());
System.out.println(locale.getDisplayLanguage());
System.out.println(locale.getDisplayName());
System.out.println(locale.getISO3Country());
System.out.println(locale.getISO3Language());
System.out.println(locale.getLanguage());
System.out.println(locale.getCountry());
import java.util.*;
enLocale.getDisplayLanguage());
enLocale.getDisplayLanguage(frLocale));
enLocale.getDisplayLanguage(esLocale));
import java.util.*;
}}
} Output:en_US: English
es_ES: espa?ol
it_IT: italiano
Use of Serialization
Write to Disk
Store in Memory
After a serialized object has been written into a file, it can be read from the file
and deserialized that is, the type information and bytes that represent the
object and its data can be used to recreate the object in memory.
The above method serializes an Object and sends it to the output stream.
Similarly, the ObjectInputStream class contains the following method for
deserializi g a o je t −
This method retrieves the next Object out of the stream and deserializes it. The
return value is Object, so you will need to cast it to its appropriate data type.
Example-
import java.io.*;
All of the fields in the class must be serializable. If a field is not serializable, it
must be marked transient.
If you are curious to know if a Java Standard Class is serializable or not, check
the documentation for the class. The test is simple: If the class implements
java.io.Serializable, then it is serializable; otherwise, it's not.
import java.io.*;
emp.ename="Raju";
emp.eCity="Agra";
try
op.writeObject(emp);
op.close();
System.out.println("Data Saved...");
catch(Exception e)
System.out.println(e.getMessage());
} } }
import java.io.*;
emp=(Employee)oin.readObject();
System.out.println(emp.ename);
System.out.println(emp.eCity);
}}
Identifiers Java, Cpp, C and Dbms are called enumeration constants. These are
public, static final by default.
Subject sub
sub = Subject.Java;
Example---
Sunday, Monday,Tuesday,Wednesday,Thursday,Friday;
public enumk()
System.out.println(weak.Monday);
System.out.println(weak.Saturady);
Output--
Monday
Saturday
System.out.println(i+" "+iob);
System.out.println(cob+" "+ch);
Output :
100 100
aa
++iOb;
This will happen always, when we will use Wrapper class objects in expressions
or conditions etc.
Autoboxing / Unboxing lets us use primitive types and Wrapper class objects
interchangeably.
It helps prevent errors, but may lead to unexpected results sometimes. Hence
must be used with care.
The static import feature of Java 5 facilitate the java programmer to access any
static member of a class directly. There is no need to qualify it by the class
name.
Less coding is required if you have access any static member of a class oftenly.
If you overuse the static import feature, it makes the program unreadable and
unmaintainable.
class StaticImportExample{
out.println("Java");
Output: Hello
Java
@Override
@SuppressWarnings
@Deprecated
@Target
@Retention
@Inherited
@Documented
@Override
Sometimes, we does the silly mistake such as spelling mistakes etc. So, it is
better to mark @Override annotation that provides assurity that method is
overridden.
class Animal{
void eatSomething(){System.out.println("eating something");}
}
class TestAnnotation1{
a.eatSomething();
}}
@SuppressWarnings
import java.util.*;
class TestAnnotation2{
@SuppressWarnings("unchecked")
list.add("sonoo");
list.add("vimal");
list.add("ratan");
for(Object obj:list)
}}
@Deprecated
assert expression;
Example
import java.util.Scanner;
class AssertionExample{
System.out.println("value is "+value);
If you use assertion, It will not run simply because assertion is disabled by
default. To enable the assertion, -ea or -enableassertions switch of java must