Java Notes (Class)
Java Notes (Class)
Unit-I
Introduction to Java
A. Features of OOPS:
1. CLASS: Class is a collection of objects of similar type. Once a class has been defined, we
can create any number of objects belonging to that class. It is a logical entity. Example: Fruit;
NOTE: Classes are user defined data types.
2. OBJECT: Object is a basic runtime entity. Objects are reference variables of type class
and take up space in the memory. Objects are instances of classes. Any entity that has state and
behavior is known as an object. It can be physical and logical. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.
3. DATA ABSTRACTION: Hiding the complexity of program is called Abstraction and only
essential features are represented. In short we can say that internal working is hidden. Hiding
internal details and showing functionality is known as abstraction. In java, we use abstract
class and interface to achieve abstraction.
4. ENCAPSULATION: Combining data and functions into a single unit called class and
the process is known as Encapsulation. Data is not accessible from the outside world. Binding
(or wrapping) code and data together into a single unit is known as encapsulation. A
java class is the example of encapsulation.
5. INHERITANCE: it is the process by which object of one class acquire the properties or
features of objects of another class. The concept of inheritance provide the idea of
reusability means we can add additional features to an existing class without Modifying it.
6. POLYMORPHISM: A Greek term means ability to take more than one form. An
operation may exhibit different behaviors in different instances. The behavior depends upon the
types of data used in the operation. In java, we use method overloading and method
overriding to achieve polymorphism.
7. DYNAMIC BINDING: Refers to linking of function call with function definition is called
binding and when it is take place at run time called dynamic binding.
8. MESSAGE PASSING: The process by which one object can interact with other object
is called message passing.
10. REUSABILITY OF CODE: Code reuse, also called software reuse, is the use of existing
software, or software knowledge, to build new software, following the reusability principles.
11. MODULARITY OF CODE: Modularity is the degree to which a system's components may
be separated and recombined. Modularity is a software design technique that emphasizes
separating the functionality of a program into independent, interchangeable modules, such that
each contains everything necessary to execute only one aspect of the desired functionality.
B. Benefits of OOPS:
1. Reusability: In OOP’s programs functions and modules that are written by a user can be
reused by other users without any modification.
2. Inheritance: Through this we can eliminate redundant code and extend the use of existing
classes.
3. Data Hiding: The programmer can hide the data and functions in a class from other classes.
It helps the programmer to build the secure programs.
4. Reduced complexity of a problem: The given problem can be viewed as a collection of
different objects. Each object is responsible for a specific task. The problem is solved by
interfacing the objects. This technique reduces the complexity of the program design.
5. Easy to Maintain and Upgrade: OOP makes it easy to maintain and modify existing code
as new objects can be created with small differences to existing ones.
6. Message Passing: The technique of message communication between objects makes the
interface with external systems easier.
7. Modifiability: it is easy to make minor changes in the data representation or the procedures
in an OO program. Changes inside a class do not affect any other part of a program, since
the only public interface that the external world has to a class is through the use of methods.
8. Security: OOPS is more secure than procedure oriented languages
C. Comparisons:
Approach POP follows Top Down approach. OOP follows Bottom Up approach.
Access POP does not have any access OOP has access specifiers named Public,
Specifiers specifier. Private, Protected, etc.
Data Moving In POP, Data can move freely from objects can move and communicate with
function to function in the system. each other through member functions.
Expansion To add new data and function in OOP provides an easy way to add new
POP is not so easy. data and function.
Data Access In POP, Most function uses Global In OOP, data cannot move easily from
data for sharing that can be function to function, it can be kept public
accessed freely from function to or private so we can control the access
function in the system. of data.
Data Hiding POP does not have any proper way OOP provides Data Hiding so
for hiding data so it is less secure. provides more security.
Overloading In POP, Overloading is not possible. overloading is possible in the form of
Function and Operator Overloading.
Examples Example of POP are : C, VB, Example of OOP are : C++, JAVA,
FORTRAN, Pascal. VB.NET, C#.NET.
2. C Vs. Java
C Programming Java Programming
1 Procedure Oriented Object Oriented
2 Function is a basic programming unit Class is a basic programming unit (ADT)
3 Platform Dependant Platform independent and portable
4 One step compilation process Two step process i.e. Compilation and
Interpretation
5 Concept of pointer is used No pointers used in java
6 Source code directly converted to machine Source code is converted into byte code
code then it is interpreted by JVM to machine
code
7 Manual management of memory using Automatic management of memory using
malloc() and free() garbage collector
8 Less secure More secure
9 Provides preprocessors Doesn't provides preprocessors
10 Does not supports for function overloading Supports method overloading
D. History of Java:
1. James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in
June 1991. The small team of sun engineers called Green Team.
2. Originally designed for small, embedded systems in electronic appliances like set-top boxes.
3. Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
4. After that, it was called Oak and was developed as a part of the Green project.
5. Why Oak? Oak is a symbol of strength and choosen as a national tree of many countries like
U.S.A., France, Germany, Romania etc.
6. In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
7. Why they choose java name for java language? The team gathered to choose a new
name. The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA" etc. They
wanted something that reflected the essence of the technology: revolutionary, dynamic,
lively, cool, unique, and easy to spell and fun to say.
8. According to James Gosling "Java was one of the top choices along with Silk". Since java was
so unique, most of the team members preferred java.
9. Java is an island of Indonesia where first coffee was produced (called java coffee).
10. Notice that Java is just a name not an acronym.
11. Originally developed by James Gosling at Sun Microsystems (which is now a subsidiary of
Oracle Corporation) and released in 1995.
12. In 1995, Time magazine called Java one of the Ten Best Products of 1995.
13. JDK 1.0 released in(January 23, 1996)
14. There are many java versions that has been released. Current stable release of Java is Java
SE 8.
1) Standalone Application
It is also known as desktop application or window-based application. AWT and Swing are used in
java for creating standalone applications.
2) Web Application
An application that runs on the server side and creates dynamic page, is called web application.
Currently, servlet, jsp, struts, jsf etc. technologies are used for creating web applications in java.
3) Enterprise Application
An application that is distributed in nature, such as banking applications etc. In java, EJB is used
for creating enterprise applications.
4) Mobile Application
An application that is created for mobile devices. Currently Android and Java ME are used for
creating mobile applications.
F. Features of Java:
Simple
According to Sun, Java language is simple because: Syntax is based on C++ (so easier for
programmers to learn it after C++). removed many confusing and/or rarely-used features e.g.,
explicit pointers, operator overloading etc.
Object-oriented
Object-oriented means we organize our software as a combination of different types of objects
that incorporates both data and behavior. Object-oriented programming(OOPs) is a methodology
that simplify software development and maintenance by providing some rules. Basic concepts of
OOPs are: Object, Class, Polymorphism, Abstraction, Inheritance, Encapsulation
Platform Independent
A platform is the hardware or software environment in which a program runs. There are two
types of platforms software-based and hardware-based. Java provides software-based platform.
The Java platform differs from most other platforms in the sense that it's a software-based
platform that runs on top of other hardware-based platforms. It has two components:
1. Runtime Environment 2. API(Application Programming Interface)
Java code can be run on multiple platforms e.g. Windows, Linux, Sun Solaris, Mac/OS etc. Java
code is compiled by the compiler and converted into bytecode. This bytecode is a platform
independent code because it can be run on multiple platforms i.e. Write Once and Run
Anywhere(WORA).
Secured
Java is secured because:
• No explicit pointer
• Programs run inside virtual machine sandbox.
• Class loader- adds security by separating the package for the classes of the local file system
from those that are imported from network sources.
• Bytecode Verifier- checks the code fragments for illegal code that can violate access right
to objects.
• Security Manager- determines what resources a class can access such as reading and
writing to the local disk.
Robust
Robust simply means strong. Java uses strong memory management. There are lack of pointers
that avoids security problem. There is automatic garbage collection in java. There is exception
handling and type checking mechanism in java. All these points makes java robust.
Architecture-neutral & Portable
There is no implementation dependent features e.g. size of primitive types is set. We may carry
the java bytecode to any platform.
High-performance
Java is faster than traditional interpretation since byte code is "close" to native code still
somewhat slower than a compiled language (e.g., C++)
Distributed
We can create distributed applications in java. RMI and EJB are used for creating distributed
applications. We may access files by calling the methods from any machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that
deal with many tasks at once by defining multiple threads. The main advantage of multi-
threading is that it shares the same memory. Threads are important for multi-media, Web
applications etc.
G. Components of JAVA:
1. JDK (Java Development Kit)
JDK is an acronym for Java Development Kit. It physically exists. It contains JRE +
development tools. It is used for developing, debugging, testing, and executing java
programs. It exist in "C:\Program Files\Java\" folder. It contains utility tools to develop and
test java applications.
javac (java A java program can be typed using any text editor and save file with
compiler) .java extension. Then Java Compiler, reads Java class and interface
definitions and compiles them into bytecode i.e. it converts .java file
into .class file.
java (java The java command starts a Java application. It does this by starting
interpreter) the Java Runtime Environment (JRE), loading the specified .class, and
calling that class's main() method. It interprets .class file into
machine specific code with the help of JVM and execute it.
javap (java Java disassembler is used to convert bytecode into source code.
disassembler)
javah (java The javah command generates C header and source files that are
header) needed to implement native methods. The generated header and
source files are used by C programs to reference an object's instance
variables from native code.
jdb (java The Java Debugger (JDB) is a simple command-line debugger for Java
debugger) classes. The jdb command provides inspection and debugging of a local
or remote Java Virtual Machine (JVM).
jar (java The jar command is a general-purpose archiving and compression tool,
archive) based on ZIP and the ZLIB compression format. However, the jar
command was designed mainly to package Java applets or applications
into a single archive.
JRE is an acronym for Java Runtime Environment. It is used to provide runtime environment.
It is the implementation of JVM. It physically exists. It contains set of libraries + other files
that JVM uses at runtime.
a) JVM:
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides
runtime environment in which java bytecode can be executed. JVMs are available for
many hardware and software platforms. JVM, JRE and JDK are platform dependent
because configuration of each OS differs. But, Java Application is platform independent.
b) Bytecode:
Bytecode is nothing but the intermediate representation of Java source code which is
produced by the Java compiler by compiling that source code. This byte code is an
machine independent code. It is not an completely a compiled code but it is an
intermediate code somewhere in the middle which is later interpreted and executed by
JVM. It is stored in .class file which is created after compiling the source code. Bytecode
files generally have a .class extension.
Let's see what is the meaning of class, public, static, void, main, String[],
System.out.println().
• class keyword is used to declare a class in java.
• public keyword is an access modifier which represents visibility, it means it is visible to
all.
• static is a keyword, if we declare any method as static, it is known as static method. The
core advantage of static method is that there is no need to create object to invoke the
static method. The main method is executed by the JVM, so it doesn't require to create
object to invoke the main method. So it saves memory.
• void is the return type of the method, it means it doesn't return any value.
• main represents startup of the program.
• String[] args is used for command line argument. We will learn it later.
• System.out.println() is used print statement on standard output device.
What happens at compile time? [ i.e. javac Simple.java]: At compile time, java file is
compiled by Java Compiler (It does not interact with OS) and converts the java code into
bytecode.
What happens at runtime? [ i.e. java Simple]: At runtime, following steps are
performed:
Multiple classes in single java source file: Yes, you can write multiple java classes in single
java source file.
The java command-line argument is an argument i.e. passed at the time of running the java
program. The arguments passed from the console (i.e. command prompt) can be received in the
java program and it can be used as an input. You can pass N (1,2,3....... and so on) numbers of
arguments from the command prompt. All the arguments passed at command line are
stored in " args[] " of main method in String format.
Example:
class CommandLineExample {
public static void main(String args[])
{
String s=args[0];
System.out.println("args"+s);
}
}
Example:
class CommandLineExampleTwo{
public static void main(String args[]){
int len;
len = args.length;
for (int i=0; i<len ; i++){
System.out.println( " args
[ " + i + " ] is " + args[i] );
}
}
}
1. Variable
Variable is a name of reserved area allocated in memory. Variables represent memory area
where the information is stored. A variable has a name, a value and a data type.
Initialization of variable:
2. Types of variable:
a. Local Variable
A variable that is declared inside the method is called local variable.
b. Instance Variable
A variable that is declared inside the class but outside the method is called instance variable .
It is not declared as static. Separate copy of instance variable is assigned to each object
hence each object have their own copies of instance variables.
c. Static variable / Class variable
A variable that is declared inside the class and as static is called static variable or class
variable. Static variables are shared by all objects of class hence these variables are common
variables for all objects.
3. Scope of Variable:
The scope of a variable defines the section of the code in which the variable is visible. As a rule,
variables that are defined within a block are not accessible outside that block. The lifetime of a
variable refers to how long the variable exists before it is destroyed. Destroying variables refers
to de-allocating the memory that was allotted to the variables when declaring it.
a. Local Level Scope
Local variables are created when the method, constructor or block is entered, and the
variable will be destroyed once it exits the method, constructor or block. Local variables are
visible only within the declared method, constructor or block.
Example:
class A{
int data=50; // instance variable
static int m=100; // static variable or class variable
void method(){
int n=90; // local variable
}//end of method
}//end of class
4. Data Types:
A data type or simply type is a classification identifying one of various types of data, such
as real, integer or boolean, that determines the possible values for that type, the operations that
can be done on values of that type, the meaning of the data, and the way values of that type
can be stored. The type of a variable determines how much space it occupies in storage and
how the bit pattern stored is interpreted.
The process of converting one data type to another is called casting. Assigning a value of
one type to a variable of another type is known as Type Casting. In Java, type casting is
classified into two types:
• Widening Casting(Implicit / Automatic)
A data type of lower size (occupying less memory) is assigned to a data type of higher
size. This is done implicitly by the JVM. The lower size is widened to higher size. This is
also named as automatic type conversion. Automatic Type casting take place when,
• the two types are compatible
• the target type is larger than the source type
Example :
int x = 10; // occupies 4 bytes
double y = x; // occupies 8 bytes
System.out.println(y); // prints 10.0
Example:
public class Test{
public static void main(String[] args) {
double d = 100.04;
long l = (long)d; //explicit type casting required
int i = (int)l; //explicit type casting required
System.out.println("Double value "+d);
System.out.println("Long value "+l);
System.out.println("Int value "+i);
}
}
2. Java Literals:
A literal is a source code representation of a fixed value. They are represented directly in the
code without any computation. Literals can be assigned to any primitive type variable. For
example: byte a = 68; char a = 'A'. String literals in Java are specified like they are in
most other languages by enclosing a sequence of characters between a pair of double
quotes. Examples of string literals are: "Hello World", "two \n lines".
L. Java Operators:
Java provides a rich set of operators environment. Java operators can be divided into following
categories:
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 denominator
% remainder of division
++ Increment operator increases integer value by one
-- Decrement operator decreases integer value by one
Relational operators
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
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
Assignment Operators
Conditional operator
This operator is used for object reference variables. The operator checks whether the
object is of particular type (class type or interface type)
Decision making structures have one or more conditions to be evaluated or tested by the
program, along with a statement or statements that are to be executed if the condition is
determined to be true, and optionally, other statements to be executed if the condition is
determined to be false.
Statement Description
if An if statement consists of a boolean expression followed by one or more
statements.
if...else An if statement can be followed by an optional else statement, which executes
when the boolean expression is false.
nested if You can use one if or else if statement inside another if or else if statement(s).
switch A switch statement allows a variable to be tested for equality against a list of
values.
1. IF
Syntax: if(Boolean_expression){
//Statements will execute if the Boolean expression is true
}
If the Boolean expression evaluates to true then the block of code inside the if statement will be
executed. If not the first set of code after the end of the if statement (after the closing curly
brace) will be executed.
Flow Diagram
Example:
public class Test {
public static void main(String args[]){
int x = 10;
if( x < 20 ){
System.out.print("This is if statement");
}
}
}
2. IF....ELSE
An if statement can be followed by an optional else statement, which executes when the
Boolean expression is false.
Syntax: if(Boolean_expression){
//Executes when the Boolean expression is true
}else{
//Executes when the Boolean expression is false
}
If the boolean expression evaluates to true, then the if block of code will be executed, otherwise
else block of code will be executed.
Flow Diagram
Example:
public class Test {
public static void main(String args[]){
int x = 30;
if( x < 20 ){
System.out.print("This is if statement");
}else{
System.out.print("This is else statement");
}
}
}
3. ELSE IF Ladder:
An if statement can be followed by an optional else if...else statement, which is very useful to
test various conditions using single if...else if statement. When using if , else if , else statements
there are few points to keep in mind.
• An if can have zero or one else's and it must come after any else if's.
• An if can have zero to many else if's and they must come before the else.
• Once an else if succeeds, none of the remaining else if's or else's will be tested.
Syntax: Example:
4. Nested IF
It is always legal to nest if-else statements which means you can use one if or else if statement
inside another if or else if statement.
Syntax:
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}
}
You can nest else if...else in the similar way as we have nested if statement.
5. SWITCH
A switch statement allows a variable to be tested for equality against a list of values. Each value
is called a case, and the variable being switched on is checked for each case.
Syntax: switch(expression){
case value :
//Statements
break; //optional
case value :
//Statements
break; //You can have any number of case statements.
default : //Optional
}
• When the variable being switched on is equal to a case, the statements following that case
will execute until a break statement is reached.
• When a break statement is reached, the switch terminates, and the flow of control jumps to
the next line following the switch statement.
• Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
• A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true.
No break is needed in the default case.
Example:
Compile and run above program using various command line arguments.
We have covered conditional operator ? : in previous chapter which can be used to replace
if...else statements. It has the following general form:
Exp1 ? Exp2 : Exp3;
Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
To determine the value of whole expression, initially exp1 is evaluated
• If the value of exp1 is true, then the value of Exp2 will be the value of the whole
expression.
• If the value of exp1 is false, then Exp3 is evaluated and its value becomes the value of
the entire expression.
N. Loop Statements
There may be a situation when you need to execute a block of code several number of times. In
general, statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on. A loop statement allows us to execute a statement or group
of statements multiple times.
1. WHILE
A while loop statement in java programming language repeatedly executes a target statement
as long as a given condition is true.
Syntax: while(Boolean_expression){
//Statements
}
Here, statement(s) may be a single statement or a block of statements. The condition may
be any expression, and true is any non zero value. When executing, if the boolean_expression
result is true, then the actions inside the loop will be executed. This will continue as long as the
expression result is true. When the condition becomes false, program control passes to the line
immediately following the loop. Here, key point of the while loop is that the loop might not ever
run. When the expression is tested and the result is false, the loop body will be skipped and the
first statement after the while loop will be executed.
Example:
2. DO WHILE
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time.
Syntax: do
{
//Statements
}while(Boolean_expression);
Notice that the Boolean expression appears at the end of the loop, so the statements in the loop
execute once before the Boolean is tested. If the Boolean expression is true, the control jumps
back up to do statement, and the statements in the loop execute again. This process repeats
until the Boolean expression is false.
Example:
3. FOR
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times. A for loop is useful when you know how many times a task is
to be repeated.
• The initialization step is executed first, and only once. This step allows you to declare and
initialize any loop control variables. and this step ends with a semi colon (;)
• Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If
it is false, the body of the loop will not be executed and control jumps to the next statement
past the for loop.
• After the body of the for loop gets executed, the control jumps back up to the update
statement. This statement allows you to update any loop control variables. This statement
can be left blank with a semicolon at the end.
• The Boolean expression is now evaluated again. If it is true, the loop executes and the
process repeats (body of loop, then update step, then Boolean expression). After the Boolean
expression is false, the for loop terminates.
Flow Diagram
Example:
Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed. Java supports the
following control statements.
1. BREAK
The break statement in Java programming language has the following two usages:
1. When the break statement is encountered inside a loop, the loop is immediately
terminated and program control resumes at the next statement following the loop.
2. It can be used to terminate a case in the switch statement.
Syntax: break;
Example:
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}
2. CONTINUE
The continue keyword can be used in any of the loop control structures. It causes the loop to
immediately jump to the next iteration of the loop.
• In a for loop, the continue keyword causes control to immediately jump to the update
statement.
• In a while loop or do/while loop, control immediately jumps to the Boolean expression.
Syntax: continue;
Flow Diagram
Example:
• Declaration: The newly declared block variable, which is of a type compatible with the
elements of the array you are accessing. The variable will be available within the for block
and its value would be the same as the current array element.
• Expression: This evaluates to the array you need to loop through. The expression can be an
array variable or method call that returns an array.
Output: 10,20,30,40,50,
The java.lang.Math class contains methods for performing basic numeric operations
such as the elementary exponential, logarithm, square root, and trigonometric
functions. It contains various static methods to perform numeric operations. Following
are some important methods of Math class.
Example
public class MathDemo {
Example:
class MathFunctions
{
public static void main(String[] args)
{
int i1,i2;
double d1;
double a1,b1;
double e1;
float f1;
float f2;
i1=35;
i2=58;
int minimum=Math.min(i1,i2);
int maximum=Math.max(i1,i2);
d1=64.00;
double squareroot=Math.sqrt(d1);
a1=2;
b1=4;
double power=Math.pow(a1,b1);
e1=175;
double exponential=Math.exp(e1);
f1=75.20f;
int roundval=Math.round(f1);
f2=-50.26f;
float absval=Math.abs(f2);
System.out.println("min() = "+minimum);
System.out.println("max() = "+maximum);
System.out.println("sqrt() = "+squareroot);
System.out.println("pow() = "+power);
System.out.println("exp() = "+exponential);
System.out.println("round() = "+roundval);
System.out.println("abs() = "+absval);
}
}
Unit-II
Classes & Objects
A. Class Fundamental
1. Class in Java
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. A class is declared using class keyword. A class contain both data and code that operate
on that data. A class is a group of objects that has common properties. A class in java can
contain: data member, method, constructor, block, class and interface.
B. Object Fundamental
1. Object in Java
An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table,
car etc. An object has three characteristics:
• state: represents data (value) of an object.
• behavior: represents the behavior (functionality) of an object such as deposit, withdraw
etc.
• identity: Object identity is typically implemented via a unique ID.
2. Creating an Object:
As mentioned previously, a class provides the blueprints for objects. So basically an object is
created from a class. In Java, the new keyword is used to create new objects. There are three
steps when creating an object from a class:
• Declaration: A variable declaration with a variable name with an object type.
• Instantiation: The 'new' keyword is used to create the object.
• Initialization: The 'new' keyword is followed by a call to a constructor. This call
initializes the new object.
class Student.
{
String name;
int rollno;
int age;
}
4. Object Example:
/* Now call a variable as follows */ /* Now you can call a class method as
follows */
ObjectReference.variableName; ObjectReference.MethodName();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
8. Array of Objects
An array of objects is created just like an array of primitive type data items in the following
way.
The Student objects have to be instantiated using the constructor of the Student class and
their references should be assigned to the array elements in the following way.
The above for loop creates seven Student objects and assigns their reference to the array
elements.
}
}
}
C. Constructors
A constructor is a special method that is used to initialize an object. Every class has a
constructor, if we don't explicitly declare a constructor for any java class the compiler builds a
default constructor for that class. A constructor does not have any return type. A constructor has
same name as the class in which it resides. Constructor in Java cannot be abstract, static, final
or synchronized. These modifiers are not allowed for constructor. Java constructor is invoked at
the time of object creation. It constructs the values i.e. provides data for the object that is why it
is known as constructor.
1. Default Constructor
A constructor that have no parameter is known as default constructor.
2. Parameterized Constructor
3. 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. Constructor overloading is done to construct object in different ways.
There are many differences between constructors and methods. They are given below.
4. this keyword
this.width = w;
this.height = h;
this.depth = d;
}
}
class Student10{
int id;
String name;
Student10(int id,String name){
id = id;
name = name;
}
void display(){
System.out.println(id+" "+name);
}
class Student11{
int id;
String name;
Student11(int id,String name){
this.id = id;
this.name = name;
}
void display(){
System.out.println(id+" "+name);
}
class Car{
private String name;
public Car(){
this("BMW"); //oveloaded constructor is called.
}
public Car(String n){
this.name=n; //member is initialized using this.
}
}
D. Garbage Collection
In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming the
runtime unused memory automatically. In other words, it is a way to destroy the unused objects.
• It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
• It is automatically done by the garbage collector(a part of JVM) so we don't need to make
extra efforts.
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. It's the
last chance for any object to perform cleanup utility. The finalize() method is invoked each time
before the object is garbage collected. This method can be used to perform cleanup processing.
This method is defined in Object class.
4. 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. Example: System.gc();
E. Method Overloading
1. Java - Methods
A Java method is a collection of statements that are grouped together to perform an operation.
When you call the System.out.println() method, for example, the system actually executes
several statements in order to display a message on the console.
NOTE : In Java, when you pass a primitive type to a method it is passed by value whereas when
you pass an object of any type to a method it is passed as reference.
If a class have multiple methods by same name but different parameters, it is known as Method
Overloading. If we have to perform only one operation, having same name of the methods
increases the readability of the program.
class Calculate{
class Area{
void find(int l, int b){
System.out.println("Area is"+(l*b)) ;
}
void find(int l, int b,int h){
System.out.println("Area is"+(l*b*h));
}
public static void main (String[] args){
Area ar = new Area();
ar.find(8,5); //find(int l, int b) is method is called.
ar.find(4,6,2); //find(int l, int b,int h) is called.
}
}
F. Nested Classes
A class within another class is known as Nested class. The scope of the nested is bounded by the
scope of its enclosing class.
A static nested class is the one that has static modifier applied. Because it is static it cannot
refer to non-static members of its enclosing class directly.
Non-static Nested class is most important type of nested class. It is also known as Inner class.
It has access to all variables and methods of Outer class and may refer to them directly. But the
reverse is not true, that is, Outer class cannot directly access members of Inner class. One
more important thing to notice about an Inner class is that it can be created only within the
scope of Outer class. Java compiler generates an error if any code outside Outer class attempts
to instantiate Inner class.
class Outer{
public void display(){
Inner in=new Inner();
in.show();
}
class Inner{
class Outer{
int count;
for(int i=0;i<5;i++){
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();
Output :
Outer.Inner in= ot.new Inner();
Inside inner 1
in.show();
}
}
iv. Anonymous class: A class without any name is called Anonymous class.
interface Animal{
void type();
}
an.type();
} Output :
} Annonymous animal
G. Static Members
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.
Suppose there are 500 students in my college, now all instance data members will get memory
each time when object is created. All student have its unique rollno and name so instance data
member is good. Here, college refers to the common property of all objects. If we make it static,
this field will get memory only once. Note: Java static property is shared to all objects.
Example:
class Student8{
int rollno;
String name;
static String college ="ITS";
Student8(int r,String n){
rollno = r;
name = n;
}
class Counter{
class Counter2{
static int count=0; //will get memory only once and retain its value
Counter2(){
count++;
System.out.println(count);
}
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.
When you try to access a non-static variable from a static context like main method, java
compiler throws a message like "a non-static variable cannot be referenced from a static
context". This is because non-static variables are related with instance of class(object) and they
get created when instance of a class is created by using new operator. So if you try to access a
non-static variable without any instance compiler will complain because those variables are not
yet created and they don't have any existence until an instance is created and associated with it.
H. Inheritance Basics
Inheritance can be defined as the process where one class acquires the properties (methods and
fields) of another. With the use of inheritance the information is made manageable in a
hierarchical order. The class which inherits the properties of other is known as Subclass
(derived class, child class) and the class whose properties are inherited is known as Super Class
(base class, parent class). Inheritance in java is a mechanism in which one object acquires all
the properties and behaviors of parent object. Inheritance represents the IS-A relationship,
also known as parent-child relationship. extends and implements keywords are used to
describe inheritance in Java.
Example:
class Vehicle{
......
}
Output :
Child method
Parent method
3. Example: class Vehicle{ String vehicleType; }
modelType = "sports";
System.out.println(modelType+" "+vehicleType);
}
public static void main(String[] args){
Car car =new Car(); Output :
car.showDetail(); sports Car
}
}
4. Types of Inheritance
NOTE :
Multiple inheritance is
not supported in java
through class.
Example: class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
//suppose if it were
class C extends A,B{
public static void main(String args[]){ Compile Time Error
C obj=new C();
obj.msg();
//Now which msg() method would be invoked?
}
}
I. Super Keyword
The super keyword is similar to this keyword following are the scenarios where the super
keyword is used.
• It is used to differentiate the members of super class from the members of subclass, if
they have same names.
• It is used to invoke the super class constructor from subclass.
If a class is inheriting the properties of another class. And if the members of the superclass have
the names same as the sub class, to differentiate these variables we use super keyword as
shown below.
super.variable; super.method();
If a class is inheriting the properties of another class, the subclass automatically acquires the
default constructor of the super class. But if you want to call a parameterized constructor of the
super class, you need to use the super keyword as shown below. super(values);
1. Example of Child class referring Parent class property using super keyword
class Parent{
String name;
}
2. Example of Child class referring 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); Output :
} Parent
public static void main(String[] args){ Child
Child cobj = new Child();
cobj.details();
}
}
3. 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;
public Child(String n1, String n2){
super(n1); //passing argument to parent class constructor
this.name = n2;
}
public void details(){
System.out.println(super.name+" and "+name); Output :
} Parent and Child
public static void main(String[] args){
Child cobj = new Child("Parent","Child");
cobj.details();
}
}
In context to above example where Class B extends class A. A a=new B(); is legal syntax
because of IS-A relationship is there between class A and Class B.
5. Can you use both this() and super() in a Constructor?
NO, because both super() and this() must be first statement inside a constructor. Hence we
cannot use them together.
J. Method Overriding
If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in java. In other words, If subclass provides the specific implementation of
the method that has been provided by one of its parent class, it is known as 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.
1. Example: class Animal{
public void eat(){
System.out.println("Generic Animal eating");
}
}
class Dog extends Animal{
public void eat(){ //eat() method overriden by Dog class.
System.out.println("Dog eat meat");
}
}
NOTE : Static methods cannot be overridden because, a static method is bounded with class
where as instance method is bounded with object.
class Bank{
int getRateOfInterest(){return 0;}
}
a. Up-casting
When Parent class reference variable refers to Child class object, it is known as Up-casting
b. Example:
class Game{
public void type(){
System.out.println("Indoor & outdoor");
}
}
Class Cricket extends Game{ Notice the last output. This is
public void type() {
because of gm = ck; Now
System.out.println("outdoor game");
} gm.type() will call Cricket
version of type method.
public static void main(String[] args){ Because here gm refers to
Game gm = new Game(); cricket object.
Cricket ck = new Cricket();
gm.type(); Output :
ck.type(); Indoor & outdoor
gm=ck; //gm refers to Cricket object Outdoor game
gm.type(); //calls Cricket's version of type Outdoor game
}
}
Static binding in Java occurs during compile time while dynamic binding occurs during runtime.
Static binding uses type(Class) information for binding while dynamic binding uses instance of
class(Object) to resolve calling of method at run-time. Overloaded methods are bonded using
static binding while overridden methods are bonded using dynamic binding at runtime.
L. Final Keyword
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, or class. The final keyword can be applied with
the variables, a final variable that have no value it is called blank final variable or uninitialized
final variable. It can be initialized in the constructor only. The blank final variable can be static
also which will be initialized in the static block only. We will have detailed learning of these. Let's
first learn the basics of final keyword.
1. final Variables:
If you make any variable as final, you cannot change the value of final variable(It will be
constant). A final variable can be explicitly initialized only once. A reference variable declared
final can never be reassigned to refer to an different object. With variables, the final modifier
often is used with static to make the constant a class variable.
2. final Methods:
A final method cannot be overridden by any subclasses. As mentioned previously the final
modifier prevents a method from being modified in a subclass. The main intention of making a
method final would be that the content of the method should not be changed by any outsider. If
you make any method as final, you cannot override it.
void run(){
System.out.println("running safely with 100kmph");
}
The main purpose of using a class being declared as final is to prevent the class from being
subclassed. If a class is marked as final then no class can inherit any feature from the final class.
If you make any class as final, you cannot extend it.
1. Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to
the user. Another way, it shows only important things to the user and hides the internal details.
2. Abstract class
A class that is declared as abstract is known as abstract class. It needs to be extended and its
method implemented. It cannot be instantiated.
Example: abstract class A{}
3. Abstract method
A method that is declared as abstract and does not have implementation is known as abstract
method. Example: abstract void printStatus(); //no body and abstract
4. Example:
abstract class Bike{
In this example, Shape is the abstract class, its implementation is provided by the Rectangle and
Circle classes. Mostly, we don't know about the implementation class (i.e. hidden to the end
user) and object of the implementation class is provided by the factory method. A factory
method is the method that returns the instance of the class.
Abstract classes can also have normal methods with definitions, along with abstract methods.
abstract class A{
abstract void callme();
public void normal(){
System.out.println("this is concrete method");
}
}
class B extends A{
void callme() {
System.out.println("this is callme.");
}
7. Points to Remember
1. Abstract classes are not Interfaces. They are different, we will study this when we will
study Interfaces.
2. An abstract class must have an abstract method.
3. Abstract classes can have Constructors, Member variables and Normal methods.
4. Abstract classes are never instantiated.
5. When you extend Abstract class with abstract method, you must define the abstract
method in the child class, or make the child class abstract.
Rule: If there is any abstract method in a class, that class must be abstract.
A partial implemented class is called an abstract class , Where as fully implemented class is
commonly known as concrete or normal class.
Abstract class:
• It is must to declare a class with an abstract access modifier .
• May or may not contain abstract methods.
• It is not possible to instantiate a abstract class .
• Variables are not final by default. We can able to reassign values.
• The abstract methods should implement in the derived classes. If not , the derived class
also become an abstract.
• Interface implementation is possible.
Concrete class:
• Should not declare a concrete class with an abstract access modifier.
• Should not contain abstract methods.
• Instantiation is possible for a concrete class.
• Variables are not final by default.
• There is no abstract methods in any level to implement.
• Interface implementation is possible.
N. Visibility Controls
Java provides a number of access modifiers to set access levels for classes, variables, methods
and constructors. The four access levels are:
There are two types of modifiers in java: access modifiers and non-access modifiers. The
access modifiers in java specifies accessibility (scope) of a data member, method, constructor or
class. There are 4 types of java access modifiers:
There are many non-access modifiers such as static, abstract, synchronized, native, volatile,
transient etc. Here, we will learn access modifiers.
1. Private
Example: class A{
private int data=40;
private void msg(){
System.out.println("Hello java");
}
}
If you make any class constructor private, you cannot create the instance of that class from
outside the class.
Note: A class cannot be private or protected except nested class.
2. Default
If you don't use any modifier, it is treated as default. The default modifier is accessible only
within package.
Example: package pack;
class A{
void msg(){
System.out.println("Hello");
}
}
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A(); //Compile Time Error
obj.msg(); //Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package
3. Protected
The protected access modifier is accessible within package and outside the package but
through inheritance only. The protected access modifier can be applied on the data member,
method and constructor. It can't be applied on the class.
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
4. Public
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
O. Arrays
Normally, array is a collection of similar type of elements that have contiguous memory location.
Java array is an object the contains elements of similar data type. It is a data structure where
we store similar elements. We can store only fixed set of elements in a java array. Array in java
is index based, first element of the array is stored at 0 index.
Types of Array in java: Single Dimensional Array, Two Dimensional Array, Multidimensional
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};
In such case, data is stored in row and column based index (also known as matrix form).
1. arr[0][0]=1;
2. arr[0][1]=2;
3. arr[0][2]=3;
4. arr[1][0]=4;
5. arr[1][1]=5;
6. arr[1][2]=6;
7. arr[2][0]=7;
8. arr[2][1]=8;
9. arr[2][2]=9;
P. Strings
Java String provides a lot of concepts that can be performed on a string such as compare,
concat, equals, split, length, replace, compareTo, intern, substring etc. In java, string is basically
an object that represents sequence of char values. An array of characters works same as java
string.
For example:
1. char[] ch={'n','i','k','i','t','a','e','d','u','c',’a’,’t’,’i’,’o’,’n’};
1. String s=new String(ch); is same as: String s="nikitaeducation";
The java String is immutable i.e. it cannot be changed but a new instance is created. For
mutable class, you can use StringBuffer and StringBuilder class.
1) By String Literal:
2) By new keyword:
System.out.println(s1);
Output:
System.out.println(s2);
System.out.println(s3); java
strings
}
example
}
1. 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. StringBuffer defines 3 constructors.
They are,
1. StringBuffer(): creates an empty string buffer with the initial capacity of 16.
2. StringBuffer(String str): creates a string buffer with the specified string.
3. StringBuffer(int capacity): creates an empty string buffer with the specified capacity
as length.
2. public synchronized StringBuffer insert(int offset, String s): is used to insert the
specified string with this string at the specified position. The insert() method is overloaded
like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int,
double) etc.
8. public char charAt(int index): is used to return the character at the specified position.
9. public int length(): is used to return the length of the string i.e. total number of
characters.
10. public String substring(int beginIndex): is used to return the substring from the
specified beginIndex.
11. public String substring(int beginIndex, int endIndex): is used to return the
substring from the specified beginIndex and endIndex.
Q. Vector class
Vector is a class and it implements a dynamic array. It is similar to ArrayList, but with two
differences:
• Vector is synchronized.
• Vector contains many legacy methods that are not part of the collections framework.
Vector proves to be very useful if you don't know the size of the array in advance or you just
need one that can change sizes over the lifetime of a program. Constructors provided by the
vector class.
Method Description
addElement() add element to the Vector
elementAt() return the element at specified index
elements return an enumeration of element in vector
firstElement() return first element in the Vector
lastElement() return last element in the Vector
removeAllElement() remove all element of the Vector
Example
import java.util.*;
public class VectorDemo {
public static void main(String args[]) {
Vector v = new Vector(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " + v.capacity());
v.addElement(new Integer(1));
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));
System.out.println("Capacity after four additions: " + v.capacity());
v.addElement(new Double(5.45));
System.out.println("Current capacity: " +v.capacity());
v.addElement(new Double(6.08));
v.addElement(new Integer(7));
System.out.println("Current capacity: " +v.capacity());
v.addElement(new Float(9.4));
v.addElement(new Integer(10));
System.out.println("Current capacity: " + v.capacity());
v.addElement(new Integer(11));
v.addElement(new Integer(12));
System.out.println("First element: " + (Integer)v.firstElement());
System.out.println("Last element: " +(Integer)v.lastElement());
if(v.contains(new Integer(3)))
System.out.println("Vector contains 3.");
Enumeration vEnum = v.elements();
System.out.println("\nElements in vector:");
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println();
}
}
ArrayList Vector
1) ArrayList is not synchronized. Vector is synchronized.
2) ArrayList increments 50% of Vector increments 100% means doubles the array size
current array size if number of if total number of element exceeds than its capacity.
element exceeds from its capacity.
3) ArrayList is not a legacy class, it Vector is a legacy class.
is introduced in JDK 1.2.
4) ArrayList is fast because it is Vector is slow because it is synchronized i.e. in
non-synchronized. multithreading environment, it will hold the other threads
in runnable or non-runnable state until current thread
releases the lock of object.
5) ArrayList uses Iterator interface Vector uses Enumeration interface to traverse the
to traverse the elements. elements. But it can use Iterator also.
R. Wrapper Classes
Wrapper class in java provides the mechanism to convert primitive into object and object into
primitive. Since J2SE 5.0, autoboxing and unboxing feature converts primitive into object and
object into primitive automatically. The automatic conversion of primitive into object is known
and autoboxing and vice-versa unboxing. One of the eight classes of java.lang package are
known as wrapper class in java. The list of eight wrapper classes are given below:
Output: 3 3 3
Unit-III
Packages & Interfaces
A. Packages
a) Package Definition:
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
System Packages:
Package is a way to organize files in java, it is used when a project consists of multiple modules.
It also helps resolve naming conflicts. Package's access level also allows you to protect data from
being used by the non-authorized classes.
b) Creating 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.
The above statement create a package called mypack. Java uses file system directory to store
package.
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
class test{
public static void main(String[] args){
Book bk = new Book("java","Herbert");
bk.show();
}
}
How to compile java package: There are two ways used to compile java packages.
1. By Creating Directory:
• create a directory under your current working development 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.
2. By Using -d attribute
If you are not using any IDE, you need to follow the syntax given below:
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).
How to run java package program: You need to use fully qualified name e.g. mypack.Simple
etc to run the class.
We can add a class to an existing package by using the package name at the top of the program
as shown above and saving the .java file under the package directory. We need a new java file
if we want to define a public class, otherwise we can add the new class to an existing java file
and recompile it. Similar to classes, we can also define interfaces as a part of a package and
import and implement it as and when required. Moreover, we can extend a class inside a
package to create subclasses.
d) Accessing Package:
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*:
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages. The import keyword is used to make the classes and interface of another package
accessible to the current package.
//save by A.java
package pack;
public class A{
public void msg(){
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
} Output: Hello
}
2) Using packagename.classname:
If you import package.classname then only declared class of this package will be accessible.
//save by A.java
package pack;
public class A{
public void msg(){
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
Output: Hello
obj.msg();
}
}
If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface. It is generally used when two packages have same class name
e.g. java.util and java.sql packages contain Date class.
//save by A.java
package pack;
public class A{
public void msg(){
System.out.println("Hello");
}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A(); //using fully qualified name
obj.msg();
} Output: Hello
}
Note: If you import a package, subpackages will not be imported. If you import a
package, all the classes and interface of that package will be imported excluding the classes and
interfaces of the subpackages. Hence, you need to import the subpackage as well.
Note: Sequence of the program must be package then import then class.
e) Subpackage:
Package inside the package is called the subpackage. It should be created to categorize the
package further. Let's take an example, Sun Microsystem has defined a package named java
that contains many classes like System, String, Reader, Writer, Socket etc. These classes
represent a particular group e.g. Reader and Writer classes are for Input/Output operation,
Socket and ServerSocket classes are for networking etc and so on. So, Sun has subcategorized
the java package into subpackages such as lang, net, io etc. and put the Input/Output related
classes in io package, Server and ServerSocket classes in net packages and so on. The standard
of defining package is domain.company.package e.g. com.javatpoint.bean or org.sssit.dao.
Example of Subpackage
package com.javatpoint.core;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
} To Compile: javac -d . Simple.java
To Run: java com.javatpoint.core.Simple
Output: Hello subpackage
e) System Packages:
All the classes and interfaces that come with the installation of JDK are put together are known
as Java API (Application Programming Interface). All the Java API packages are prefixed
with java or javax. Following table gives some important packages, a few prominent classes and
their functionality.
First statement imports Vector class from util package which is contained inside java package.
Second statement imports all the classes from util package. Packages have an advantage over
header files of C-lang. A package allows importing a single class also instead of importing all. C-
lang does not have this ease of getting one function from a header file.
Note: While importing a single class, asterisk (*) should not be used.
f) Naming Conventions:
Like identifiers have conventions, the packages come with their own naming conventions. Like
keywords and protocols, packages are also of lowercase letters. In a single project, a number of
programmers may be involved assigned with different modules and tasks. To avoid namespace
problems in storing their work, naming conventions are followed. While creating packages, they
may follow company name, project name or personal name etc. to precede their package.
Following are a few examples.
This package naming convention never clashes with the others work in a big project involving
many programmers. The same convention is also followed in working on a domain also.
g) Import keyword:
import keyword is used to import built-in and user-defined packages into your java source file.
So that your class can refer to a class that is in another package by directly using its name.
There are 3 different ways to refer to class that is present in different package
But if you are not creating any package then import statement will be the first statement of your
java source file.
h) 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.
1. The first form of static import statement, import only a single static member of a class
Example: import static java.lang.Math.sqrt; //importing static method sqrt of Math class
2. The second form of static import statement, imports all the static member of a class
Example: import static java.lang.Math.*; //importing all static member of Math class
B. Interfaces
a) Interface Definition:
An interface is like a class containing methods and variables but the difference is that an
interface can define only abstract methods and final fields. Interfaces doesn't contain
constructors and they cannot be instantiated. There is no method definition inside the interface.
It is the responsibility of the class that implements the interface to define those methods. If the
class that implements an interface doesn't define all the methods of the interface, then that class
becomes an abstract class and cannot be instantiated. An interface in java is a blueprint of a
class. It has static constants and abstract methods only. The interface in java is a mechanism
to achieve fully abstraction. There can be only abstract methods in the java interface not
method body. It is used to achieve fully abstraction and multiple inheritance in Java. Java
Interface also represents IS-A relationship. It cannot be instantiated just like abstract class.
There are mainly three reasons to use interface. They are given below.
• It is used to achieve fully abstraction.
• By interface, we can support the functionality of multiple inheritance.
• It can be used to achieve loose coupling.
The java compiler adds public and abstract keywords before the interface method
and public, static and final keywords before data members automatically.
In other words, Interface fields are public, static and final by default, and methods are public
and abstract.
As shown in the figure given below, a class extends another class, an interface extends another
interface but a class implements an interface.
interface printable{
void print();
}
class A6 implements printable{
public void print(){
System.out.println("Hello");
}
public static void main(String args[]){
A6 obj = new A6();
Output: Hello
obj.print();
}
}
d) Features of Interfaces
Interfaces are derived from abstract classes with a special additional rule that interfaces should
contain only abstract methods. Let us see some more properties.
1. Interfaces support multiple inheritance which is not possible with concrete and abstract
classes.
2. "implements" keyword is used in place of "extends". "extends" comes with concrete and
abstract classes.
3. Interfaces must contain abstract methods only.
4. As in abstract classes, all the abstract methods of the interfaces should be overridden by
the subclass.
5. As with abstract classes, with interfaces also, objects cannot be created but reference
variables can be created.
6. Interface reference variable can be assigned with concrete subclass objects. Once
assigned, the interface reference variable works like an object. This feature applies to
abstract classes also.
7. As all methods must be abstract and public, these two keyword can be omitted in method
declaration. If omitted, JVM takes by default.
8. All interface variables must be public, static and final. If omitted, they are taken by
default.
9. All interface methods should be overridden with public only as overridden method cannot
have a weaker access specifier.
interface Moveable{
int AVG-SPEED = 40;
void move();
}
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known
as multiple inheritance.
Example:
interface Printable{
void print();
}
interface Showable{
void show();
}
h) Interface inheritance
Unit-IV
Multithreading & Exception Handling
Multi-Threading:
A. Introduction to Multithreading
1. It doesn't block the user because threads are independent and you can perform multiple
operations at same time.
2. You can perform many operations together so it saves time.
3. Threads are independent so it doesn't affect other threads if exception occur in a single
thread.
Multitasking
• Each process have its own address in memory i.e. each process allocates separate
memory area.
• Process is heavyweight & Cost of communication between the process is high.
• Switching from one process to another require some time for saving and loading registers,
memory maps, updating lists etc.
As shown in the above figure, thread is executed inside the process. There is context-switching
between the threads. There can be multiple processes inside the OS and one process can have
multiple threads.
A thread can be in one of the five states. According to sun, there is only 4 states in thread life
cycle in java new, runnable, non-runnable and terminated. There is no running state. But for
better understanding the threads, we are explaining it in the 5 states. The life cycle of the thread
in java is controlled by JVM. The java thread states are as follows:
1. New (born)
2. Runnable
3. Running
4. Non-Runnable (Blocked/waiting)
5. Terminated (dead)
1. New/born : A thread begins its life cycle in the new state. It remains in this state until the
start() method is called on it.
2. Runnable : After invocation of start() method on new thread, the thread becomes runnable.
3. Running : A method is in running thread if the thread scheduler has selected it.
4. Waiting/blocked : A thread is waiting for another thread to perform a task. In this stage
the thread is still alive.
• A Running Thread transit to one of the non runnable states, depending upon the
circumstances.
• A Thread remains non runnable until a special transition occurs.
• A Thread does not go directly to the running state from non runnable state. But transits
first to runnable state.
1. Sleeping: The Threas sleeps for specified amount of time.
2. Blocked for I/O: The Thread waits for a blocking operation to complete.
3. Blocked for join completion: The Thread waits for completion of another Thread.
4. Waiting for notification: The Thread waits for notification another Thread.
5. Blocked for lock acquisition: The Thread waits to acquire the lock of an object.
• JVM executes the Thread based on their priority and scheduling.
5. Terminated/dead : A thread enter the terminated state when it complete its task.
Even if you don't create any thread in your program, a thread called main thread is still created.
Although the main thread is automatically created, you can control it by obtaining a reference to
it by calling currentThread() method. Two important things to know about main thread are,
Example:
class MainThread{
public static void main(String[] args){
Thread t=Thread.currentThread(); Output :
t.setName("MainThread"); Name of thread is
System.out.println("Name of thread is "+t); Thread[MainThread,5,main]
}
}
D. Creating Threads
1. Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.
Thread class extends Object class and implements Runnable interface.
Constructors of Thread class
1. Thread ( )
2. Thread ( String str )
3. Thread ( Runnable r )
4. Thread ( Runnable r, String str)
5.
Commonly used methods of Thread class:
2. Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread. Runnable interface have only one method named run().
public void run(): is used to perform action for a thread.
3. Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs
following tasks:
• A new thread starts(with new callstack).
• The thread moves from New state to the Runnable state.
• When the thread gets a chance to execute, its target run() method will run.
Example:
Class MyThreadDemo{
public static void main( String args[] ){
MyThread mt = new MyThread();
mt.start();
} Output :
} concurrent thread started running..
If you are not extending the Thread class, your class object would not be treated as a thread
object. So you need to explicitly create Thread class object. We are passing the object of your
class that implements Runnable so that your class run() method may execute. The easiest way
to create a thread is to create a class that implements the runnable interface. After implementing
runnable interface , the class needs to implement the run() method, which is of form,
• run() method introduces a concurrent thread into your program. This thread will end
when run() returns.
• You must specify the code for your thread inside run() method.
• run() method can call other methods, can use other classes and declare variables just like
any other normal method.
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.
Thread scheduler in java is the part of the JVM that decides which thread should run. There is
no guarantee that which runnable thread will be chosen to run by the thread scheduler. Only one
thread at a time can run in a single process. The thread scheduler mainly uses preemptive or
time slicing scheduling to schedule the threads.
The sleep() method of Thread class is used to sleep a thread for the specified amount of time.
Syntax: The Thread class provides two methods for sleeping a thread:
• public static void sleep(long miliseconds)throws InterruptedException
• public static void sleep(long miliseconds, int nanos)throws InterruptedException
a) Naming Thread
The Thread class provides methods to change and get the name of a thread. By default, each
thread has a name i.e. thread-0, thread-1 and so on. By we can change the name of the thread
by using setName() method. The syntax of setName() and getName() methods are given below:
Example:
b. Current Thread
class TestMultitasking3{
public static void main(String args[]){
Simple1 t1=new Simple1();
Simple2 t2=new Simple2(); Output:
t1.start(); task one
t2.start(); task two
}
}
E. Synchronization
Synchronization in java is the capability to control the access of multiple threads to any shared
resource. Java Synchronization is better option where we want to allow only one thread to
access the shared resource.
Types of Synchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread communication.
1. Mutual Exclusive
2. Cooperation (Inter-thread communication in java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data. This
can be done by three ways in java:
1. by synchronized method
2. by synchronized block
3. by static synchronization
class Table{
void printTable(int n){ //method not synchronized
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){
System.out.println(e);
}
}
}
}
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.
Synchronized block can be used to perform synchronization on any specific resource of the
method. Suppose you have 50 lines of code in your method, but you want to synchronize only 5
lines, you can use synchronized block. If you put all the codes of the method in the synchronized
block, it will work same as the synchronized method. Points to remember for Synchronized
block:
• Synchronized block is used to lock an object for any shared resource.
• Scope of synchronized block is smaller than the method.
d. Static synchronization
If you make any static method as synchronized, the lock will be on the class not on object.
Problem without static synchronization: Suppose there are two objects of a shared
class(e.g. Table) named object1 and object2.In case of synchronized method and synchronized
block there cannot be interference between t1 and t2 or t3 and t4 because t1 and t2 both refers
to a common object that have a single lock. But there can be interference between t1 and t3 or
t2 and t4 because t1 acquires another lock and t3 acquires another lock. I want no interference
between t1 and t3 or t2 and t4.Static synchronization solves this problem. Example: In this
example we are applying synchronized keyword on the static method to perform static
synchronization.
F. Interrupting a Thread:
If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the
interrupt() method on the thread, breaks out the sleeping or waiting state throwing
InterruptedException. If the thread is not in the sleeping or waiting state, calling the interrupt()
method performs normal behavior and doesn't interrupt the thread but sets the interrupt flag to
true. Let's first see the methods provided by the Thread class for thread interruption.
public void interrupt() public static boolean interrupted() public boolean isInterrupted()
Example:
G. Stopping Thread:
This noncompliant code example shows a thread that fills a vector with pseudorandom numbers.
The thread is forcefully stopped after a given amount of time.
Example:
H. Thread Exceptions
• SecurityException - if the current thread cannot create a thread in the specified thread
group
I. Thread Priority
Each thread have a priority. Priorities are represented by a number between 1 and 10. In most
cases, thread scheduler schedules the threads according to their priority (known as preemptive
scheduling). But it is not guaranteed because it depends on JVM specification that which
scheduling it chooses. Three constants defined in Thread class:
public static int public static int public static int
MIN_PRIORITY NORM_PRIORITY MAX_PRIORITY
Example:
Daemon thread in java is a service provider thread that provides services to the user thread.
Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM terminates
this thread automatically. There are many java daemon threads running automatically e.g. gc,
finalizer etc. You can see all the detail by typing the jconsole in the command prompt. The
jconsole tool provides information about the loaded classes, memory usage, running threads etc.
Points to remember for Daemon Thread in Java
• It provides services to user threads for background supporting tasks. It has no role in life
than to serve user threads.
• Its life depends on user threads.
• It is a low priority thread.
The sole purpose of the daemon thread is that it provides services to user thread for background
supporting task. If there is no user thread, why should JVM keep running this thread. That is
why JVM terminates the daemon thread if there is no user thread.
if(Thread.currentThread().isDaemon()){
//checking for daemon thread
System.out.println("daemon thread work");
}
else{
System.out.println("user thread work");
}
}
public static void main(String[] args){
//creating thread
TestDaemonThread1 t1=new TestDaemonThread1();
TestDaemonThread1 t2=new TestDaemonThread1();
TestDaemonThread1 t3=new TestDaemonThread1();
t1.setDaemon(true); //now t1 is daemon thread
t1.start(); //starting threads
t2.start();
t3.start(); Output
} daemon thread work
user thread work
}
user thread work
Note: If you want to make a user thread as Daemon, it must not be started otherwise it will
throw IllegalThreadStateException.
Exception-Handling:
A. Introduction
The exception handling in java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained. In this page, we will learn about
java exception, its type and the difference between checked and unchecked exceptions. What is
exception?: Dictionary Meaning: Exception is an abnormal condition. In java, exception is an
event that disrupts the normal flow of the program. It is an object which is thrown at runtime.
What is exception handling?: Exception Handling is a mechanism to handle runtime errors
such as ClassNotFound, IO, SQL, Remote etc.
The core advantage of exception handling is to maintain the normal flow of the
application. Exception normally disrupts the normal flow of the application that is why we use
exception handling. Let's take a scenario:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Suppose there is 10 statements in your program and there occurs an exception at statement 5,
rest of the code will not be executed i.e. statement 6 to 10 will not run. If we perform exception
handling, rest of the statement will be executed. That is why we use exception handling in java.
B. Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is considered as
unchecked exception. The sun microsystem says there are three types of exceptions:
1) Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known as
checked exceptions e.g. IOException, SQLException etc. Checked exceptions are checked at
compile-time.
2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked
exceptions are not checked at compile-time rather they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
There are given some scenarios where unchecked exceptions can occur. They are as follows:
If we have null value in any variable, performing any operation by the variable occurs an
NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException
The wrong formatting of any value, may occur NumberFormatException. Suppose I have a
string variable that have characters, converting this variable into digit will occur
NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
1. try
2. catch
3. finally
4. throw
5. throws
E. Java try-catch
Java try block is used to enclose the code that might throw an exception. It must be used within
the method. Java try block must be followed by either catch or finally block.
Syntax: try{
//code that may throw exception
}catch(Exception_class_Name ref){
//exception catching code
}
Syntax: try{
//code that may throw exception
}finally{
//important code which must be execute
}
Java catch block is used to handle the Exception. It must be used after the try block only. You
can use multiple catch block with a single try.
As displayed in the above example, rest of the code is not executed (in such case, rest of the
code... statement is not printed). There can be 100 lines of code after exception. So all the code
after exception will not be executed.
The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM
provides a default exception handler that performs the following tasks:
But if exception is handled by the application programmer, normal flow of the application is
maintained i.e. rest of the code is executed.
If you have to perform different tasks at the occurrence of different Exceptions, use java multi
catch block.
Example:
Rule: At a time only one Exception is occurred and at a time only one catch block is
executed.
Rule: All catch blocks must be ordered from most specific to most general i.e. catch
for ArithmeticException must come before catch for Exception.
Example:
class TestMultipleCatchBlock1{
public static void main(String args[]){ Output:
try{ Compile-time error
int a[]=new int[5];
a[5]=30/0;
}
catch(Exception e){
System.out.println("common task completed");
}
catch(ArithmeticException e){
System.out.println("task1 is completed");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("task 2 completed");
}
System.out.println("rest of the code...");
}
}
The try block within a try block is known as nested try block in java. Why use nested try
block: Sometimes a situation may arise where a part of a block may cause one error and the
entire block itself may cause another error. In such cases, exception handlers have to be nested.
Syntax: try{
statement 1;
statement 2;
try{
statement 1;
statement 2;
}catch(Exception e){}
}catch(Exception e){}
Java finally block is a block that is used to execute important code such as closing connection,
stream etc.
Java finally block is always executed whether exception is handled or not. Java finally block must
be followed by try or catch block.
Note: If you don't handle exception, before terminating the program, JVM executes
finally block(if any).
• Finally block in java can be used to put "cleanup" code such as closing a file, closing
connection etc.
Let's see the different cases where java finally block can be used.
Case 1: Let's see the java finally example where exception doesn't occur.
class TestFinallyBlock{
public static void main(String args[]){
try{
Output:
int data=25/5; 5
System.out.println(data); finally block is always executed
}catch(NullPointerException e){ rest of the code...
System.out.println(e);
}finally{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Case 2: Let's see the java finally example where exception occurs and not handled.
class TestFinallyBlock1{
public static void main(String args[]){
try{ Output:
int data=25/0; finally block is always executed
System.out.println(data); Exception in thread main
}catch(NullPointerException e){ java.lang.ArithmeticException:/ by zero
System.out.println(e);
}finally{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Case 3: Let's see the java finally example where exception occurs and handled.
Rule: For each try block there can be zero or more catch blocks, but only one finally
block.
Note: The finally block will not be executed if program exits(either by calling
System.exit() or by causing a fatal error that causes the process to abort).
The Java throw keyword is used to explicitly (manually) throw an exception. We can throw either
checked or unchecked exception in java by throw keyword. The throw keyword is mainly used to
throw custom exception. We will see custom exceptions later.
Example:
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
Output:
public static void main(String args[]){
Exception in thread main
validate(13); java.lang.ArithmeticException:
System.out.println("rest of the code..."); not valid
}
}
The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to provide the
exception handling code so that normal flow can be maintained. Exception Handling is mainly
used to handle the checked exceptions. If there occurs any unchecked exception such as
NullPointerException, it is programmers fault that he is not performing check up before the code
being used.
Rule: If you are calling a method that declares an exception, you must either caught
or declare the exception.
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
public class Testthrows2{
public static void main(String args[]){
try{
M m=new M();
m.method(); Output:
}catch(Exception e){ exception handled
System.out.println("exception handled"); normal flow...
}
System.out.println("normal flow...");
}
}
In case you declare the exception, if exception does not occur, the code will be executed
fine.
In case you declare the exception if exception occures, an exception will be thrown at
runtime because throws does not handle the exception.
import java.io.*;
class M{
void method()throws IOException{
System.out.println("device operation performed");
}
}
class Testthrows3{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();
Output:
System.out.println("normal flow..."); device operation performed
} normal flow...
}
b. if exception occurs
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
class Testthrows4{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();
System.out.println("normal flow..."); Output:
Runtime Exception
}
}
1) Java throw keyword is used to explicitly Java throws keyword is used to declare an
throw an exception. exception.
4) Throw is used within the method. Throws is used with the method signature.
5) You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws IOException,
SQLException.
Final is used to apply Finally is used to place important Finalize is used to perform clean
restrictions on class, code, it will be executed whether up processing just before object
method and variable. Final exception is handled or not. is garbage collected.
class can't be inherited,
final method can't be
overridden and final
variable value can't be
changed.
If you are creating your own Exception that is known as custom exception or user-defined
exception. Java custom exceptions are used to customize the exception according to user need.
By the help of custom exception, you can have your own exception and message.
class TestCustomException1{
static void validate(int age)throws InvalidAgeException{
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
try{
validate(13);
}catch(Exception m){
System.out.println("Exception occured: "+m);
}
System.out.println("rest of the code...");
}
}
Output:
Exception occured:
InvalidAgeException:not valid
rest of the code...
Unit-V
Graphics & Internet Programming
A. Java Applet:
Applet is a special type of java program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side.
• 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.
Advantage of Applet
Drawback of Applet
Every applet is an extension of the java.applet.Applet class. The base Applet class provides
methods that a derived Applet class may call to obtain information and services from the browser
context. These include methods that do the following:
java.applet.Applet:
The java.applet.Applet class has 4 life cycle methods and java.awt.Component class
provides 1 life cycle methods for an applet. For creating any applet java.applet.Applet class
must be inherited.
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.
java.awt.Component class
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class
object that can be used for drawing oval, rectangle, arc etc.
Applet runs in the browser and its lifecycle method are called by JVM at its birth, its death and
when it is momentarily away. Every Applet can be said to be any of the following state
• The life cycle of an applet is begin on that time when the applet is first loaded into the
browser and called the init() method.
• The init() method is called only one time in the life cycle on an applet.
• The init() method is basically called to read the PARAM tag in the html file.
• The init () method retrieve the passed parameter through the PARAM tag of html file
using get Parameter() method .
• All the initialization such as initialization of variables and the objects like image, sound file
are loaded in the init () method .
• After the initialization of the init() method user can interact with the Applet
//Statements
2. Running State
• After initialization, this state will automatically occur by invoking the start method of
applet class which again calls the run method and which calls the paint method.
• The running state also occurs from idle state when the applet is reloaded.
• This method may be called multiples time when the Applet needs to be started or
restarted.
• For Example if the user wants to return to the Applet, in this situation the start Method()
of an Applet will be called by the web browser and the user will be back on the applet.
• In the start method user can interact within the applet.
//Statements
3. Idle State
• The idle state will make the execution of the applet to be halted temporarily.
• Applet moves to this state when the currently executed applet is minimized or when the
user switches over to another page.
• At this point the stop method is invoked.
• From the idle state the applet can move to the running state.
• The stop() method can be called multiple times in the life cycle of applet Or called at
least one time.
• For example the stop() method is called by the web browser on that time When the user
leaves one applet to go another applet
//Statements
4. Dead State
• When the applet programs terminate, the destroy function is invoked which makes an
applet to be in dead state.
• The destroy() method is called only one time in the life cycle of Applet like init() method.
//Statements
5. Display State
• The applet is said to be in display state when the paint method is called.
• This method can be used when we want to display output in the screen.
• This method can be called any number of times.
• paint() method is must in all applets when we want to draw something on the applet
window.
• paint() method takes Graphics object as argument
D. A Simple Applet
Output:
An Applet program is compiled in the same way as you have been compiling your console
programs. However there are two ways to run an applet.
For executing an Applet in an web browser, create short HTML file in the same directory. Inside
body tag of the file, include the following code. (applet tag loads the Applet class)
1. By html file.
2. By appletviewer tool (for testing purpose).
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.
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}
}
Note: class must be public because its object is created by Java Plugin software that resides on
the browser.
myapplet.html: <html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
To execute the applet by appletviewer tool, create an applet that contains applet tag in comment
and compile it. After that run it by: appletviewer First.java. Now Html file is not required but it is
for testing purpose only.
c:\>javac First.java
c:\>appletviewer First.java
Applet Application
Small Program Large Program
Used to run a program on client Browser Can be executed on standalone computer system
Applet is portable and can be executed by Need JDK, JRE, JVM installed on client machine.
any JAVA supported browser.
Applet applications are executed in a Application can access all the resources of the
Restricted Environment computer
Applets are created by extending the Applications are created by writing public static
java.applet.Applet void main(String[] s) method.
Applet application has 5 methods which will Application has a single start point which is main
be automatically invoked on occurrence of method
specific event
Example: public class MyClass
import java.awt.*; {
import java.applet.*; public static void main(String args[]) {
public class Myclass extends Applet }
{ }
public void init() { }
public void start() { }
public void stop() {}
public void destroy() {}
public void paint(Graphics g) {}
}
1. Execution of applets is easy in a Web browser and does not require any installation or
deployment procedure in real-time programming (where as servlets require).
2. Writing and displaying (just opening in a browser) graphics and animations is easier than
applications.
3. In GUI development, constructor, size of frame, window closing code etc. are not required
(but are required in applications).
G. Types of Applet
1. Local Applets
Local applets are applet types that are developed and stored in local system. The web page will
search the local system directories, find the local applet and execute it. Execution of local applet
does not require internet connection. Specifying a Local Applet:
In the above listing , the codebase attribute specifies a path name on your system for the local
applet, whereas the code attribute specifies the name of the byte-code file that contains the
applet's code. The path specified in the codebase attribute is relative to the folder containing the
HTML document that references the applet.
2. Remote Applets
Remote applets are applet types that are developed and stored in remote system. The web page
requires internet connection to locate and load the remote applet from remote computer.
Specifying a Remote Applet
The only difference between Local Applet and Remote Applet is the value of the codebase
attribute. In the first case, codebase specifies a local folder, and in the second case, it specifies
the URL at which the applet is located.
H. Parameter in Applet
We can get any information from the HTML file as a parameter. For this purpose, Applet class
provides a method named getParameter().
myapplet.html: <html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to GPN">
</applet>
</body>
</html>
Graphics Programming
A. Graphics Class:
The AWT supports a rich assortment of graphics methods. All graphics are drawn relative to a
window. This can be the main window of an applet, a child window of an applet, or a stand-
alone application window. The origin of each window is at the top-left corner and is 0,0.
Coordinates are specified in pixels. All output to a window takes place through a graphics
context. A graphics context is encapsulated by the Graphics class and is obtained in two
ways:
• It is passed to an applet when one of its various methods, such as paint() or update(),
is called.
• It is returned by the getGraphics() method of Component.
myapplet.html: <html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>
1. Color
Java supports color in a portable, device-independent fashion. The AWT color system allows you to
specify any color you want. It then finds the best match for that color, given the limits of the display
hardware currently executing your program or applet. Color is encapsulated by the Color class.
• Color brighter() - Creates a new Color that is a brighter version of this Color.
• Color darker() - Creates a new Color that is a darker version of this Color.
• Int getBlue() - Returns the blue component in the range 0-255 in the default sRGB space.
• Int getGreen() - Returns the green component in the range 0-255 in the default sRGB space.
• Int getRed() - Returns the red component in the range 0-255 in the default sRGB space.
• Int getRGB() - Returns the RGB value representing the color in the default sRGB ColorModel.
D.6. Example:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
g.setColor(c1);
g.drawLine(10, 10, 100, 10);
g.drawLine(10, 15, 100, 15);
g.setColor(c2);
g.drawLine(10, 20, 100, 20);
g.drawLine(10, 25, 100, 25);
g.setColor(c3);
g.drawLine(10, 30, 100, 30);
g.drawLine(10, 35, 100, 35);
g.setColor(Color.red);
g.drawOval(10, 50, 100, 100);
g.fillOval(120, 50, 100, 100);
g.setColor(Color.blue);
g.drawOval(10, 160, 100, 80);
g.drawRect(120, 160, 100, 80);
g.setColor(Color.cyan);
g.fillRect(10, 270, 100, 100);
g.drawRoundRect(190, 10, 60, 50, 15, 15);
}
}
Output:
cmd>javac ColorDemo.java
cmd>appletviewer ColorDemo.java
2. Font
The AWT supports multiple type fonts. The AWT provides flexibility by abstracting font-manipulation
operations and allowing for dynamic selection of fonts. Fonts have a family name, a logical font
name, and a face name. Fonts are encapsulated by the Font class
1. The family name is the general name of the font, such as Courier.
2. The logical name specifies a category of font, such as Monospaced.
3. The face name specifies a specific font, such as Courier Italic.
Font(String name, int style, int size) - Creates a new Font from the specified name, style and point
size.
import java.awt.*;
class AvailableFonts{
public static void main(String[] args){
GraphicsEnvironment ge=
GraphicsEnvironment.getLocalGraphicsEnvironment();
for(int i=0;i<list.length;i++)
{
System.out.println("Font : "+list[i]);
}
}
}
E.5. Example:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
3. FontMetrics
For most fonts, characters are not all the same dimension—most fonts are proportional. Also, the height
of each character, the length of descenders (the hanging parts of letters, such as y), And the amount of
space between horizontal lines vary from font to font. Further, the point size of a font can be
changed. Hence we need to obtain font information for managing text outputs. To fulfill above need
AWT provides us FontMetrics class. FontMetrics class encapsulates information about a font.
FontMetrics doesn’t provide visible constructor hence we need to obtain its object using following way.
• FontMetrics FM=getFontMetrics(Font F); OR
• FontMetrics FMS=g.getFontMetrics();
a. int getAscent( ) - Determines the font ascent of the Font described by this FontMetrics object.
b. int getDescent( ) - Determines the font descent of the Font described by this FontMetrics object.
c. int getHeight( ) - Gets the standard height of a line of text in this font.
d. int getLeading( ) - Determines the standard leading of the Font described by this FontMetrics
object.
e. int getMaxAscent( ) - Determines the maximum ascent of the Font described by this FontMetrics
object.
f. int getMaxDescent() - Determines the maximum descent of the Font described by this FontMetrics
object.
F.4. Example:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
Unit-VI
File I/O & Collection Framework
File I/O
Java I/O (Input and Output) is used to process the input and produce the output based on the
input. 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. We can perform file handling
in java by java IO API. 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.
• Stream
A stream is a sequence of data. In Java a stream is composed of bytes. It's called a stream
because it's like a stream of water that continues to flow. In java, 3 streams are created for
us automatically. All these streams are attached with console.
Let's see the code to print output and error message to the console.
1. System.out.println("simple message");
2. System.err.println("error message");
1. OutputStream
Java application uses an output stream to write data to a destination, it may be a file, an array,
peripheral device or socket.
2. InputStream
Java application uses an input stream to read data from a source, it may be a file, an array,
peripheral device or socket.
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.
Byte stream is defined by using two abstract class at the top of hierarchy, they are
InputStream and OutputStream. These two abstract classes have several concrete classes
that handle various devices such as disk files, network connection etc. Some important Byte
stream classes.
These classes define several key methods. Two most important are
Character stream is also defined by using two abstract class at the top of hierarchy, they are
Reader and Writer. These two abstract classes have several concrete classes that handle
unicode character. Some important Character stream classes.
We use the object of BufferedReader class to take inputs from the keyboard.
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.
Example:
class CharRead{
public static void main( String args[]){
BufferedReader br = new Bufferedreader(new InputStreamReader(System.in));
//Reading character
char c = (char)br.read();
}
}
To read string we have to use readLine() function with BufferedReader class's object.
1.1. OutputStream
OutputStream class is an abstract class. It is the superclass of all classes representing an output
stream of bytes. An output stream accepts output bytes and sends them to some sink.
Method Description
public void write(int)throws is used to write a byte to the current output stream.
IOException:
public void write(byte[])throws is used to write an array of byte to the current output
IOException: stream.
public void flush()throws IOException: flushes the current output stream.
public void close()throws IOException: is used to close the current output stream.
1.2. InputStream
InputStream class is an abstract class.It is the superclass of all classes representing an input
stream of bytes.
Method Description
public abstract int read()throws reads the next byte of data from the input stream.It
IOException: returns -1 at the end of file.
public int available()throws IOException: returns an estimate of the number of bytes that can
be read from the current input stream.
public void close()throws IOException: is used to close the current input stream.
In Java, FileInputStream and FileOutputStream classes are used to read and write data in file. In
another words, they are used for file handling in java.
2.1. FileOutputStream
Java FileOutputStream is an output stream for writing data to a file. If you have to write
primitive values then use FileOutputStream. Instead, for character-oriented data, prefer
FileWriter. But you can write byte-oriented as well as character-oriented data.
Example:
import java.io.*;
class Test{
public static void main(String args[]){
try{
FileOutputstream fout=new FileOutputStream("abc.txt");
String s="Sachin Tendulkar is my favourite player";
//converting string into byte array
byte b[]=s.getBytes();
fout.write(b);
fout.close();
System.out.println("success..."); Output:
}catch(Exception e){ success...
system.out.println(e);
}
}
}
2.2. FileInputStream
Java FileInputStream class obtains input bytes from a file. It is used for reading streams of raw
bytes such as image data. For reading streams of characters, consider using FileReader. It
should be used to read byte-oriented data for example to read image, audio, video etc.
2.3. Example of Reading the data of current java file and writing it into another file
import java.io.*;
class C{
public static void main(String args[])throws Exception{
FileInputStream fin=new FileInputStream("C.java");
3.1. DataOutputStream
The DataOutputStream stream let you write the primitives to an output source. Following is the
constructor to create a DataOutputStream: public DataOutputStream(OutputStream out);
Once you have DataOutputStream object in hand, then there is a list of helper methods, which
can be used to write the stream or to do other operations on the stream.
Example:
import java.io.*;
String k = dataIn.readUTF();
System.out.print(k+" "); Output:
THIS IS TEST 1 ,
}
THIS IS TEST 2 ,
} THIS IS TEST 3 ,
} THIS IS TEST 4 ,
THIS IS TEST 5 ,
3.2. DataInputStream
The DataInputStream is used in the context of DataOutputStream and can be used to read
primitives. Following is the constructor to create an InputStream: public
DataInputStream(InputStream in); Once you have DataInputStream object in hand, then
there is a list of helper methods, which can be used to read the stream or to do other operations
on the stream.
Example:
import java.io.*;
public class DataInput_Stream{
public static void main(String args[])throws IOException{
//writing string to a file encoded as modified UTF-8
DataOutputStream dataOut;
dataOut = new DataOutputStream(new FileOutputStream("E:\\file.txt"));
dataOut.writeUTF("hello");
//Reading data from the same file
DataInputStream dataIn;
dataIn = new DataInputStream(new FileInputStream("E:\\file.txt"));
while(dataIn.available()>0){
String k = dataIn.readUTF();
System.out.print(k+" "); Output:
} hello
}
}
4.1. BufferedOutputStream
Java BufferedOutputStream class uses an internal buffer to store data. It adds more efficiency
than to write data directly into a stream. So, it makes the performance fast.
4.2. BufferedInputStream
Java BufferedInputStream class is used to read information from stream. It internally uses buffer
mechanism to make the performance fast.
5. PrintStream
The PrintStream class provides methods to write data to another stream. The PrintStream class
automatically flushes the data so there is no need to call flush() method. Moreover, its methods
don't throw IOException.
pout.println("Hello Java");
pout.println("Welcome to Java");
pout.close();
fout.close();
}
}
1.1. Reader
Syntax: public abstract class Reader extends Object implements DataOutput, DataInput,
Closeable
abstract int read(char[] cbuf, int off, int len): This method reads characters into a portion
of an array.
int read(CharBuffer target): This method attempts to read characters into the specified
character buffer.
boolean ready(): This method tells whether this stream is ready to be read.
void reset(): This method resets the stream.
long skip(long n): This method skips characters.
1.2. Writer
Syntax: public abstract class Writer extends Object implements Appendable, Closeable,
Flushable
2.1. BufferedReader
The Java.io.BufferedReader class reads text from a character-input stream, buffering characters
so as to provide for the efficient reading of characters, arrays, and lines. Following are the
important points about BufferedReader:
• The buffer size may be specified, or the default size may be used.
Nikita Education ( NET ) [ 9689925884 / 7350009884 ] 135
Basics of Java Programming Introduction to Java
• Each read request made of a Reader causes a corresponding read request to be made of the
underlying character or byte stream.
Example:
import java.io.*;
class G5{
public static void main(String args[])throws Exception{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
System.out.println("Enter your name"); Output:
String name=br.readLine(); Enter your name
System.out.println("Welcome "+name); Nikita Education
}
} Welcome
Nikita Education
2.2. BufferedWriter
• The buffer size may be specified, or the default size may be used.
• A Writer sends its output immediately to the underlying character or byte stream.
Java FileWriter and FileReader classes are used to write and read data from text files. These are
character-oriented classes, used for file handling in java. Java has suggested not to use the
FileInputStream and FileOutputStream classes if you have to read and write the textual
information.
3.1. FileWriter
Constructor Description
FileWriter(String file) creates a new file. It gets file name in string.
FileWriter(File file) creates a new file. It gets file name in File object.
Method Description
public void write(String text) writes the string into FileWriter.
public void write(char c) writes the char into FileWriter.
public void write(char[] c) writes char array into FileWriter.
public void flush() flushes the data of FileWriter.
public void close() closes FileWriter.
3.2. FileReader
Java FileReader class is used to read data from the file. It returns data in byte format like
FileInputStream class.
Constructor Description
FileReader(String It gets filename in string. It opens the given file in read mode. If file
file) doesn't exist, it throws FileNotFoundException.
FileReader(File file) It gets filename in file instance. It opens the given file in read mode.
If file doesn't exist, it throws FileNotFoundException.
Method Description
1) public int read() returns a character in ASCII form. It returns -1 at the end of file.
2) public void closes FileReader.
close()
4.1. InputStreamReader
}
inputStreamReader.close();
4.2. OutputStreamWriter
5. PrintWriter
Field: protected Writer out -- This is the character-output stream of this PrintWriter.
protected Object lock -- This is the object used to synchronize operations on this
stream.
6. Scanner
There are various ways to read input from the keyboard, the java.util.Scanner class is one of
them. The Java Scanner class breaks the input into tokens using a delimiter that is whitespace
by default. It provides many methods to read and parse various primitive values. Java Scanner
class is widely used to parse text for string and primitive types using regular expression. Java
Scanner class extends Object class and implements Iterator and Closeable interfaces.
Method Description
public String next() it returns the next token from the scanner.
public String nextLine() it moves the scanner position to the next line and returns the
value as a string.
public byte nextByte() it scans the next token as a byte.
public short nextShort() it scans the next token as a short value.
public int nextInt() it scans the next token as an int value.
public long nextLong() it scans the next token as a long value.
public float nextFloat() it scans the next token as a float value.
public double it scans the next token as a double value.
nextDouble()
1. Marker interface
Marker Interface is a special interface in Java without any field and method. Marker interface is
used to inform compiler that the class implementing it has some special behavior or meaning.
Some example of Marker interface are,
All these interfaces does not have any method and field. They only add special behavior to the
classes implementing them. However marker interfaces have been deprecated since Java 5, they
were replaced by Annotations. Annotations are used in place of Marker Interface that play the
exact same role as marker interfaces did before.
2.1. writeObject() method of ObjectOutputStream class serializes an object and send it to the
output stream.
2.2. readObject() method of ObjectInputStream class references object out of stream and
deserialize it.
while serializing if you do not want any field to be part of object state then declare it either static
or transient based on your need and it will not be included during java serialization process.
3. Serializing an Object
import java.io.*;
class Studentinfo implements Serializable{
String name;
int rid;
static String contact; Output:
Studentinfo(string n, int r, string c){ Object of Studentinfo class is
this.name = n; serialized using writeObject()
this.rid = r; method and written to
contact = c; student.ser file
}
}
class Test{
public static void main(String[] args){
try{
Studentinfo si = new Studentinfo("Abhi", 104, "110044");
FileOutputStream fos = new FileOutputStream("student.ser");
Objectoutputstream oos = new ObjectOutputStream(fos);
oos.writeObject(si);
oos.close();
fos.close();
}catch (Exception e){
e. printStackTrace();
}
}
}
4. Deserialization of Object
import java.io * ;
class DeserializationTest{
public static void main(String[] args){
studentinfo si=null ;
try{
FileInputStream fis = new FileInputStream("student.ser");
ObjectOutputStream ois = new ObjectOutputStream(fis);
si = (studentinfo)ois.readObject();
}catch (Exception e){
e.printStackTrace(); Output :
} Abhi
System.out.println(si.name); 104
null
System.out. println(si.rid);
System.out.println(si.contact);
}
}
Contact field is null because, it was marked as static and as we have discussed earlier static
fields does not get serialized.
NOTE : Static members are never serialized because they are connected to class not object of
class.
Collection Framework
B. Introduction:
Before Collection Framework (or before JDK 1.2) was introduced, the standard methods for
grouping Java objects (or collections) were Arrays or Vectors or HashTables. All of these
collections had no common interface. Accessing elements of these Data Structures was a difficult
task as each had a different method (and syntax) for accessing its members. Hence java
introduced a collection framework.
The Collection framework represents a unified architecture for storing and manipulating a group
of objects. It has:
1. Interfaces and its classes
2. Algorithms
Iterators in Java
Iterators are used in Collection framework in Java to retrieve elements one by one. There are
three types of iterators:
1. Enumeration
2. Iterator
3. ListIterator
Enumeration :
Limitations of Enumeration:
▪ Enumeration is for legacy classes(Vector, Hashtable) only. Hence it is not a universal
iterator.
▪ Remove operations can’t be performed using Enumeration.
▪ Only forward direction iterating is possible.
Nikita Education ( NET ) [ 9689925884 / 7350009884 ] 147
Basics of Java Programming Introduction to Java
Iterator:
It is a universal iterator as we can apply it to any Collection object. By using Iterator, we can
perform both read and remove operations. It is improved version of Enumeration with additional
functionality of remove-ability of a element. Iterator must be used whenever we want to
enumerate elements in all Collection framework implemented interfaces like Set, List, Queue,
Deque and also in all implemented classes of Map interface. Iterator is the only cursor available
for entire collection framework.
Limitations of Iterator:
▪ Only forward direction iterating is possible.
▪ Replacement and addition of new element is not supported by Iterator.
ListIterator:
It is only applicable for List collection implemented classes like arraylist, linkedlist etc. It provides
bi-directional iteration. ListIterator must be used when we want to enumerate elements of List.
This cursor has more functionality(methods) than iterator.
Limitations of ListIterator:
It is the most powerful iterator but it is only applicable for List implemented classes, so it is not a
universal iterator.
1. ArrayList
1. ArrayList()
2. ArrayList(Collection c)
3. ArrayList(int capacity)
1. void clear()
2. void add(int index, Object element)
3. int indexOf(Object O)
4. int lastIndexOf(Object O)
5. Object clone()
6. Object[] toArray()
7. boolean addAll(Collection C)
8. boolean add(Object o)
9. boolean addAll(int index, Collection C)
Example:
import java.io.*;
import java.util.*;
class myarraylist
{
public static void main(String[] args)
throws IOException
{
// size of ArrayList
int n = 5;
// Printing elements
System.out.println(arrli);
2. LinkedList
In java LinkedList class provides the functionality of doubly linked list concept used in data
structure. LinkedList class implements the list interface. The LinkedList class also consists of
various constructors and methods like other java collections.
1. LinkedList()
2. LinkedList(Collection C)
1. int size()
2. void clear()
3. Object set(int index, Object element)
4. boolean contains(Object element)
5. boolean add(Object element)
6. void add(int index, Object element)
7. boolean addAll(Collection C)
8. boolean addAll(int index, Collection C)
9. void addFirst(Object element)
10. void addLast(Object element)
11. Object get(int index)
12. Object getFirst()
13. Object getLast()
14. int indexOf(Object element)
15. Object remove()
16. Object remove(int index)
17. boolean remove(Object O)
18. Object removeFirst()
19. Object removeLast()
Example:
import java.util.*;
if(status)
System.out.println("List contains the element 'E' ");
else
System.out.println("List doesn't contain the element 'E'");
Difference between List and Set: List can contain duplicate elements whereas Set contains
unique elements only.
1. HashSet
Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the
AbstractSet class and implements Set interface. The important points about Java HashSet class
are:
Constructors in HashSet:
1. HashSet()
2. HashSet( Collection C )
3. HashSet( int capacity )
Methods in HashSet:
1. boolean add(E e)
2. void clear()
3. boolean contains(Object o)
4. boolean remove(Object o)
5. Iterator iterator()
6. boolean isEmpty()
7. int size()
8. Object clone()
Example:
import java.util.*;
class HashSetTest
{
public static void main(String[]args)
{
HashSet<String> h = new HashSet<String>();
2. TreeSet
1. TreeSet()
2. TreeSet( Collection C )
3. TreeSet( Comparator comp )
4. TreeSet( SortedSet ss )
Example:
import java.util.*;
class TreeSetDemo
{
public static void main (String[] args)
{
TreeSet<String> ts1= new TreeSet<String>();
3. LinkedHashSet
Example
import java.util.*;
class LinkedHashSetDemo
{
public static void main(String args[])
{
LinkedHashSet< String> hs = new LinkedHashSet< String>();
hs.add("B");
Nikita Education ( NET ) [ 9689925884 / 7350009884 ] 153
Basics of Java Programming Introduction to Java
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);
}
}
4. PriorityQueue
Example:
import java.util.*;
class PriorityQueueDemo
{
public static void main(String args[])
{
PriorityQueue<String> queue=new PriorityQueue<String>();
queue.add("WE");
queue.add("LOVE");
queue.add("STUDY");
queue.add("TONIGHT");
System.out.println("At head of the queue:"+queue.element());
System.out.println("At head of the queue:"+queue.peek());
System.out.println("Iterating the queue elements:");
Iterator itr=queue.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
queue.remove();
queue.poll();
System.out.println("After removing two elements:");
Iterator itr2=queue.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
}
}
}
A map contains values on the basis of key i.e. key and value pair. Each key and value pair is
known as an entry. Map is useful if you have to search, update or delete elements on the basis
of key. The java.util.Map interface represents a mapping between a key and a value. The Map
interface is not a subtype of the Collection interface. Therefore it behaves a bit different from the
rest of the collection types. A Map stores data in key and value association. Both key and values
are objects. The key must be unique but the values can be duplicate.
1. HashMap
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));
2. TreeMap
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));
3. Hashtable
Example:
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());
}
}
}
Utility Classes:
The java.util package contains the collections framework, legacy collection classes, event model,
date and time facilities, internationalization, and miscellaneous utility classes.
1. Date
The java.util.Date class represents date and time in java. It provides constructors and methods
to deal with date and time in java. The java.util.Date class implements Serializable, Cloneable
and Comparable<Date> interface. It is inherited by java.sql.Date, java.sql.Time and
java.sql.Timestamp interfaces.
java.util.Date Constructors
2) Date(long milliseconds) Creates a date object for the given milliseconds since
January 1, 1970, 00:00:00 GMT.
java.util.Date Methods
Example:
import java.util.Date;
public class DateDemo {
import java.util.*;
import java.util.*;
boolean a = d3.after(d1);
System.out.println("Date d3 comes after " +
"date d2: " + a);
boolean b = d3.before(d2);
System.out.println("Date d3 comes before "+
"date d2: " + b);
int c = d1.compareTo(d2);
System.out.println(c);
import java.util.*;
import java.text.*;
import java.util.Date;
public class DateDemo {
System.out.printf(str);
}
}
import java.util.Date;
public class DateDemo {
import java.util.*;
import java.text.*;
2. Calendar
The java.util.calendar class is an abstract class that provides methods for converting between
a specific instant in time and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH,
HOUR, and for manipulating the calendar fields, such as getting the date of the next week.
• This class also provides additional fields and methods for implementing a concrete
calendar system outside the package.
• Calendar defines the range of values returned by certain calendar fields.
Constructors:
Methods:
Method Description
public void add(int field, int amount) Adds the specified (signed) amount of time to the given
calendar field.
public boolean after (Object when) The method Returns true if the time represented by this
Calendar is after the time represented by when Object.
public boolean before(Object when) The method Returns true if the time represented by this
Calendar is before the time represented by when Object.
public int get(int field) In get() method fields of the calendar are passed as the
parameter, and this method Returns the value of fields
passed as the parameter.
public static Set<String> Returns a set which contains string set of all available
getAvailableCalendarTypes() calendar type supported by Java Runtime Environment.
public String getCalendarType() Returns in string all available calendar type supported by
Java Runtime Environment.
public int getFirstDayOfWeek() Returns the first day of the week in integer form.
public static Calendar getInstance() This method is used with calendar object to get the
instance of calendar according to current time zone set
by java runtime environment
public int getMinimalDaysInFirstWeek() Returns required minimum days in integer form.
public final Date getTime() This method gets the time value of calendar object and
Returns date.
public int getWeekYear() This method gets the week year represented by current
Calendar.
public void set(int field, int value) Sets the specified calendar field by the specified value.
public void setWeekDate(int weekYear, int Sets the current date with specified integer value as the
weekOfYear, int dayOfWeek) parameter. These values are weekYear, weekOfYear and
dayOfWeek.
Example:
import java.util.Calendar;
public class CalendarExample1 {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
System.out.println("The current date is : " + calendar.getTime());
calendar.add(Calendar.DATE, -15);
System.out.println("15 days ago: " + calendar.getTime());
calendar.add(Calendar.MONTH, 4);
3. Random
Random class is used to generate pseudo random numbers in java. Instance of this class are
thread safe. The instance of this class are however cryptographically insecure. This class
provides various method call to generate different random data types such as float, double, int.
Constructors:
Methods:
Example:
import java.util.Random;
public class RandomNumberExample {
Best Of Luck
Nikita Education - 7350009884