Java Material
Java Material
Prepared by:
Dr.Y.NARASIMHA REDDY
ASSOCIATE PROFESSOR
DEPT.OF CSE
SJCET
UNIT I:
The History and Evolution of Java:
Java’s Lineage, The Creation of java, how java changed the internet, Java’s magic: The byte
code, Servlets: java on the server side, java Buzzwords, Evolution of java.
An Overview of Java:
Object Oriented Programming, Two control statements, Using blocks of codes, Lexical
issues,
The java class Libraries.
Control Statements:
Java’s selection Statements, Iteration statements, Jump Statements.
Java is a high level prgg. Lang. It was introduced by “SUN MicroSystems” in June 1995. It
was officially released in November 1995. It was developed by a team under James Gosling.
Its original name was “OAK” meant for consumer electronic devices and later renamed to Java.
Java has become the standard for Internet applications. It provides interactive processing and
easy use of graphics and animation on the Internet.
Since the Internet consists of different types of computers and operating systems. A common
lang. needed to enable computers. To run prgs that run on multiple plot forms. This need was
fulfilled by Java, and it so on. Because the lang.of choice for the Internet. Java is Object- riented
An application is a prg.that runs on the user’s computers under the operating system. An Applet
is a small window based prg.that runs on HTML page using a java enabled web browser like
internet Explorer, Netscape Navigator or an Applet Viewer
Why is it called Java? It is customary for the creator of a programming language to name the
language anything he/she chooses. The original name of this language was Oak, until it was
discovered that a programming language already existed that was named Oak. As the story
goes, after many hours of trying to come up with a new name, the development team went out
for coffee and the name Java was born.
While Java is viewed as a programming language to design applications for the Internet, it
is in reality a general all purpose language which can be used independent of the Internet
Currently, Java is used in internet programming, mobile devices, games, e-business solutions
etc. There are given the major points that describe the history of java.
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 had they choosen 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) Java is an island of Indonesia where first coffee was produced (called java coffee).
10) Originally developed by James Gosling at Sun Microsystems (which is now a subsidiary
of Oracle Corporation) and released in 1995.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
Byte codes are the machine language of the Java virtual machine. When a JVM loads a
class file, it gets one stream of byte codes for each method in the class. The byte codes
streams are stored in the method area of the JVM. The byte codes for a method are executed
when that method is invoked during the course of running the program. They can be
executed by interpretation, just-in-time compiling, or any other technique that was chosen
by the designer of a particular JVM. Byte codes are the machine language of the Java virtual
machine. When a JVM loads a class file, it gets one stream of byte codes for each method
in the class. The byte codes streams are stored in the method area of the JVM. The byte
codes for a method are executed when that method is invoked during the course of running
Java's Lineage
Java is related to C++, which is direct descendent of c. Much of the character of java is inherited
from these two languages. from C, Java derives its syntax. Many of java's object-oriented
features were influenced by C++. In fact, several of java's defining characteristics come from-
or are responses to- its predecessors. Moreover, the creation of java was deeply rooted in the
process of refinement and adaptation that has been occurring in the in computer programming
languages for the past several decades. For these reasons, this section reviews the sequence of
events and forces that led up to java. as you will see, each innovation in language design was
driven by the need to solve a fundamental problem that the preceding languages could not
solve. java is no exception
● There are mainly 4 type of applications that can be created using java:-
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. It has the
advantage of high level security, load balancing and clustering. 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.
Features of a language are nothing but the set of services or facilities provided by the language
vendors to the industry programmers. Some important features of java are;
● Simple
● Platform Independent
● Architectural Neutral
● Portable
1. Simple
● It is free from pointer due to this execution time of application is improved. [Whenever
we write a Java program without pointers then internally it is converted into the
equivalent pointer program].
● It has Rich set of API (application protocol interface).
● It hs Garbage Collector which is always used to collect un-Referenced (unused)
Memory location for improving performance of a Java program.
● It contains user friendly syntax for developing any applications.
Platform Independent
3. Architectural Neutral
A Language or Technology is said to be Architectural neutral which can run on any available
processors in the real world without considering their development and compilation. The
languages like C, CPP are treated as architectural dependent.
If any language supports platform independent and architectural neutral feature known as
portable. The languages like C, CPP, Pascal are treated as non-portable language. It is a
portable language.
According to SUN microsystem.
5. Multithreaded
A flow of control is known as a threa. When any Language executes multiple thread at a time
that language is known as multithreaded e. It is multithreaded.
6. Distributed
7. Networked
It is mainly designed for web based applications; J2EE is used for developing network based
applications.
8. Robust
Simply means of Robust are strong. It is robust or strong Programming Language because of
its capability to handle Run-time Error, automatic garbage collection, the lack of pointer
concept, Exception Handling. All these points make It robust Language.
9. Dynamic
It supports Dynamic memory allocation due to this memory wastage is reduce and improve
performance of the application. The process of allocating the memory space to the input of the
program at a run-time is known as dynamic memory allocation, To programming to allocate
memory space by dynamically we use an operator called 'new' 'new' operator is known as
dynamic memory allocation operator.
10. Secure
● This language uses Bytecode which is faster than ordinary pointer code so Performance
of this language is high.
● Garbage collector, collect the unused memory space and improve the performance of
the application.
● It has no pointers so that using this language we can develop an application very easily.
● It support multithreading, because of this time consuming process can be reduced to
executing the program.
12. Interpreted
It supports OOP's concepts because of this it is most secure language, for this topic you can
read our oop's concepts in detail.
Object means a real word entity such as pen, chair, table etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and objects. It
simplifies the software development and maintenance by providing some concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.
Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example:
phone call, we don't know the internal processing.
Encapsulation
JRE
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.
Implementation of JVMs is also actively released by other companies besides Sun Micro
Systems.
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 is platform independent.
● Loads code
● Verifies code
● Executes code
● Provides runtime environment
It is:
1)ClassLoader
Class loader is a subsystem of JVM that is used to load class files.
3) Heap:
It is the runtime data area in which objects are allocated.
4) Stack:
Java Stack stores frames. It holds local variables and partial results, and plays a part in method
invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its method
invocation completes.
7) Execution Engine:
It contains:
1) A virtual processor
1. class Simple{
2. public static void main(String args[]){
3. System.out.println("Hello Java");
4. }
5. }
Output:Hello Java
Let's see what is the meaning of class, public, static, void, main, String[], System.out.println()
To write the simple program, open notepad by start menu -> All Programs -> Accessories ->
notepad and write simple program as displayed below:
As displayed in the above diagram, write the simple program of java in notepad and saved it as
Simple.java. To compile and run this program, you need to open command prompt by start
menu -> All Programs -> Accessories -> command prompt.
1. temporary
2. permanent
To set the temporary path of JDK, you need to follow following steps:
For setting the permanent path of JDK, you need to follow these steps:
● Go to MyComputer properties -> advanced tab -> environment variables -> new tab of
user variable -> write path in variable name -> write path of bin folder in variable value
-> ok -> ok -> ok
Internal Details of Hello Java Program
In the previous page, we have learned about the first program, how to compile and how to run
the first java program. Here, we are going to learn, what happens while compiling and running
the java program. Moreover, we will see some question based on the first program.
Bytecode Verifier: checks the code fragments for illegal code that can violate access right to
objects.
Q)Can you save a java source file by other name than the class name?
Yes, like the figure given below illustrates:
The path is required to be set for using tools such as javac, java etc.
If you are saving the java source file inside the jdk/bin directory, path is not required to be set
because all the tools will be available in the current directory.
But If you are having your java file outside the jdk/bin folder, it is necessary to set path of JDK
1. Variable
2. Types of Variable
3. Data Types in Java
Variable is a name of memory location. There are three types of variables: local, instance and
static. There are two types of data types in java, primitive and non-primitive.
Variable
Variable is name of reserved area allocated in memory.
Types of Variable
There are three types of variables in java
● local variable
● instance variable
● static variable
Local Variable
A variable that is declared inside the method is called local variable.
Instance Variable
A variable that is declared inside the class but outside the method is called instance variable . It
is not declared as static.
Static variable
A variable that is declared as static is called static variable. It cannot be local.
void method(){
int n=90;//local variable
}
}//end of class
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
OPERATORS:
Java provides a rich set of operators to manipulate variables. We can divide all the Java
operators into the following groups:
Arithmetic operators are used in mathematical expressions in the same way that they are used
in algebra. The following table lists the arithmetic operators:
- Subtraction - Subtracts right hand operand from left hand operand A - B will give -10
A * B will give
* Multiplication - Multiplies values on either side of the operator
200
/ Division - Divides left hand operand by right hand operand B / A will give 2
Checks if the values of two operands are equal or not, if yes then (A == B) is not
==
condition becomes true. true.
Checks if the value of left operand is less than the value of right
< (A < B) is true.
operand, if yes then condition becomes true.
Checks if the value of left operand is greater than or equal to the (A >= B) is not
>=
value of right operand, if yes then condition becomes true. true.
Java defines several bitwise operators, which can be applied to the integer types, long, int,
short, char, and byte.
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60; and b =
13; now in binary format they will be as follows:
a = 0011 1100
b = 0000 1101
-----------------
~a = 1100 0011
(A ^ B) will give
Binary XOR Operator copies the bit if it is set in one operand but
^ 49 which is 0011
not both.
0001
Binary Right Shift Operator. The left operands value is moved A >> 2 will give
>>
right by the number of bits specified by the right operand. 15 which is 1111
Shift right zero fill operator. The left operands value is moved A >>>2 will give
>>> right by the number of bits specified by the right operand and 15 which is 0000
shifted values are filled up with zeros. 1111
Assume Boolean variables A holds true and variable B holds false, then:
C = A + B will
Simple assignment operator, Assigns values from right side
= assign value of A
operands to left side operand
+ B into C
C += A is
Add AND assignment operator, It adds right operand to the left
+= equivalent to C =
operand and assign the result to left operand
C+A
C -= A is
Subtract AND assignment operator, It subtracts right operand
-= equivalent to C =
from the left operand and assign the result to left operand
C-A
C *= A is
Multiply AND assignment operator, It multiplies right operand
*= equivalent to C =
with the left operand and assign the result to left operand
C*A
C /= A is
Divide AND assignment operator, It divides left operand with the
/= equivalent to C =
right operand and assign the result to left operand
C/A
C %= A is
Modulus AND assignment operator, It takes modulus using two
%= equivalent to C =
operands and assign the result to left operand
C%A
C <<= 2 is same as
<<= Left shift AND assignment operator
C = C << 2
C >>= 2 is same as
>>= Right shift AND assignment operator
C = C >> 2
C &= 2 is same as
&= Bitwise AND assignment operator
C=C&2
C ^= 2 is same as
^= bitwise exclusive OR and assignment operator
C=C^2
C |= 2 is same as C
|= bitwise inclusive OR and assignment operator
=C|2
6. Misc Operators
Conditional operator is also known as the ternary operator. This operator consists of three
operands and is used to evaluate Boolean expressions. The goal of the operator is to decide
which value should be assigned to the variable. The operator is written as:
int a , b;
a = 10;
b = (a == 1) ? 20: 30;
Value of b is : 30
Value of b is : 20
instanceof Operator:
This operator is used only for object reference variables. The operator checks whether the
object is of a particular type (class type or interface type). Instance of operator is written as:
A program executes from top to bottom except when we use control statements, we can
control the order of execution of the program, based on logic and values.
● Selection Statements
● Iteration Statements
● Jump Statements
Selection Statements
Selection statements allow you to control the flow of program execution on the basis of the
outcome of an expression or state of a variable known during runtime.
Selection statements can be divided into the following categories:
The if statements
The first contained statement (that can be a block) of an if statement only executes when the
specified condition is true. If the condition is false and there is not else keyword then the first
contained statement will be skipped and execution continues with the rest of the program.
The condition is an expression that returns a boolean value.
import java.util.Scanner;
public class IfDemo
{
public static void main(String[] args) {
int age;
Scanner inputDevice = new Scanner(System.in); System.out.print("Please ent
er Age: ");
age = inputDevice.nextInt();
if(age > 18)
System.out.println("above 18 ");
}
}
Output:
In if-else statements, if the specified condition in the if statement is false, then the statement
after the else keyword (that can be a block) will execute.
import java.util.Scanner;
public class IfElseDemo
{
public static void main( String[] args )
{
int age;
Scanner inputDevice = new Scanner( System.in ); System.out.print( "Please ente
r Age: " );
age = inputDevice.nextInt();
if ( age >= 18 )
System.out.println( "above 18 " );
else
System.out.println( "below 18" );
}
}
OUTPUT:
This statement following the else keyword can be another if or if-else statement.
if(condition)
statements;
else if (condition)
statements;
else if(condition)
statement;
else
statements;
Whenever the condition is true, the associated statement will be executed and the remaining
conditions will be bypassed. If none of the conditions are true then the else block will
execute.
The switch statement is a multi-way branch statement. The switch statement of Java is another
selection statement that defines multiple paths of execution of a program. It provides a better
alternative than a large series of if-else-if statements.
import java.util.Scanner;
public class SwitchDemo
{
public static void main( String[] args )
{
int age;
Scanner inputDevice = new Scanner( System.in );
System.out.print( "Please enter Age: " );
age = inputDevice.nextInt();
switch ( age )
{
case 18:
System.out.println( "age 18" );
break;
case 19:
System.out.println( "age 19" );
break;
default:
System.out.println( "not matched" );
break;
}
An expression must be of a type of byte, short, int or char. Each of the values specified in
the case statement must be of a type compatible with the expression. Duplicate case values
are not allowed. The break statement is used inside the switch to terminate a statement
sequence. The break statement is optional in the switch statement.
Iteration Statements
Repeating the same code fragment several times until a specified condition is satisfied is
called iteration. Iteration statements execute the same set of instructions until a termination
condition is met.
It continually executes a statement (that is usually be a block) while a condition is true. The
condition must return a boolean value.
The only difference between a while and a do-while loop is that do-while evaluates its
expression at the bottom of the loop instead of the top. The do-while loop executes at least
one time then it will check the expression prior to the next iteration.
A for loop executes a statement (that is usually a block) as long as the boolean condition
evaluates to true. A for loop is a combination of the three elements initialization statement,
boolean expression and increment or decrement statement.
Syntax:
This was introduced in Java 5. This loop is basically used to traverse the array or collection
elements.
Jump Statements
Jump statements are used to unconditionally transfer the program control to another part of
the program.
Java provides the following jump statements:
● break statement
● continue statement
● return statement
Break Statement
The break statement immediately quits the current iteration and goes to the first statement
following the loop. Another form of break is used in the switch statement.
Unlabeled Break Statement: This is used to jump program control out of the specific loop on
the specific condition.
Continue Statement
The continue statement is used when you want to continue running the loop with the next
iteration and want to skip the rest of the statements of the body for the current iteration.
Labeled Continue Statement: This statement skips the current iteration of the loop with the
specified label.
The return statement is used to immediately quit the current method and return to the calling
method. It is mandatory to use a return statement for non-void methods to return a value.
int returnCall()
{
return 5;
}
}
Output:
ARRAYS:
An array is a container object that holds a fixed number of values of a single type. The length
of an array is established when the array is created. After creation, its length is fixed. You have
seen an example of arrays already, in the main method of the "Hello World!" application. This
section discusses arrays in greater detail.
Each item in an array is called an element, and each element is accessed by its numerical index.
As shown in the preceding illustration, numbering begins with 0. The 9th element, for example,
would therefore be accessed at index 8.
class ArrayDemo {
public static void main(String[] args) {
// declares an array of integers
int[] anArray;
One way to create an array is with the new operator. The next statement in the ArrayDemo
program allocates an array with enough memory for 10 integer elements and assigns the array
to the anArray variable.
If this statement is missing, then the compiler prints an error like the following, and compilation
fails:
The next few lines assign values to each element of the array:
Alternatively, you can use the shortcut syntax to create and initialize an array:
Here the length of the array is determined by the number of values provided between braces
and separated by commas.
You can also declare an array of arrays (also known as a multidimensional array) by using two
or more sets of brackets, such as String[][] names. Each element, therefore, must be
accessed by a corresponding number of index values.
class MultiDimArrayDemo {
public static void main(String[] args) {
String[][] names = {
{"Mr. ", "Mrs. ", "Ms. "},
{"Smith", "Jones"}
};
// Mr. Smith
System.out.println(names[0][0] + names[1][0]);
// Ms. Jones
System.out.println(names[0][2] + names[1][1]);
}
}
Mr. Smith
Ms. Jones
Finally, you can use the built-in length property to determine the size of any array. The
following code prints the array's size to standard output:
System.out.println(anArray.length);
1. String Handling
2. How to create string objects?
1. String literal
2. new keyword
3. Why Java uses the concept of String literal?
In java, string is basically an immutable object. We will discuss about immutable string later.
Let's first understand what string is and how we can create the string object.
String
Generally string is a sequence of characters. But in java, string is an object. String class is used
to create string object.
Do You Know ?
1. By string literal
2. By new keyword
1) String literal
1. String s="Hello";
Each time you create a string literal, the JVM checks the string constant pool first. If the string
already exists in the pool, a reference to the pooled instance returns. If the string does not exist
in the pool, a new String object instantiates, then is placed in the pool.For example:
1. String s1="Welcome";
2. String s2="Welcome";//no new object will be created
Note: String objects are stored in a special memory area known as string constant pool
inside the Heap memory.
To make Java more memory efficient (because no new objects are created if it exists already in
string constant pool).
2) By new keyword
In such case, JVM will create a new String object in normal(nonpool) Heap memory and the
literal "Welcome" will be placed in the string constant pool.The variable s will refer to the object
in Heap(nonpool).
● Concept of String
● Immutable String
● String Comparison
● String Concatenation
● Concept of Substring
● String class methods and its usage
Once string object is created its data or state can't be changed but a new string object is created.
Let's try to understand the immutability concept by the example given below:
1. class Simple{
2. public static void main(String args[]){
3. String s="Sachin";
4. s.concat(" Tendulkar");//concat() method appends the string at the end
5. System.out.println(s);//will print Sachin because strings are immutable objects
6. }
7. }
Output:Sachin
Now it can be understood by the diagram given below. Here Sachin is not changed but a new
object is created with sachintendulkar. That is why string is known as immutable.
As you can see in the above figure that two objects are created but s reference variable still
refers to "Sachin" not to "Sachin Tendulkar".
1. class Simple{
2. public static void main(String args[]){
3. String s="Sachin";
4. s=s.concat(" Tendulkar");
5. System.out.println(s);
6. }
7. }
Output:Sachin Tendulkar
In such case, s points to the "Sachin Tendulkar". Please notice that still sachin object is not
modified.
Because java uses the concept of string literal.Suppose there are 5 reference variables,all
referes to one object "sachin".If one reference variable changes the value of the object, it will
be affected to all the reference variables. That is why string objects are immutable in java.
We can compare two given strings on the basis of content and reference.
It is used in authentication (by equals() method), sorting (by compareTo() method), reference
matching (by == operator) etc.
1. By equals() method
1) By equals() method
equals() method compares the original content of the string.It compares values of string for
equality.String class provides two methods:
● public boolean equals(Object another){} compares this string to the specified object.
● public boolean equalsIgnoreCase(String another){} compares this String to another
String, ignoring case.
1. class Simple{
2. public static void main(String args[]){
3.
4. String s1="Sachin";
5. String s2="Sachin";
6. String s3=new String("Sachin");
7. String s4="Saurav";
8.
9. System.out.println(s1.equals(s2));//true
10. System.out.println(s1.equals(s3));//true
11. System.out.println(s1.equals(s4));//false
12. }
13. }
Output:true
true
false
Output:false
true
1. //<b><i>Example of == operator</i></b>
2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s1="Sachin";
7. String s2="Sachin";
8. String s3=new String("Sachin");
9.
10. System.out.println(s1==s2);//true (because both refer to same instance)
11. System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)
12. }
13. }
Output:true
false
3) By compareTo() method:
compareTo() method compares values and returns an int which tells if the values compare less
than, equal, or greater than.
● s1 == s2 :0
● s1 > s2 :positive value
● s1 < s2 :negative value
Output:0
-1
Concating strings form a new string i.e. the combination of multiple strings.
Output:Sachin Tendulkar
String concatenation is implemented through the StringBuilder(or StringBuffer) class and its
append method.String concatenation operator produces a new string by appending the second
operand onto the end of the first operand.The string concatenation operator can concat not only
string but primitive values also.For Example:
1. class Simple{
2. public static void main(String args[]){
Output:80Sachin4040
Note:If either operand is a string, the resulting operation will be string concatenation. If both
operands are numbers, the operator will perform an addition.
2) By concat() method
concat() method concatenates the specified string to the end of current string.
Output:Sachin Tendulkar
c) Substring in Java
A part of string is called substring. In other words, substring is a subset of another string.
You can get substring from the given String object by one of the two methods:
1. public String substring(int startIndex): This method returns new String object
containing the substring of the given string from specified startIndex (inclusive).
2. public String substring(int startIndex,int endIndex): This method returns new String
object containing the substring of the given string from specified startIndex to endIndex.
In case of string:
Output:Tendulkar
Sachin
java.lang.String class provides a lot of methods to work on string. By the help of these methods,
we can perform operations on string such as trimming, concatenating, converting strings etc.
Method Description
1)public boolean equals(Object anObject) Compares this string to the specified object.
4)public int compareTo(String str) Compares two strings and returns int
7)public String substring(int beginIndex,int Returns a new string that is a substring of this
endIndex) string.
13)public char charAt(int index) Returns the char value at the specified index.
24)public static String valueOf(char[] i) converts the char array into String.
25)public static String valueOf(Object obj) converts the Object into String.
First seven methods have already been discussed.Now Let's take the example of other methods:
1. class Simple{
2. public static void main(String args[]){
3.
4. String s="Sachin";
5. System.out.println(s.toUpperCase());//SACHIN
6. System.out.println(s.toLowerCase());//sachin
7. System.out.println(s);//Sachin(no change in original)
8. }
9. }
Output:SACHIN
sachin
Sachin
trim() method
1. class Simple{
2. public static void main(String args[]){
3.
4. String s=" Sachin ";
5. System.out.println(s);// Sachin
6. System.out.println(s.trim());//Sachin
Output:Sachin
Sachin
1. class Simple{
2. public static void main(String args[]){
3.
4. String s="Sachin";
5. System.out.println(s.startsWith("Sa"));//true
6. System.out.println(s.endsWith("n"));//true
7. }
8. }
Output:true
true
charAt() method
1. class Simple{
2. public static void main(String args[]){
3.
4. String s="Sachin";
5. System.out.println(s.charAt(0));//S
6. System.out.println(s.charAt(3));//h
7. }
8. }
Output:S
h
length() method
1. class Simple{
2. public static void main(String args[]){
3.
4. String s="Sachin";
5. System.out.println(s.length());//6
6. }
7. }
Output:6
intern() method
When the intern method is invoked, if the pool already contains a string equal to this String
object as determined by the equals(Object) method, then the string from the pool is returned.
Otherwise, this String object is added to the pool and a reference to this String object is
returned.
1. class Simple{
2. public static void main(String args[]){
3.
4. String s=new String("Sachin");
5. String s2=s.intern();
6. System.out.println(s2);//Sachin
7. }
8. }
Output:Sachin
StringBuffer class:
The StringBuffer class is used to created mutable (modifiable) string. The StringBuffer class
is same as String except it is mutable i.e. it can be changed.
Note: StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously
.So it is safe and will result in an order.
1. class A{
2. public static void main(String args[]){
3.
4. StringBuffer sb=new StringBuffer("Hello ");
5. sb.append("Java");//now original string is changed
6.
7. System.out.println(sb);//prints Hello Java
8. }
9. }
1. class A{
2. public static void main(String args[]){
3.
4. StringBuffer sb=new StringBuffer("Hello ");
5. sb.insert(1,"Java");//now original string is changed
6.
7. System.out.println(sb);//prints HJavaello
8. }
9. }
1. class A{
2. public static void main(String args[]){
1. class A{
2. public static void main(String args[]){
3.
4. StringBuffer sb=new StringBuffer("Hello");
5. sb.delete(1,3);
6.
7. System.out.println(sb);//prints Hlo
8. }
9. }
1. class A{
2. public static void main(String args[]){
3.
4. StringBuffer sb=new StringBuffer("Hello");
5. sb.reverse();
6.
7. System.out.println(sb);//prints olleH
8. }
9. }
1. class A{
2. public static void main(String args[]){
3.
4. StringBuffer sb=new StringBuffer();
5. System.out.println(sb.capacity());//default 16
1. class A{
2. public static void main(String args[]){
3.
4. StringBuffer sb=new StringBuffer();
5. System.out.println(sb.capacity());//default 16
6.
7. sb.append("Hello");
8. System.out.println(sb.capacity());//now 16
9.
10. sb.append("java is my favourite language");
11. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
12.
13. sb.ensureCapacity(10);//now no change
14. System.out.println(sb.capacity());//now 34
15.
16. sb.ensureCapacity(50);//now (34*2)+2
17. System.out.println(sb.capacity());//now 70
18.
19. }
20. }
StringBuilder class:
The StringBuilder class is used to create mutable (modifiable) string. The StringBuilder class
is same as StringBuffer class except that it is non-synchronized. It is available since JDK1.5.
1. StringBuilder(): creates an empty string Builder with the initial capacity of 16.
2. StringBuilder(String str): creates a string Builder with the specified string.
1. public StringBuilder append(String s): is used to append the specified string with
this string. The append() method is overloaded like append(char), append(boolean),
append(int), append(float), append(double) etc.
2. public StringBuilder 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.
3. public StringBuilder replace(int startIndex, int endIndex, String str): is used to
replace the string from specified startIndex and endIndex.
4. public StringBuilder delete(int startIndex, int endIndex): is used to delete the string
from specified startIndex and endIndex.
5. public StringBuilder reverse(): is used to reverse the string.
6. public int capacity(): is used to return the current capacity.
7. public void ensureCapacity(int minimumCapacity): is used to ensure the capacity
at least equal to the given minimum.
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.
The append() method concatenates the given argument with this string.
1. class A{
2. public static void main(String args[]){
3.
4. StringBuilder sb=new StringBuilder("Hello ");
5. sb.append("Java");//now original string is changed
6.
7. System.out.println(sb);//prints Hello Java
8. }
9. }
The insert() method inserts the given string with this string at the given position.
The replace() method replaces the given string from the specified beginIndex and endIndex.
1. class A{
2. public static void main(String args[]){
3.
4. StringBuilder sb=new StringBuilder("Hello");
5. sb.replace(1,3,"Java");
6.
7. System.out.println(sb);//prints HJavalo
8. }
9. }
The delete() method of StringBuilder class deletes the string from the specified beginIndex to
endIndex.
1. class A{
2. public static void main(String args[]){
3.
4. StringBuilder sb=new StringBuilder("Hello");
5. sb.delete(1,3);
6.
7. System.out.println(sb);//prints Hlo
8. }
9. }
1. class A{
2. public static void main(String args[]){
The capacity() method of StringBuilder class returns the current capacity of the Builder. The
default capacity of the Builder is 16. If the number of character increases from its current
capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity
is 16, it will be (16*2)+2=34.
1. class A{
2. public static void main(String args[]){
3.
4. StringBuilder sb=new StringBuilder();
5. System.out.println(sb.capacity());//default 16
6.
7. sb.append("Hello");
8. System.out.println(sb.capacity());//now 16
9.
10. sb.append("java is my favourite language");
11. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
12. }
13. }
The ensureCapacity() method of StringBuilder class ensures that the given capacity is the
minimum to the current capacity. If it is greater than the current capacity, it increases the
capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be
(16*2)+2=34.
1. class A{
2. public static void main(String args[]){
3.
4. StringBuilder sb=new StringBuilder();
5. System.out.println(sb.capacity());//default 16
6.
7. sb.append("Hello");
8. System.out.println(sb.capacity());//now 16
9.
10. sb.append("java is my favourite language");
11. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
If you want to represent any object as a string, toString() method comes into existence.
If you print any object, java compiler internally invokes the toString() method on the object. So
overriding the toString() method, returns the desired output, it can be the state of an object etc.
depends on your implementation.
By overriding the toString() method of the Object class, we can return values of the object, so
we don't need to write much code.
1. class Student{
2. int rollno;
3. String name;
4. String city;
5.
6. Student(int rollno, String name, String city){
7. this.rollno=rollno;
8. this.name=name;
9. this.city=city;
10. }
11. public static void main(String args[]){
12. Student s1=new Student(101,"Raj","lucknow");
13. Student s2=new Student(102,"Vijay","ghaziabad");
14.
15. System.out.println(s1);//compiler writes here s1.toString()
16. System.out.println(s2);//compiler writes here s2.toString()
17. }
18. }
1. class Student{
2. int rollno;
3. String name;
4. String city;
5. Student(int rollno, String name, String city){
6. this.rollno=rollno;
7. this.name=name;
8. this.city=city;
9. }
10. public String toString(){//overriding the toString() method
11. return rollno+" "+name+" "+city;
12. }
13. public static void main(String args[]){
14. Student s1=new Student(101,"Raj","lucknow");
15. Student s2=new Student(102,"Vijay","ghaziabad");
16.
17. System.out.println(s1);//compiler writes here s1.toString()
18. System.out.println(s2);//compiler writes here s2.toString()
19. }
20. }
StringTokenizer in Java
1. StringTokenizer
2. Methods of StringTokenizer
3. Example of StringTokenizer
The java.util.StringTokenizer class allows you to break a string into tokens. It is simple way
to break string.
It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like
StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter.
Constructor Description
StringTokenizer(String str,
creates StringTokenizer with specified string and delimeter.
String delim)
String nextToken() returns the next token from the StringTokenizer object.
String nextToken(String delim) returns the next token based on the delimeter.
Let's see the simple example of StringTokenizer class that tokenizes a string "my name is khan"
on the basis of whitespace.
1. import java.util.StringTokenizer;
2. public class Simple{
3. public static void main(String args[]){
4. StringTokenizer st = new StringTokenizer("my name is khan"," ");
5. while (st.hasMoreTokens()) {
6. System.out.println(st.nextToken());
7. }
8. }
Output:my
name
is
khan
1. import java.util.*;
2.
3. public class Test {
4. public static void main(String[] args) {
5. StringTokenizer st = new StringTokenizer("my,name,is,khan");
6.
7. // printing next token
8. System.out.println("Next token is : " + st.nextToken(","));
9. }
10. }
Output:Next token is : my
UNIT-II
Introducing Classes:
Class Fundamentals
Class
In Java everything is encapsulated under classes. Class is the core of Java language. Class can
be defined as a template/ blueprint that describe the behaviors /states of a particular entity. A
class defines new data type. Once defined this new type can be used to create object of that
A class is declared using class keyword. A class contains both data and code that operate on
that data. The data or variables defined within a class are called instance variables and the
code that operates on this data is known as methods.
● A class can have only public or default (no modifier) access specifier.
● It can be either abstract, final or concrete (normal class).
● It must have the class keyword, and class must be followed by a legal identifier.
● It may optionally extend one parent class. By default, it will extend java.lang.Object.
● It may optionally implement any number of comma-separated interfaces.
● The class's variables and methods are declared within a set of curly braces {}.
● Each .java source file may contain only one public class. A source file may contain any
number of default visible classes.
● Finally, the source file name must match the public class name and it must have a .java
suffix.
int age;
When a reference is made to a particular student with its property then it becomes an object,
physical existence of Student class.
After the above statement std is instance/object of Student class. Here the new keyword creates
an actual physical copy of the object and assign it to the std variable. It will have physical
existence and get memory in heap area. The new operator dynamically allocates memory for
an object
A Class is initialized in Java when an instance of class is created using either new operator or
using reflection using class.forName(). A class is also said to be initialized when a static method
of Class is invoked or a static field of Class is assigned.
Q. How would you make a copy of an entire Java object with its state?
Make that class implement Cloneable interface and call clone() method on its object. clone()
method is defined in Object class which is parent of all java class by default.
Methods in Java
Method describe behavior of an object. A method is a collection of statements that are group
together to perform an operation.
Syntax :
return-type methodName(parameter-list)
//body of method
Example of a Method
String name="StudyTonight";
name=name+st;
return name;
Modifier : Modifier are access type of method. We will discuss it in detail later.
Return Type : A method may return value. Data type of value return by a method is declare in
method heading.
Parameter is variable defined by a method that receives value when the method is called.
Parameter are always local to the method they dont have scope outside the method. While
argument is a value that is passed to a method when it is called.
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.
Example of call-by-value
x=100;
int x=50;
System.out.println(x);
Output : 50
Example of call-by-reference
int x=10;
int y=20;
t.x=100;
t.y=50;
ts.callByReference(ts);
Output :
Before 10 20
After 100 50
1. Object in Java
2. Class in Java
3. Instance Variable in Java
4. Method in Java
Object is the physical as well as logical entity whereas class is the logical entity only.
Object in Java
An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table,
car etc. It can be physical or logical (tengible and intengible). The example of integible object
is banking system.
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It
is used to write, so writing is its behavior.
Object is an instance of a class. Class is a template or blueprint from which objects are
created. So object is the instance (result) of a class.
Class in Java
A class is a group of objects that has common properties. It is a template or blueprint from which objects
are created.
● data member
● method
● constructor
● block
● class and interface
1. class <class_name>{
2. data member;
3. method;
4. }
In this example, we have created a Student class that has two data members’ id and name. We
are creating the object of the Student class by new keyword and printing the objects value.
1. class Student{
2. int id;//data member (also instance variable)
3. String name;//data member(also instance variable)
4.
5. public static void main(String args[]){
6. Student s1=new Student();//creating an object of Student
7. System.out.println(s1.id+" "+s1.name);
8.
9. }
Method in Java
In java, a method is like function i.e. used to expose behaviour of an object.
Advantage of Method
● Code Reusability
● Code Optimization
new keyword
The new keyword is used to allocate memory at runtime.
1. class Student{
2. int rollno;
3. String name;
4.
5. void insertRecord(int r, String n){ //method
6. rollno=r;
7. name=n;
8. }
9.
10. void displayInformation(){System.out.println(rollno+" "+name);}//method
11.
12. public static void main(String args[]){
13. Student s1=new Student();
14. Student s2=new Student();
15.
16. s1.insertRecord(111,"Karan");
17. s2.insertRecord(222,"Aryan");
18.
19. s1.displayInformation();
20. s2.displayInformation();
21.
22. }
Output:111 Karan
222 Aryan
As you see in the above figure, object gets the memory in Heap area and reference variable
refers to the object allocated in the Heap memory area. Here, s1 and s2 both are reference
variables that refer to the objects allocated in memory.
1. class Rectangle{
2. int length;
3. int width;
4.
5. void insert(int l,int w){
6. length=l;
7. width=w;
8. }
9.
10. void calculateArea(){System.out.println(length*width);}
11.
12. public static void main(String args[]){
13. Rectangle r1=new Rectangle();
14. Rectangle r2=new Rectangle();
15.
16. r1.insert(11,5);
17. r2.insert(3,15);
18.
19. r1.calculateArea();
20. r2.calculateArea();
21. }
22. }
● By new keyword
● By newInstance() method
● By clone() method
● By factory method etc.
Anonymous object
Anonymous simply means nameless. An object that has no reference is known as anonymous
object.
If you have to use an object only once, anonymous object is a good approach.
1. class Calculation{
2.
3. void fact(int n){
4. int fact=1;
5. for(int i=1;i<=n;i++){
6. fact=fact*i;
7. }
8. System.out.println("factorial is "+fact);
9. }
10.
11. public static void main(String args[]){
12. new Calculation().fact(5);//calling method with annonymous object
13. }
14. }
Output:Factorial is 120
1. class Rectangle{
2. int length;
3. int width;
4.
5. void insert(int l,int w){
6. length=l;
7. width=w;
8. }
9.
10. void calculateArea(){System.out.println(length*width);}
11.
12. public static void main(String args[]){
13. Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
14.
15. r1.insert(11,5);
16. r2.insert(3,15);
17.
18. r1.calculateArea();
19. r2.calculateArea();
20. }
21. }
Output:55
45
CONSTRUCTORS
1. Types of constructors
1. Default Constructor
2. Parameterized Constructor
2. Constructor Overloading
3. Does constructor return any value
4. Copying the values of one object into another
5. Does constructor perform other task instead initialization
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.
Types of constructors
1) Default Constructor
A constructor that has no parameter is known as default constructor.
1. <class_name>(){}
1. class Bike{
2.
3. Bike(){System.out.println("Bike is created");}
4.
5. public static void main(String args[]){
6. Bike b=new Bike();
7. }
8. }
Default constructor provides the default values to the object like 0, null etc. depending on the
type.
Output:0 null
0 null
Explanation:In the above class,you are not creating any constructor so compiler provides you
a default constructor.Here 0 and null values are provided by default constructor.
2. Parameterized constructor
A constructor that has parameters is known as parameterized constructor.
1. class Student{
2. int id;
3. String name;
4.
5. Student(int i,String n){
6. id = i;
7. name = n;
8. }
9. void display(){System.out.println(id+" "+name);}
10.
11. public static void main(String args[]){
12. Student s1 = new Student(111,"Karan");
13. Student s2 = new Student(222,"Aryan");
14. s1.display();
15. s2.display();
16. }
17. }
Output:111 Karan
222 Aryan
Constructor Overloading
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.
1. class Student{
2. int id;
3. String name;
4. int age;
5. Student(int i,String n){
6. id = i;
7. name = n;
8. }
9. Student(int i,String n,int a){
10. id = i;
11. name = n;
12. age=a;
13. }
14. void display(){System.out.println(id+" "+name+" "+age);}
Constructor Method
Constructor must not have return type. Method must have return type.
The java compiler provides a default constructor if you Method is not provided by compiler
don't have any constructor. in any case.
Copying the values of one object to another like copy constructor in C++
There are many ways to copy the values of one object into another. They are:
● By constructor
● By assigning the values of one object into another
● By clone() method of Object class
In this example, we are going to copy the values of one object into another using constructor.
1. class Student{
2. int id;
3. String name;
4. Student(int i,String n){
5. id = i;
6. name = n;
7. }
Output:111 Karan
111 Karan
1. class Student{
2. int id;
3. String name;
4. Student(int i,String n){
5. id = i;
6. name = n;
7. }
8. Student(){}
9. void display(){System.out.println(id+" "+name);}
10.
11. public static void main(String args[]){
12. Student s1 = new Student(111,"Karan");
13. Student s2 = new Student();
14. s2.id=s1.id;
15. s2.name=s1.name;
16. s1.display();
17. s2.display();
18. }
19. }
Output:111 Karan
111 Karan
Yes, like object creation, starting a thread, calling method etc. You can perform any operation
in the constructor as you perform in the method.
1. this keyword
2. Usage of this keyword
1. to refer the current class instance variable
2. to invoke the current class constructor
3. to invoke the current class method
4. to pass as an argument in the method call
5. to pass as an argument in the constructor call
6. to return the current class instance
3. Proving this keyword
There can be a lot of usage of java this keyword. In java, this is a reference variable that
refers to the current object.
Suggestion: If you are beginner to java, lookup only two usage of this keyword.
1) The this keyword can be used to refer current class instance variable.
If there is ambiguity between the instance variable and parameter, this keyword resolves the
problem of ambiguity.
1. class Student10{
2. int id;
3. String name;
4.
5. Student10(int id,String name){
6. id = id;
7. name = name;
8. }
9. void display(){System.out.println(id+" "+name);}
10.
11. public static void main(String args[]){
12. Student10 s1 = new Student10(111,"Karan");
13. Student10 s2 = new Student10(321,"Aryan");
14. s1.display();
15. s2.display();
16. }
17. }
Output:0 null
0 null
In the above example, parameter (formal arguments) and instance variables are same that is
why we are using this keyword to distinguish between local variable and instance variable.
If local variables(formal arguments) and instance variables are different, there is no need to
use this keyword like in the following program:
1. class Student12{
2. int id;
3. String name;
4.
5. Student12(int i,String n){
6. id = i;
7. name = n;
8. }
9. void display(){System.out.println(id+" "+name);}
10. public static void main(String args[]){
11. Student12 e1 = new Student12(111,"karan");
12. Student12 e2 = new Student12(222,"Aryan");
13. e1.display();
14. e2.display();
15. }
16. }
Output:111 Karan
222 Aryan
The this() constructor call can be used to invoke the current class constructor (constructor
chaining). This approach is better if you have many constructors in the class and want to reuse
that constructor.
Output:
default constructor is invoked
default constructor is invoked
111 Karan
222 Aryan
1. class Student14{
2. int id;
3. String name;
4. String city;
5.
6. Student14(int id,String name){
7. this.id = id;
8. this.name = name;
9. }
10. Student14(int id,String name,String city){
1. class Student15{
2. int id;
3. String name;
4. Student15(){System.out.println("default constructor is invoked");}
5.
6. Student15(int id,String name){
7. id = id;
8. name = name;
9. this ();//must be the first statement
10. }
11. void display(){System.out.println(id+" "+name);}
12.
13. public static void main(String args[]){
14. Student15 e1 = new Student15(111,"karan");
15. Student15 e2 = new Student15(222,"Aryan");
16. e1.display();
17. e2.display();
18. }
19. }
3)The this keyword can be used to invoke current class method (implicitly).
You may invoke the method of the current class by using the this keyword. If you don't use
the this keyword, compiler automatically adds this keyword while invoking the method. Let's
see the example
Output:method is invoked
1. class S2{
2. void m(S2 obj){
3. System.out.println("method is invoked");
4. }
5. void p(){
6. m(this);
7. }
8.
9. public static void main(String args[]){
10. S2 s1 = new S2();
Output:method is invoked
1. class B{
2. A4 obj;
3. B(A4 obj){
4. this.obj=obj;
5. }
6. void display(){
7. System.out.println(obj.data);//using data member of A4 class
8. }
9. }
10. class A4{
11. int data=10;
12. A4(){
13. B b=new B(this);
14. b.display();
15. }
16. public static void main(String args[]){
17. A4 a=new A4();
18. }
19. }
Output:10
1. return_type method_name(){
Example of this keyword that you return as a statement from the method
1. class A{
2. A getA(){
3. return this;
4. }
5. void msg(){System.out.println("Hello java");}
6. }
7.
8. class Test1{
9. public static void main(String args[]){
10. new A().getA().msg();
11. }
12. }
Output:Hello java
1. class A5{
2. void m(){
3. System.out.println(this);//prints same reference ID
4. }
5. public static void main(String args[]){
6. A5 obj=new A5();
7. System.out.println(obj);//prints the reference ID
8.
9. obj.m();
10. }
11. }
Output:A5@22b3ea59
A5@22b3ea59
GARBAGE COLLECTION
o It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we don't need to
make extra efforts.
1) By nulling a reference:
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 as:
Note: The Garbage collector of JVM collects only those objects that are created by new
keyword. So if you have created any object without new, you can use finalize method to
perform cleanup processing (destroying remaining objects).
gc() method
Java Runtime class is used to interact with java runtime environment. Java Runtime class
provides methods to execute a process, invoke GC, get total and free memory etc. There is only
one instance of java.lang.Runtime class is available for one java application.
In the given program, after creating 10000 instance, free memory will be less than the previous
free memory. But after gc() call, you will get more free memory.
Constructor Overloading
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.
Output:111 Karan 0
222 Aryan 25
METHOD OVERLOADING
If a class has 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.
In java, Method Overloading is not possible by changing the return type of the method.
In this example, we have created two overloaded methods, first sum method performs addition
of two numbers and second sum method performs addition of three numbers.
1. class Calculation{
2. void sum(int a,int b){System.out.println(a+b);}
3. void sum(int a,int b,int c){System.out.println(a+b+c);}
4.
5. public static void main(String args[]){
6. Calculation obj=new Calculation();
7. obj.sum(10,10,10);
8. obj.sum(20,20);
9.
10. }
Output:30
40
In this example, we have created two overloaded methods that differs in data type. The first
sum method receives two integer arguments and second sum method receives two double
arguments.
1. class Calculation{
2. void sum(int a,int b){System.out.println(a+b);}
3. void sum(double a,double b){System.out.println(a+b);}
4.
5. public static void main(String args[]){
6. Calculation obj=new Calculation();
7. obj.sum(10.5,10.5);
8. obj.sum(20,20);
9.
10. }
11. }
Output:21.0
40
Que) Why Method Overloaing is not possible by changing the return type of
method?
In java, method overloading is not possible by changing the return type of the method because
there may occur ambiguity. Let's see how ambiguity may occur: because there was problem:
1. class Calculation{
2. int sum(int a,int b){System.out.println(a+b);}
3. double sum(int a,int b){System.out.println(a+b);}
4.
5. public static void main(String args[]){
6. Calculation obj=new Calculation();
7. int result=obj.sum(20,20); //Compile Time Error
8.
9. }
10. }
int result=obj.sum(20,20); //Here how can java determine which sum() method should be called
Yes, by method overloading. You can have any number of main methods in a class by method
overloading. Let's see the simple example:
One type is promoted to another implicitly if no matching datatype is found. Let's understand
the concept by the figure given below:
As displayed in the above diagram, byte can be promoted to short, int, long, float or double.
The short datatype can be promoted to int,long,float or double. The char datatype can be
promoted to int,long,float or double and so on.
Output:40
60
If there are matching type arguments in the method, type promotion is not performed.
1. class Calculation{
2. void sum(int a,int b){System.out.println("int arg method invoked");}
3. void sum(long a,long b){System.out.println("long arg method invoked");}
4. public static void main(String args[]){
5. Calculation obj=new Calculation();
6. obj.sum(20,20);//now int arg sum() method gets invoked
7. }
8. }
1. class Calculation{
2. void sum(int a,long b){System.out.println("a method invoked");}
3. void sum(long a,int b){System.out.println("b method invoked");}
4. public static void main(String args[]){
5. Calculation obj=new Calculation();
6. obj.sum(20,20);//now ambiguity
7. }
8. }
One type is not de-promoted implicitly for example double cannot be depromoted to any type
implicitly
1. Static variable
2. Program of counter without static variable
3. Program of counter with static variable
4. Static method
5. Restrictions for static method
6. Why main method is static ?
7. Static block
8. Can we execute a program without main method ?
The static keyword in java is used for memory management mainly. We can apply java static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the
class than instance of the class.
● The static variable can be used to refer the common property of all objects (that is not
unique for each object) e.g. company name of employees,college name of students etc.
● The static variable gets memory only once in class area at the time of class loading.
1. class Student{
2. int rollno;
3. String name;
4. String college="ITS";
5. }
Suppose there are 500 students in my college, now all instance data members will get memory
each time when 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.
In this example, we have created an instance variable named count which is incremented in the
constructor. Since instance variable gets the memory at the time of object creation, each object
will have the copy of the instance variable, if it is incremented, it won't reflect to other objects.
So each objects will have the value 1 in the count variable.
1. class Counter{
2. int count=0;//will get memory when instance is created
3.
4. Counter(){
5. count++;
6. System.out.println(count);
7. }
8.
9. public static void main(String args[]){
10.
11. Counter c1=new Counter();
12. Counter c2=new Counter();
13. Counter c3=new Counter();
14.
15. }
16. }
1. class Counter2{
2. static int count=0;//will get memory only once and retain its value
3. Counter2(){
4. count++;
5. System.out.println(count);
6. }
7. public static void main(String args[]){
8. Counter2 c1=new Counter2();
9. Counter2 c2=new Counter2();
10. Counter2 c3=new Counter2();
11.
12. }
13. }
Output:1
2
3
If you apply static keyword with any method, it is known as static method.
Output:125
1. The static method cannot use non static data member or call non-static method directly.
2. this and super cannot be used in static context.
1. class A{
2. int a=40;//non static
3.
4. public static void main(String args[]){
5. System.out.println(a);
1. class A2{
2. static{System.out.println("static block is invoked");}
3. public static void main(String args[]){
4. System.out.println("Hello main");
5. }
6. }
Ans) Yes, one of the way is static block but in previous version of JDK not in JDK 1.7.
1. class A3{
2. static{
3. System.out.println("static block is invoked");
4. System.exit(0);
5. }
6. }
Output:Error: Main method not found in class A3, please define the main method as:
public static void main(String[] args)
Java inner class or nested class is a class i.e. declared inside the class or interface.
We use inner classes to logically group classes and interfaces in one place so that it can be
more readable and maintainable.
Additionally, it can access all the members of outer class including private data members and
methods.
1. class Java_Outer_class{
2. //code
3. class Java_Inner_class{
4. //code
5. }
6. }
There are basically three advantages of inner classes in java. They are as follows:
1) Nested classes represent a special type of relationship that is it can access all the members
(data members and methods) of outer class including private.
2) Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.
Do You Know
o What is the internal code generated by the compiler for member inner class ?
o What are the two ways to create annonymous inner class ?
o Can we access the non-final local variable inside the local inner class ?
o How to access the static nested class ?
o Can we define an interface within the class ?
o Can we define a class within the interface ?
Inner class is a part of nested class. Non-static nested classes are known as inner classes.
Type Description
Member Inner Class A class created within class and outside method.
Anonymous Inner A class created for implementing interface or extending class. Its name is
Class decided by the java compiler.
A non-static class that is created inside a class but outside a method is called member inner
class.
Syntax:
1. class Outer{
2. //code
3. class Inner{
4. //code
5. }
6. }
In this example, we are creating msg() method in member inner class that is accessing the
private data member of outer class.
1. class TestMemberOuter1{
2. private int data=30;
3. class Inner{
4. void msg(){System.out.println("data is "+data);}
5. }
Output:
data is 30
The java compiler creates two class files in case of inner class. The class file name of inner
class is "Outer$Inner". If you want to instantiate inner class, you must have to create the
instance of outer class. In such case, instance of inner class is created inside the instance of
outer class.
The java compiler creates a class file named Outer$Inner in this case. The Member inner class
have the reference of Outer class that is why it can access all the data members of Outer class
including private.
1. import java.io.PrintStream;
2. class Outer$Inner
3. {
4. final Outer this$0;
5. Outer$Inner()
6. { super();
7. this$0 = Outer.this;
8. }
9. void msg()
10. {
11. System.out.println((new StringBuilder()).append("data is ")
12. .append(Outer.access$000(Outer.this)).toString());
13. }
14. }
Java Anonymous inner class
A class that have no name is known as anonymous inner class in java. It should be used if you
have to override method of class or interface. Java Anonymous inner class can be created by
two ways:
Output:
nice fruits
1. import java.io.PrintStream;
2. static class TestAnonymousInner$1 extends Person
3. {
4. TestAnonymousInner$1(){}
5. void eat()
6. {
7. System.out.println("nice fruits");
8. }
9. }
1. interface Eatable{
2. void eat();
3. }
4. class TestAnnonymousInner1{
5. public static void main(String args[]){
6. Eatable e=new Eatable(){
Output:
nice fruits
A class i.e. created inside a method is called local inner class in java. If you want to invoke the
methods of local inner class, you must instantiate this class inside the method.
Output:
30
In such case, compiler creates a class named Simple$1Local that have the reference of the outer
class.
1. import java.io.PrintStream;
2. class localInner1$Local
3. {
4. final localInner1 this$0;
5. localInner1$Local()
6. {
7. super();
8. this$0 = Simple.this;
9. }
10. void msg()
11. {
12. System.out.println(localInner1.access$000(localInner1.this));
13. }
14. }
2) Local inner class cannot access non-final local variable till JDK 1.7. Since JDK 1.8, it
is possible to access the non-final local variable in local inner class.
Output:
50
Java static nested class
A static class i.e. created inside a class is called static nested class in java. It cannot access non-
static data members and methods. It can be accessed by outer class name.
1. class TestOuter1{
2. static int data=30;
3. static class Inner{
4. void msg(){System.out.println("data is "+data);}
5. }
6. public static void main(String args[]){
7. TestOuter1.Inner obj=new TestOuter1.Inner();
8. obj.msg();
9. }
10. }
Output:
data is 30
In this example, you need to create the instance of static nested class because it has instance
method msg(). But you don't need to create the object of Outer class because nested class is
static and static properties, methods or classes can be accessed without object.
1. class TestOuter2{
2. static int data=30;
3. static class Inner{
4. static void msg(){System.out.println("data is "+data);}
5. }
6. public static void main(String args[]){
7. TestOuter2.Inner.msg();//no need to create the instance of static nested class
8. }
9. }
Output:
data is 30
Java Nested Interface
An interface i.e. declared within another interface or class is known as nested interface. The
nested interfaces are used to group related interfaces so that they can be easy to maintain. The
nested interface must be referred by the outer interface or class. It can't be accessed directly.
There are given some points that should be remembered by the java programmer.
o Nested interface must be public if it is declared inside the interface but it can have any
access modifier if declared within the class.
o Nested interfaces are declared static implicitely.
1. interface interface_name{
2. ...
3. interface nested_interface_name{
4. ...
5. }
6. }
1. class class_name{
2. ...
3. interface nested_interface_name{
4. ...
5. }
6. }
In this example, we are going to learn how to declare the nested interface and how we can
access it.
1. interface Showable{
2. void show();
3. interface Message{
4. void msg();
5. }
6. }
7.
8. class TestNestedInterface1 implements Showable.Message{
9. public void msg(){System.out.println("Hello nested interface");}
10.
11. public static void main(String args[]){
12. Showable.Message message=new TestNestedInterface1();//upcasting here
13. message.msg();
14. }
15. }
Output:hello nested interface
As you can see in the above example, we are acessing the Message interface by its outer
interface Showable because it cannot be accessed directly. It is just like almirah inside the
room, we cannot access the almirah directly because we must enter the room first. In
collection frameword, sun microsystem has provided a nested interface Entry. Entry is the
subinterface of Map i.e. accessed by Map.Entry.
Internal code generated by the java compiler for nested interface Message
The java compiler internally creates public and static interface as displayed below:.
Let's see how can we define an interface inside the class and how can we access it.
1. class A{
2. interface Message{
3. void msg();
4. }
5. }
Yes, If we define a class inside the interface, java compiler creates a static nested class. Let's
see how can we define a class within the interface:
1. interface M{
2. class A{}
3. }
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 can be received in the java program and it can be used
as an input.
So, it provides a convenient way to check the behavior of the program for the different values.
You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.
1. class CommandLineExample{
2. public static void main(String args[]){
3. System.out.println("Your first argument is: "+args[0]);
4. }
5. }
1. compile by > javac CommandLineExample.java
2. run by > java CommandLineExample sonoo
1. class A{
2. public static void main(String args[]){
3.
4. for(int i=0;i<args.length;i++)
5. System.out.println(args[i]);
6.
7. }
8. }
1. compile by > javac A.java
2. run by > java A sonoo jaiswal 1 3 abc
Output: sonoo
jaiswal
1
3
abc
The varrags allows the method to accept zero or muliple arguments. Before varargs either we
use overloaded method or take an array as the method parameter but it was not considered good
because it leads to the maintenance problem. If we don't know how many argument we will
have to pass in the method, varargs is the better approach.
Advantage of Varargs:
Syntax of varargs:
The varargs uses ellipsis i.e. three dots after the data type. Syntax is as follows:
Recursion in java is a process in which a method calls itself continuously. A method in java
that calls itself is called recursive method.
Syntax:
1. returntype methodname(){
2. //code to be executed
3. methodname();//calling same method
4. }
Output:
hello
hello
...
java.lang.StackOverflowError
Output:
hello 1
hello 2
hello 3
hello 4
hello 5
Output:
factorial(5)
factorial(4)
factorial(3)
factorial(2)
factorial(1)
return 1
return 2*1 = 2
return 3*2 = 6
return 4*6 = 24
return 5*24 = 120
Output:
****************END OF UNIT-II(Part-2)***********************
INHERITENCE
Basics
Inheritance in Java
1. Inheritance
2. Types of Inheritance
3. Why multiple inheritance is not possible in java in case of class?
Inheritance is a mechanism in which one object acquires all the properties and behaviours of
parent object.
The idea behind inheritance is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you reuse (or inherit) methods and fields, and
you add new methods and fields to adapt your new class to new situations.
Syntax of Inheritance
As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
Relationship between two classes is Programmer IS-A Employee.It means that Programmer
is a type of Employee.
1. class Employee{
2. float salary=40000;
3. }
4.
5. class Programmer extends Employee{
6. int bonus=10000;
7.
8. public static void main(String args[]){
9. Programmer p=new Programmer();
10. System.out.println("Programmer salary is:"+p.salary);
11. System.out.println("Bonus of Programmer is:"+p.bonus);
12. }
13. }
In the above example,Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.
On the basis of class, there can be three types of inheritance: single, multilevel and hierarchical.
Multiple and Hybrid is supported through interface only. We will learn about interfaces later.
When a class extends multiple classes i.e. known as multiple inheritance. For Example:
● To reduce the complexity and simplify the language, multiple inheritance is not
supported in java. For example:
1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4.
5. class B{
6. void msg(){System.out.println("Welcome");}
7. }
8.
9. class C extends A,B{//suppose if it were
10.
11. Public Static void main(String args[]){
12. C obj=new C();
13. obj.msg();//Now which msg() method would be invoked?
14. }
15. }
Aggregation in Java
Consider a situation; Employee object contains much information such as id, name, emailId
etc. It contains one more object named address, which contains its own informations such as
city, state, country, zipcode etc. as given below.
1. class Employee{
2. int id;
3. String name;
4. Address address;//Address is a class
5. ...
6. }
In such case, Employee has an entity reference address, so relationship is Employee HAS-A
address.
In this example, we have created the reference of Operation class in the Circle class.
1. class Operation{
2. int square(int n){
3. return n*n;
4. }
5. }
6.
7. class Circle{
8. Operation op;//aggregation
9. double pi=3.14;
10.
11. double area(int radius){
12. op=new Operation();
13. int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).
14. return pi*rsquare;
15. }
16.
17.
18.
19. public static void main(String args[]){
20. Circle c=new Circle();
21. double result=c.area(5);
22. System.out.println(result);
23. }
24. }
Output:78.5
● Code reuse is also best achieved by aggregation when there is no is-a relationship.
● Inheritance should be used only if the relationship is-a is maintained throughout the
lifetime of the objects involved; otherwise, aggregation is the best choice.
In this example, Employee has an object of Address, address object contains its own
informations such as city, state, country etc. In such case relationship is Employee HAS-A
address.
Address.java
Emp.java
gzb UP india
112 arun
gno UP india
The super keyword in java is a reference variable which is used to refer immediate parent class
object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.
The super keyword in java is a reference variable which is used to refer immediate parent class
object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.
We can use super keyword to access the data member or field of parent class. It is used if parent
class and child class have same fields.
1. class Animal{
2. String color="white";
3. }
4. class Dog extends Animal{
5. String color="black";
6. void printColor(){
7. System.out.println(color);//prints color of Dog class
8. System.out.println(super.color);//prints color of Animal class
9. }
10. }
11. class TestSuper1{
12. public static void main(String args[]){
Output:
black
white
In the above example, Animal and Dog both classes have a common property color. If we print
color property, it will print the color of current class by default. To access the parent property,
we need to use super keyword.
The super keyword can also be used to invoke parent class method. It should be used if subclass
contains the same method as parent class. In other words, it is used if method is overridden.
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("eating bread...");}
6. void bark(){System.out.println("barking...");}
7. void work(){
8. super.eat();
9. bark();
10. }
11. }
12. class TestSuper2{
13. public static void main(String args[]){
14. Dog d=new Dog();
15. d.work();
16. }}
Output:
eating...
barking...
In the above example Animal and Dog both classes have eat() method if we call eat() method
from Dog class, it will call the eat() method of Dog class by default because priority is given
to local.
1. class Animal{
2. Animal(){System.out.println("animal is created");}
3. }
4. class Dog extends Animal{
5. Dog(){
6. super();
7. System.out.println("dog is created");
8. }
9. }
10. class TestSuper3{
11. public static void main(String args[]){
12. Dog d=new Dog();
13. }}
Output:
animal is created
dog is created
Another example of super keyword where super() is provided by the compiler implicitly.
1. class Animal{
2. Animal(){System.out.println("animal is created");}
3. }
Output:
animal is created
dog is created
Let's see the real use of super keyword. Here, Emp class inherits Person class so all the
properties of Person will be inherited to Emp by default. To initialize all the property, we are
using parent class constructor from child class. In such way, we are reusing the parent class
constructor.
1. class Person{
2. int id;
3. String name;
4. Person(int id,String name){
5. this.id=id;
6. this.name=name;
7. }
8. }
9. class Emp extends Person{
10. float salary;
11. Emp(int id,String name,float salary){
12. super(id,name);//reusing parent constructor
13. this.salary=salary;
14. }
15. void display(){System.out.println(id+" "+name+" "+salary);}
16. }
17. class TestSuper5{
18. public static void main(String[] args){
19. Emp e1=new Emp(1,"ankit",45000f);
20. e1.display();
21. }}
Output:
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.
Let's understand the problem that we may face in the program if we don't use method
overriding.
1. class Vehicle{
2. void run(){System.out.println("Vehicle is running");}
3. }
4. class Bike extends Vehicle{
5.
6. public static void main(String args[]){
7. Bike obj = new Bike();
8. obj.run();
9. }
10. }
Output:Vehicle is running
Problem is that I have to provide a specific implementation of run() method in subclass that is
why we use method overriding.
In this example, we have defined the run method in the subclass as defined in the parent class
but it has some specific implementation. The name and parameter of the method is same and
there is IS-A relationship between the classes, so there is method overriding.
1. class Vehicle{
2. void run(){System.out.println("Vehicle is running");}
3. }
4. class Bike2 extends Vehicle{
5. void run(){System.out.println("Bike is running safely");}
6.
7. public static void main(String args[]){
8. Bike2 obj = new Bike2();
9. obj.run();
10. }
Output:Bike is running safely
Consider a scenario, Bank is a class that provides functionality to get rate of interest. But, rate
of interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide
8%, 7% and 9% rate of interest.
No, static method cannot be overridden. It can be proved by runtime polymorphism, so we will
learn it later.
because static method is bound with class whereas instance method is bound with object. Static
belongs to class area and instance belongs to heap area.
There are many differences between method overloading and method overriding in java. A list
of differences between method overloading and method overriding are given below:
A class that is declared with abstract keyword, is known as abstract class in java. It can have
abstract and non-abstract methods (method with body).
Before learning java abstract class, let's understand the abstraction in java first.
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 for
example sending sms, you just type the text and send the message. You don't know the internal
processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
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.
A method that is declared as abstract and does not have implementation is known as abstract
method.
abstract void printStatus();//no body and abstract Example of abstract class that has
abstract method
In this example, Bike the abstract class that contains only one abstract method run. It
implementation is provided by the Honda class.
running safely..
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. We will learn about the
factory method later.
In this example, if you create the instance of Rectangle class, draw() method of Rectangle class
will be invoked.
File: TestAbstraction1.java
An abstract class can have data member, abstract method, method body, constructor and even
main() method.
File: TestAbstraction2.java
bike is created
running safely..
gear changed
Rule: If there is any abstract method in a class, that class must be abstract.
1. class Bike12{
2. abstract void run();
3. }
Rule: If you are extending any abstract class that have abstract method, you must either
provide the implementation of the method or make this class abstract.
The abstract class can also be used to provide some implementation of the interface. In such
case, the end user may not be forced to override all the methods of the interface.
Note: If you are beginner to java, learn interface first and skip this example.
1. interface A{
2. void a();
3. void b();
4. void c();
5. void d();
6. }
7.
8. abstract class B implements A{
9. public void c(){System.out.println("I am C");}
10. }
11.
12. class M extends B{
13. public void a(){System.out.println("I am a");}
14. public void b(){System.out.println("I am b");}
15. public void d(){System.out.println("I am d");}
Output:I am a
I am b
I am c
I am d
Abstract class and interface both are used to achieve abstraction where we can declare the
abstract methods. Abstract class and interface both can't be instantiated.
But there are many differences between abstract class and interface that are given below.
4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.
5) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.
Example:
6) Example:
public interface Drawable
public abstract class Shape{
{
Public abstract void draw();
void draw();
}
}
Using final
1. Final variable
2. Final method
3. Final class
4. Is final method inherited ?
5. Blank final variable
6. Static blank final variable
7. Final parameter
8. Can you declare a final constructor
The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:
1. variable
2. method
3. 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.
If you make any variable as final, you cannot change the value of final variable (It will be
constant).
1. class Bike9{
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){
7. Bike9 obj=new Bike9();
8. obj.run();
9. }
10. }//end of class
1. class Bike{
2. final void run(){System.out.println("running");}
3. }
4.
5. class Honda extends Bike{
6. void run(){System.out.println("running safely with 100kmph");}
7.
8. public static void main(String args[]){
9. Honda honda= new Honda();
10. honda.run();
11. }
12. }
Ans) Yes, final method is inherited but you cannot override it. For Example:
1. class Bike{
2. final void run(){System.out.println("running...");}
3. }
4. class Honda2 extends Bike{
5. public static void main(String args[]){
6. new Honda2().run();
7. }
8. }
Output:running...
A final variable that is not initialized at the time of declaration is known as blank final variable.
If you want to create a variable that is initialized at the time of creating object and once
initialized may not be changed, it is useful. For example PAN CARD number of an employee.
1. class Student{
2. int id;
3. String name;
4. final String PAN_CARD_NUMBER;
5. ...
6. }
1. class Bike10{
2. final int speedlimit;//blank final variable
3.
Output:70
A static final variable that is not initialized at the time of declaration is known as static blank
final variable. It can be initialized only in static block.
1. class A{
2. static final int data;//static blank final variable
3. static{ data=50;}
4. public static void main(String args[]){
5. System.out.println(A.data);
6. }
7. }
If you declare any parameter as final, you cannot change the value of it.
1. class Bike11{
2. int cube(final int n){
3. n=n+2;//can't be changed as n is final
4. n*n*n;
5. }
6. public static void main(String args[]){
7. Bike11 b=new Bike11();
8. b.cube(5);
9. }
10. }
The Object class is beneficial if you want to refer any object whose type you don't know. Notice
that parent class reference variable can refer the child class object, know as upcasting.
Let's take an example, there is getObject() method that returns an object but it can be of any
type like Employee,Student etc, we can use Object class reference to refer that object. For
example:
1. Object obj=getObject();//we don't know what object will be returned from this method
2. The Object class provides some common behaviors to all the objects such as object can
be compared, object can be cloned, object can be notified etc.
3.
Methods of Object class
The Object class provides many methods. They are as follows:
Method Description
public int hashCode() returns the hashcode number for this object.
public boolean equals(Object obj) compares the given object to this object.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
If you are not using any IDE, you need to follow the syntax given below:
For example
1. javac -d . Simple.java
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).
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.
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.
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2. package mypack;
3. import pack.A;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
Output:Hello
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.
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. class B{
4. public static void main(String args[]){
5. pack.A obj = new pack.A();//using fully qualified name
6. obj.msg();
7. }
8. }
Output:Hello
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.
Subpackage in java
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 definded 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.
Example of Subpackage
1. package com.javatpoint.core;
2. class Simple{
3. public static void main(String args[]){
4. System.out.println("Hello subpackage");
5. }
6. }
To Compile: javac -d . Simple.java
Output:Hello subpackage
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
To Compile:
To Run:
To run this program from e:\source directory, you need to set classpath of the directory where
the class file resides.
The -classpath switch can be used with javac and java tool.
Output:Welcome to package
o Temporary
o By setting the classpath in the command prompt
o By -classpath switch
o Permanent
o By setting the classpath in the environment variables
o By creating the jar file, that contains all the class files, and copying the jar file
in the jre/lib/ext folder.
Rule: There can be only one public class in a java source file and it must be saved by the
public class name.
1. //save as A.java
2.
3. package javatpoint;
4. public class A{}
1. //save as B.java
2.
3. package javatpoint;
4. public class B{}
Interface in Java
An interface in java is a blueprint of a class. It has static constants and abstract methods.
The interface in java is a mechanism to achieve abstraction. There can be only abstract
methods in the java interface not method body. It is used to achieve abstraction and multiple
inheritance in Java.
There are mainly three reasons to use interface. They are given below.
Since Java 8, interface can have default and static methods which is discussed later.
The java compiler adds public and abstract keywords before the interface method. More,
it adds public, static and final keywords before data members.
In other words, Interface fields are public, static and final by default, and methods are public
and abstract.
In this example, Printable interface has only one method, its implementation is provided in the
A class.
1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11. }
Output:
Hello
In this example, Drawable interface has only one method. Its implementation is provided by
Rectangle and Circle classes. In real scenario, interface is defined by someone but
implementation is provided by different implementation providers. And, it is used by someone
else. The implementation part is hidden by the user which uses the interface.
File: TestInterface1.java
Output:
drawing circle
Let's see another example of java interface which provides the implementation of Bank
interface.
File: TestInterface2.java
1. interface Bank{
2. float rateOfInterest();
3. }
4. class SBI implements Bank{
5. public float rateOfInterest(){return 9.15f;}
6. }
7. class PNB implements Bank{
8. public float rateOfInterest(){return 9.7f;}
9. }
10. class TestInterface2{
11. public static void main(String[] args){
12. Bank b=new SBI();
13. System.out.println("ROI: "+b.rateOfInterest());
14. }}
Output:
ROI: 9.15
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable,Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11. public static void main(String args[]){
12. A7 obj = new A7();
13. obj.print();
14. obj.show();
15. }
16. }
Output:Hello
Welcome
As we have explained in the inheritance chapter, multiple inheritance is not supported in case
of class because of ambiguity. But it is supported in case of interface because there is no
ambiguity as implementation is provided by the implementation class. For example:
1. interface Printable{
2. void print();
3. }
4. interface Showable{
Output:
Hello
As you can see in the above example, Printable and Showable interface have same methods
but its implementation is provided by class TestTnterface1, so there is no ambiguity.
Interface inheritance
1. interface Printable{
2. void print();
3. }
4. interface Showable extends Printable{
5. void show();
6. }
7. class TestInterface4 implements Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11. public static void main(String args[]){
12. TestInterface4 obj = new TestInterface4();
13. obj.print();
14. obj.show();
15. }
16. }
Output:
Hello
Welcome
File: TestInterfaceDefault.java
1. interface Drawable{
2. void draw();
3. default void msg(){System.out.println("default method");}
4. }
5. class Rectangle implements Drawable{
6. public void draw(){System.out.println("drawing rectangle");}
7. }
8. class TestInterfaceDefault{
9. public static void main(String args[]){
10. Drawable d=new Rectangle();
11. d.draw();
12. d.msg();
13. }}
Output:
drawing rectangle
default method
Since Java 8, we can have static method in interface. Let's see an example:
File: TestInterfaceStatic.java
1. interface Drawable{
2. void draw();
3. static int cube(int x){return x*x*x;}
4. }
5. class Rectangle implements Drawable{
6. public void draw(){System.out.println("drawing rectangle");}
7. }
8.
9. class TestInterfaceStatic{
10. public static void main(String args[]){
11. Drawable d=new Rectangle();
12. d.draw();
13. System.out.println(Drawable.cube(3));
14. }}
Output:
drawing rectangle
27
An interface that have no member is known as marker or tagged interface. For example:
Serializable, Cloneable, Remote etc. They are used to provide some essential information to
the JVM so that JVM may perform some useful operation.
Note: An interface can have another interface i.e. known as nested interface. We will learn it
in detail in the nested classes chapter. For example:
1. interface printable{
2. void print();
3. interface MessagePrintable{
4. void msg();
5. }
6. }
The exception handling is one of the powerful mechanism provided in java. It provides the
mechanism to handle the runtime errors so that normal flow of the application can be
maintained.
In this page, we will know about exception, its type and the difference between checked and
unchecked exceptions.
Exception
Exception Handling
The core advantage of exception handling is that normal flow of the application is maintained.
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;
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 exception will be executed. That is why we use exception handling.
Do You Know ?
● What is the difference between checked and unchecked exceptions ?
● What happens behind the code int data=50/0; ?
● Why use multiple catch block ?
● Is there any possibility when finally block is not executed?
● What is exception propagation ?
● What is the difference between throw and throws keyword ?
● What are the 4 rules for using exception handling with method overriding ?
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
2. Unchecked Exception
3. Error
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.
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
There are given some scenarios where unchecked exceptions can occur. They are as follows:
1. int a=50/0;//ArithmeticException
If we have null value in any variable, performing any operation by the variable occurs an
NullPointerException.
1. String s=null;
2. 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.
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:
try block
Enclose the code that might throw an exception in try block. It must be used within the method
and must be followed by either catch or finally block.
1. try{
2. ...
3. }catch(Exception_class_Name reference){}
1. try{
2. ...
3. }finally{}
catch block
Catch block is used to handle the Exception. It must be used after the try block.
1. class Simple{
2. public static void main(String args[]){
3. int data=50/0;
4.
5. System.out.println("rest of the code...");
6. }
7. }
But if exception is handled by the application programmer, normal flow of the application is
maintained i.e. rest of the code is executed.
1. class Simple{
2. public static void main(String args[]){
3. try{
4. int data=50/0;
5.
6. }catch(ArithmeticException e){System.out.println(e);}
7.
8. System.out.println("rest of the code...");
9. }
10. }
If you have to perform different tasks at the occurrence of different Exceptions, use multiple
catch block.
Output:task1 completed
rest of the code...
Rule:At a time only one Exception is occured 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 .
1. class Excep4{
2. public static void main(String args[]){
3. try{
4. int a[]=new int[5];
5. a[5]=30/0;
6. }
7. catch(Exception e){System.out.println("common task completed");}
8. catch(ArithmeticException e){System.out.println("task1 is completed");}
9. catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed"
);}
10. System.out.println("rest of the code...");
11. }
12. }
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:
1. ....
2. try
3. {
4. statement 1;
5. statement 2;
6. try
7. {
8. statement 1;
9. statement 2;
10. }
11. catch(Exception e)
12. {
Example:
Finally block
The finally block is a block that is always executed. It is mainly used to perform some important
tasks such as closing connection, stream etc.
case 1
Program in case exception does not occur
1. class Simple{
2. public static void main(String args[]){
3. try{
4. int data=25/5;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8.
9. finally{System.out.println("finally block is always executed");}
10.
11. System.out.println("rest of the code...");
12. }
13. }
Output:5
finally block is always executed
rest of the code...
case 2
Program in case exception occured but not handled
case 3
Program in case exception occured and handled
1. class Simple{
2. public static void main(String args[]){
3. try{
4. int data=25/0;
5. System.out.println(data);
6. }
7. catch(ArithmeticException e){System.out.println(e);}
8.
9. finally{System.out.println("finally block is always executed");}
10.
11. System.out.println("rest of the code...");
12. }
13. }
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).
throw keyword
1. class Excep13{
2.
3. static void validate(int age){
4. if(age<18)
5. throw new ArithmeticException("not valid");
6. else
7. System.out.println("welcome to vote");
8. }
9.
10. public static void main(String args[]){
11. validate(13);
12. System.out.println("rest of the code...");
13. }
14. }
Exception propagation:
An exception is first thrown from the top of the stack and if it is not caught, it drops down the
call stack to the previous method,If not caught there, the exception again drops down to the
previous method, and so on until they are caught or until they reach the very bottom of the call
stack.This is called exception propagation.
1. class Simple{
2. void m(){
3. int data=50/0;
4. }
5. void n(){
6. m();
7. }
8. void p(){
9. try{
10. n();
11. }catch(Exception e){System.out.println("exception handled");}
12. }
13. public static void main(String args[]){
14. Simple obj=new Simple();
15. obj.p();
16. System.out.println("normal flow...");
17. }
18. }
In the above example exception occurs in m() method where it is not handled,so it is propagated
to previous n() method where it is not handled, again it is propagated to p() method where
exception is handled.
Exception can be handled in any method in call stack either in main() method,p() method,n()
method or m() method.
Rule: By default, Checked Exceptions are not forwarded in calling chain (propagated).
Program which describes that checked exceptions are not propagated
1. class Simple{
2. void m(){
3. throw new java.io.IOException("device error");//checked exception
4. }
5. void n(){
6. m();
7. }
8. void p(){
9. try{
10. n();
11. }catch(Exception e){System.out.println("exception handeled");}
12. }
13. public static void main(String args[]){
14. Simple obj=new Simple();
15. obj.p();
16. System.out.println("normal flow");
17. }
18. }
The throws keyword is used to declare an exception. It gives 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.
Program which describes that checked exceptions can be propagated by throws keyword.
1. import java.io.IOException;
2. class Simple{
3. void m()throws IOException{
4. throw new IOException("device error");//checked exception
5. }
6. void n()throws IOException{
7. m();
8. }
9. void p(){
10. try{
11. n();
12. }catch(Exception e){System.out.println("exception handled");}
13. }
14. public static void main(String args[]){
15. Simple obj=new Simple();
16. obj.p();
Output:exception handled
normal flow...
Rule: If you are calling a method that declares an exception, you must either caught or
declare the exception.
1. Case1:You caught the exception i.e. handle the exception using try/catch.
2. Case2:You declare the exception i.e. specifying throws with the method.
● In case you handle the exception, the code will be executed fine whether exception
occurs during the program or not.
1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7.
8.
9. class Test{
10. public static void main(String args[]){
11. try{
12. Test t=new Test();
13. t.method();
14. }catch(Exception e){System.out.println("exception handled");}
15.
16. System.out.println("normal flow...");
17. }
18. }
Output:exception handled
normal flow...
● A)In case you declare the exception, if exception does not occur, the code will be
executed fine.
● B)In case you declare the exception if exception occures, an exception will be thrown
at runtime because throws does not handle the exception.
1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. System.out.println("device operation performed");
5. }
6. }
7.
8.
9. class Test{
10. public static void main(String args[])throws IOException{//declare exception
11. Test t=new Test();
12. t.method();
13.
14. System.out.println("normal flow...");
15. }
16. }
1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7.
8.
9. class Test{
10. public static void main(String args[])throws IOException{//declare exception
11. Test t=new Test();
12. t.method();
13.
14. System.out.println("normal flow...");
15. }
16. }
Output:Runtime Exception
1) Rule: If the superclass method does not declare an exception, subclass overridden method
cannot declare the checked exception.
1. import java.io.*;
2. class Parent{
3. void msg(){System.out.println("parent");}
4. }
5.
6. class Child extends Parent{
7. void msg()throws IOException{
8. System.out.println("child");
9. }
10. public static void main(String args[]){
11. Parent p=new Child();
12. p.msg();
13. }
14. }
1. import java.io.*;
2. class Parent{
3. void msg(){System.out.println("parent");}
4. }
5.
6. class Child extends Parent{
7. void msg()throws ArithmeticException{
8. System.out.println("child");
9. }
10. public static void main(String args[]){
11. Parent p=new Child();
12. p.msg();
13. }
14. }
Output:child
1) Rule: If the superclass method declares an exception, subclass overridden method can
declare same, subclass exception or no exception but cannot declare parent exception.
1. import java.io.*;
2. class Parent{
3. void msg()throws ArithmeticException{System.out.println("parent");}
4. }
5. class Child extends Parent{
6. void msg()throws Exception{System.out.println("child");}
7. public static void main(String args[]){
8. Parent p=new Child();
9. try{
10. p.msg();
11. }catch(Exception e){}
12. }
13. }
1. import java.io.*;
2. class Parent{
3. void msg()throws Exception{System.out.println("parent");}
Output:child
1. import java.io.*;
2. class Parent{
3. void msg()throws Exception{System.out.println("parent");}
4. }
5.
6. class Child extends Parent{
7. void msg()throws ArithmeticException{System.out.println("child");}
8.
9. public static void main(String args[]){
10. Parent p=new Child();
11. try{
12. p.msg();
13. }catch(Exception e){}
14. }
15. }
Output:child
1. import java.io.*;
2. class Parent{
3. void msg()throws Exception{System.out.println("parent");}
4. }
5.
6. class Child extends Parent{
7. void msg(){System.out.println("child");}
8.
9. public static void main(String args[]){
10. Parent p=new Child();
11. try{
12. p.msg();
13. }catch(Exception e){}
Output:child
Custom Exception
If you are creating your own Exception that is known as custom exception or user-defined
exception.
1. class Excep13{
2.
3. static void validate(int age)throws InvalidAgeException{
4. if(age<18)
5. throw new InvalidAgeException("not valid");
6. else
7. System.out.println("welcome to vote");
8. }
9. public static void main(String args[]){
10. try{
11. validate(13);
12. }catch(Exception m){System.out.println("Exception occured: "+m);}
13. System.out.println("rest of the code...");
14. }
15. }
*****************END OF UNIT-3******************
UNIT IV:
Multithreaded Programming:
The java Thread Model, The main thread , Creating Thread, Creating Multiple Threads, Using
isAlive() and join(), Thread Priorities, Synchronization, Interthread Communication,
Suspending, resuming and stopping threads, Obtaining a thread state, Using Multithreading.
I/O basics, Reading Console input, Writing console Output, The PrintWriter class, Reading and
writing files, Automatically closing a file, Applet fundamentals, enumerations type wrappers
auto boxing annotations, Generics: The general form of a generics class, creating a generic
method, generics interfaces.
Multithreading in Java
1. Multithreading
2. Multitasking
3. Process-based multitasking
4. Thread-based multitasking
5. What is Thread
But we use multithreading than multiprocessing because threads share a common memory area.
They don't allocate separate memory area so saves memory, and context-switching between
the threads takes less time than process.
1) It doesn't block the user because threads are independent and you can perform multiple
operations at same 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.
Threads are independent, if there occurs exception in one thread, it doesn't affect other threads.
It shares a common memory area.
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.
● Multithreading
● Life Cycle of a Thread
● Two ways to create a Thread
● How to perform multiple tasks by multiple threads
● Thread Schedular
● Sleeping a thread
● Can we start a thread twice ?
● What happens if we call the run() method instead of start() method ?
● Joining a thread
● Naming a thread
● Priority of a thread
● Daemon Thread
● ShutdownHook
● Garbage collection
● Synchronization with synchronized method
● Synchronized block
● Static synchronization
● Deadlock
● Inter-thread communication
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
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
1) New
The thread is in new state if you create an instance of Thread class but before the invocation of
start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has
not selected it to be the running thread.
3) Running
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
Thread class:
Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.
● Thread()
● Thread(String name)
● Thread(Runnable r)
● Thread(Runnable r,String name)
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().
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following
tasks:
Thread class constructor allocates a new thread object.When you create object of Multi
class,your class constructor is invoked(provided by Compiler) fromwhere Thread class
constructor is invoked(by super() as first statement).So your Multi class object is thread object
now.
Output:thread is running...
If you are not extending the Thread class,your class object would not be treated as a thread
object.So you need to explicitely create Thread class object.We are passing the object of your
class that implements Runnable so that your class run() method may execute.
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.
The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the
threads.Difference between preemptive scheduling and time slicing
Under preemptive scheduling, the highest priority task executes until it enters the waiting or
dead states or a higher priority task comes into existence. Under time slicing, a task executes
for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then
determines which task should execute next, based on priority and other factors.
The sleep() method of Thread class is used to sleep a thread for the specified amount of time.
1
1
2
2
3
3
4
4
As you know well that at a time only one thread is executed. If you sleep a thread for the
specified time,the thread shedular picks up another thread and so on.
No. After starting a thread, it can never be started again. If you does so, an
IllegalThreadStateException is thrown. In such case, thread will run once but for second time,
it will throw exception.
running
Output:Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
running...
running
The currentThread() method returns a reference to the currently executing thread object.
Syntax:
Output:Thread-0
Thread-1
Naming a thread:
The Thread class provides methods to change and get the name of a thread.
Output:Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
running...
After changeling name of t1:Sonoo Jaiswal
running...
The currentThread() method returns a reference to the currently executing thread object.
Output:Thread-0
Thread-1
Output:task one
task one
task one
Output:task one
task one
If you have to perform multiple tasks by multiple threads,have multiple run() methods.For
example:
Output:task one
task two
1. class TestMultitasking4{
Output:task one
task two
1. class TestMultitasking5{
2. public static void main(String args[]){
3. Runnable r1=new Runnable(){
4. public void run(){
5. System.out.println("task one");
6. }
7. };
8.
9. Runnable r2=new Runnable(){
10. public void run(){
11. System.out.println("task two");
12. }
13. };
14.
15. Thread t1=new Thread(r1);
16. Thread t2=new Thread(r2);
17.
18. t1.start();
19. t2.start();
20. }
21. }
Output:task one
● wait()
● notify()
● notifyAll()
1) wait() method
Causes current thread to release the lock and wait until either another thread invokes the
notify() method or the notifyAll() method for this object, or a specified amount of time has
elapsed.
The current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.
Method Description
Public final void wait(long timeout)throws waits for the specified amount of
InterruptedException time.
2) notify() method
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on
this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the
discretion of the implementation. Syntax:
3) notifyAll() method
Why wait(), notify() and notifyAll() methods are defined in Object class not Thread class?
Let's see the important differences between wait and sleep methods.
wait() sleep()
should be notified by notify() or notifyAll() after the specified amount of time, sleep is
methods completed.
1. class Customer{
2. int amount=10000;
3.
4. synchronized void withdraw(int amount){
5. System.out.println("going to withdraw...");
6.
7. if(this.amount<amount){
8. System.out.println("Less balance; waiting for deposit...");
9. try{wait();}catch(Exception e){}
10. }
11. this.amount-=amount;
12. System.out.println("withdraw completed...");
13. }
14.
15. synchronized void deposit(int amount){
16. System.out.println("going to deposit...");
17. this.amount+=amount;
18. System.out.println("deposit completed... ");
19. notify();
20. }
21. }
22.
23. class Test{
24. public static void main(String args[]){
25. final Customer c=new Customer();
26. new Thread(){
27. public void run(){c.withdraw(15000);}
28. }.start();
29. new Thread(){
30. public void run(){c.deposit(10000);}
31. }.start();
32.
33. }}
going to deposit...
deposit completed...
withdraw completed
APPLETS
Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.
Advantage of Applet
Drawback of Applet
Do You Know ?
● Who is responsible to manage the life cycle of an applet ?
● How to perform animation in applet ?
● How to paint like paint brush in applet ?
● How to display digital clock in applet ?
● How to display analog clock in applet ?
● How to communicate two applets ?
Applets can be embedded in HTML pages and downloaded over the Internet whereas
Applications have no special support in HTML for embedding or downloading.
⮚ Applets can only be executed inside a java compatible container, such as a browser or
appletviewer whereas
⮚ Applications are executed at command line by java.exe or jview.exe.
⮚ Applets execute under strict security limitations that disallow certain operations
(sandbox model security) whereas
⮚ Applications have no inherent security restrictions.
⮚ Applets don’t have the main() method as in applications. Instead they operate on
anentirely different mechanism where they are initialized by init(),started by
start(),stopped by stop() or destroyed by destroy().
⮚ Whereas Application has Main() method
<APPLET
[CODEBASE=codebaseurl]
CODE=appletFile
[ALT=alternate text]
[NAME=appletInstanceName]
WIDTH=pixels HEIGHT=pixels
[ALIGN=alignment]
[VAPCE=pixels][HSPACE=pixels] >
[<PARAM NAME=AttritubuteName VALUE=AttributeValue>]
The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life
cycle methods for an applet.
java.applet.Applet class:
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle
methods of applet.
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.
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.
1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
Note: class must be public because its object is created by Java Plugin software that
resides on the browser.
myapplet.html
1. <html>
2. <body>
3. <applet code="First.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
To run:
C:\appletviewer myapplet.html
Applet Skeleton:
Import java.awt.*;
Import java.applet.*;
</applet>*/
//Called First
// Initialization
//suspends execution
1. public abstract void drawString(String str, int x, int y): is used to draw the specified
string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the
specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle
with the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to draw
oval with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval
with the default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line
between the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer): is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used to fill a circular or elliptical arc.
10. public abstract void setColor(Color c): is used to set the graphics current color to the
specified color.
11. public abstract void setFont(Font font): is used to set the graphics current font to the
specified font.
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.
1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5. public void paint(Graphics g){
6. g.drawString("welcome to applet",150,150);
7. }
8. }
9. /*
10. <applet code="First.class" width="300" height="300">
11. </applet>
12. */
c:\>javac First.java
c:\>appletviewer First.java
1. import java.applet.Applet;
2. import java.awt.*;
3. public class GraphicsDemo extends Applet{
4. public void paint(Graphics g){
5. g.setColor(Color.red);
6. g.drawString("Welcome",50, 50);
7. g.drawLine(20,30,20,300);
8. g.drawRect(70,100,30,30);
9. g.fillRect(170,100,30,30);
10. g.drawOval(70,200,30,30);
11. g.setColor(Color.pink);
12. g.fillOval(170,200,30,30);
13. g.drawArc(90,150,30,30,30,270);
14. g.fillArc(270,150,30,30,0,180);
15. }
16. }
myapplet.html
1. <html>
2. <body>
3. <applet code="GraphicsDemo.class" width="300" height="300">
4. </applet>
5. </body>
Applet is mostly used in games and animation. For this purpose image is required to be
displayed. The java.awt.Graphics class provide a method drawImage() to display the image.
The java.applet.Applet class provides getImage() method that returns the object of Image.
Syntax:
1. public URL getDocumentBase(): is used to return the URL of the document in which
applet is embedded.
2. public URL getCodeBase(): is used to return the base URL.
1. import java.awt.*;
2. import java.applet.*;
3.
4.
5. public class DisplayImage extends Applet {
6.
7. Image picture;
8.
9. public void init() {
10. picture = getImage(getDocumentBase(),"sonoo.jpg");
11. }
12.
13. public void paint(Graphics g) {
14. g.drawImage(picture, 30,30, this);
15. }
16.
17. }
myapplet.html
1. <html>
2. <body>
3. <applet code="DisplayImage.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
******************END OF UNIT-4****************
AWT Controls
● UI elements : Thes are the core visual elements the user eventually sees and interacts
with. GWT provides a huge list of widely used and common elements varying from
basic to complex which we will cover in this tutorial.
● Layouts: They define how UI elements should be organized on the screen and provide
a final look and feel to the GUI (Graphical User Interface). This part will be covered in
Layout chapter.
● Behavior: These are events which occur when the user interacts with UI elements. This
part will be covered in Event Handling chapter.
Introduction
The class Component is the abstract base class for the non menu user-interface controls of
AWT. Component represents an object with graphical representation.
Class declaration
Field
Class constructors
AWT Components:
1. Label
2. Button
3. CheckBox
4. CheckBoxGroup
5. List
6. TextField
7. TextArea
8. Choice
Label is a passive control because it does not create any event when accessed by the user. The
label control is an object of Label. A label displays a single line of read-only text. However the
text can be changed by the application programmer but cannot be changed by the end user in
any way.
Class declaration
Field
Class constructors
Class methods
import java.awt.*;
import java.applet.*;
public class LabelDemo extends Frame
{
LabelDemo()
{
Label one=new Label("one");
//one.setText("one");
Label two=new Label("two");
//two.setText("two");
add(one);
add(two);
setSize(300,300);
//setLayout(new FlowLayout());
setVisible(true);
}
public static void main(String []args)
{
LabelDemo l=new LabelDemo();
}
}
Introduction
Button is a control component that has a label and generates an event when pressed. When a
button is pressed and released, AWT sends an instance of ActionEvent to the button, by calling
processEvent on the button. The button's processEvent method receives all events for the
button; it passes an action event along by calling its own processActionEvent method. The
latter method passes the action event on to any action listeners that have registered an interest
in action events generated by this button.
If an application wants to perform some action based on a button being pressed and released,
it should implement ActionListener and register the new listener to receive events from this
button, by calling the button's addActionListener method. The application can make use of the
button's action command as a messaging protocol.
Class declaration
Class methods
import java.awt.*;
import java.applet.*;
public class ButtonDemo extends Frame
{
ButtonDemo()
{
Introduction
Checkbox control is used to turn an option on(true) or off(false). There is label for each
checkbox representing what the checkbox does.The state of a checkbox can be changed by
clicking on it.
Class declaration
Class constructors
import java.awt.*;
import java.applet.*;
public class CheckBoxDemo extends Frame
{
CheckBoxDemo()
{
Checkbox c1=new Checkbox("apple");
Introduction
Class declaration
Class constructors
Class methods
Introduction
The List represents a list of text items. The list can be configured to that user can choose either
one item or multiple items.
Class declaration
Class constructors
Class methods
import java.awt.*;
import java.applet.*;
public class ListDemo extends Frame
{
ListDemo()
{
List os=new List(4,true);
List browser=new List(4,false);
os.add("windows Xp");
os.add("Windows Vista");
os.add("Solaries");
os.add("Mac Os");
browser.add("InternetExplorer");
browser.add("FireFox");
browser.add("opera");
add(os);
add(browser);
setSize(300,300);
// setLayout(null);
setLayout(new FlowLayout());
setVisible(true);
}
public static void main(String []args)
{
Introduction
The textField component allows the user to edit single line of text.When the user types a key
in the text field the event is sent to the TextField. The key event may be key pressed, Key
released or key typed. The key event is passed to the registered KeyListener. It is also possible
to for an ActionEvent if the ActionEvent is enabled on the textfield then ActionEvent may be
fired by pressing the return key.
Class declaration
Class constructors
Class methods
import java.awt.*;
public class TextFieldDemo extends Frame
{
TextFieldDemo()
{
Label namep=new Label("Name",Label.RIGHT);
add(pass);
setSize(300,300);
setLayout(new FlowLayout());
setVisible(true);
}
public static void main(String []args)
{
TextFieldDemo tf=new TextFieldDemo();
}
}
Introduction
The TextArea control in AWT provide us multiline editor area. The user can type here as much
as he wants. When the text in the text area become larger than the viewable area the scroll bar
is automatically appears which help us to scroll the text up & down and right & left.
Class declaration
Field
● static int SCROLLBARS_BOTH -- Create and display both vertical and horizontal
scrollbars.
● static int SCROLLBARS_HORIZONTAL_ONLY -- Create and display horizontal
scrollbar only.
● static int SCROLLBARS_NONE -- Do not create or display any scrollbars for the
text area.
● static int SCROLLBARS_VERTICAL_ONLY -- Create and display vertical
scrollbar only.
Class constructors
Class methods
import java.awt.*;
public class TextAreaDemo extends Frame
{
TextAreaDemo()
{
String str="I'm Y.Narasimha Reddy Asst.Prof,CVRCE";
TextArea text=new TextArea(str,10,20);
add(text);
setSize(300,300);
setLayout(new FlowLayout());
setVisible(true);
}
public static void main(String []args)
{
TextAreaDemo tf=new TextAreaDemo();
}
}
Introduction
Choice control is used to show pop up menu of choices. Selected choice is shown on the top of
the menu.
Class declaration
Class constructors
Class methods
import java.awt.*;
import java.applet.*;
public class ChoiceDemo extends Frame
{
ChoiceDemo()
{
Choice os=new Choice();
Choice browser=new Choice();
os.add("windows Xp");
os.add("Windows Vista");
os.add("Solaries");
os.add("Mac Os");
browser.add("InternetExplorer");
browser.add("FireFox");
browser.add("opera");
add(os);
add(browser);
setSize(300,300);
// setLayout(null);
setLayout(new FlowLayout());
setVisible(true);
}
public static void main(String []args)
{
ChoiceDemo b=new ChoiceDemo();
}
}
LayoutManagers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.
BorderLayout:
The BorderLayout is used to arrange the components in five regions: north, south, east, west
and center. Each region (area) may contain one component only. It is the default layout of
frame or window. The BorderLayout provides five constants for each region:
● BorderLayout(): creates a border layout but with no gaps between the components.
● JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal
and vertical gaps between the components.
import java.awt.*;
import javax.swing.*;
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}
GridLayout
The GridLayout is used to arrange the components in rectangular grid. One component is
displayed in each rectangle.
1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the
given rows and columns alongwith given horizontal and vertical gaps.
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class MyGridLayout{
5. Frame f;
6. MyGridLayout(){
7. f=new Frame();
8.
9. Button b1=new Button("1");
10. Button b2=new Button("2");
11. Button b3=new Button("3");
12. Button b4=new Button("4");
13. Button b5=new Button("5");
14. Button b6=new Button("6");
15. Button b7=new Button("7");
16. Button b8=new Button("8");
17. Button b9=new Button("9");
18.
19. f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
20. f.add(b6);f.add(b7);f.add(b8);f.add(b9);
FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is
the default layout of applet or panel.
1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5
unit horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given
alignment and the given horizontal and vertical gap.
import java.awt.*;
import javax.swing.*;
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyFlowLayout();
}
}
CardLayout class
The CardLayout class manages the components in such a manner that only one component is
visible at a time. It treats each component as a card that is why it is known as CardLayout.
1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and
vertical gap.
● public void next(Container parent): is used to flip to the next card of the given container.
● public void previous(Container parent): is used to flip to the previous card of the given
container.
● public void first(Container parent): is used to flip to the first card of the given container.
● public void last(Container parent): is used to flip to the last card of the given container.
● public void show(Container parent, String name): is used to flip to the specified card
with the given name.
1. import java.awt.*;
2. import java.awt.event.*;
3.
4. import javax.swing.*;
5.
6. public class CardLayoutExample extends JFrame implements ActionListener{
7. CardLayout card;
8. JButton b1,b2,b3;
9. Container c;
10. CardLayoutExample(){
11. c=getContentPane();
Menu Controls
Sr. Control & Description
No.
1 MenuComponent
It is the top level class for all menu related controls.
2 MenuBar
The MenuBar object is associated with the top-level window.
3 MenuItem
The items in the menu must belong to the MenuItem or any of its subclass.
4 Menu
The Menu object is a pull-down menu component which is displayed from the
menu bar.
5 CheckboxMenuItem
CheckboxMenuItem is subclass of MenuItem.
6 PopupMenu
PopupMenu can be dynamically popped up at a specified position within a
component.
The object of MenuItem class adds a simple labeled menu item on menu. The items used in a
menu must belong to the MenuItem or any of its subclass.
The object of Menu class is a pull down menu component which is displayed on the menu bar.
It inherits the MenuItem class.
1. import java.awt.*;
2. class MenuExample
3. {
4. MenuExample(){
5. Frame f= new Frame("Menu and MenuItem Example");
6. MenuBar mb=new MenuBar();
7. Menu menu=new Menu("Menu");
8. Menu submenu=new Menu("Sub Menu");
9. MenuItem i1=new MenuItem("Item 1");
10. MenuItem i2=new MenuItem("Item 2");
11. MenuItem i3=new MenuItem("Item 3");
12. MenuItem i4=new MenuItem("Item 4");
13. MenuItem i5=new MenuItem("Item 5");
14. menu.add(i1);
15. menu.add(i2);
16. menu.add(i3);
17. submenu.add(i4);
18. submenu.add(i5);
19. menu.add(submenu);
20. mb.add(menu);
21. f.setMenuBar(mb);
22. f.setSize(400,400);
23. f.setLayout(null);
24. f.setVisible(true);
25. }
26. public static void main(String args[])
27. {
Output:
Dialog Boxes
Java JOptionPane
The JOptionPane class is used to provide standard dialog boxes such as message dialog box,
confirm dialog box and input dialog box. These dialog boxes are used to display information
or get input from the user. The JOptionPane class inherits JComponent class.
Constructor Description
Methods Description
void setInputValue(Object newValue) It is used to set the input value that was
selected or input by the user.
1. import javax.swing.*;
2. public class OptionPaneExample {
3. JFrame f;
4. OptionPaneExample(){
5. f=new JFrame();
6. JOptionPane.showMessageDialog(f,"Hello, Welcome to Javatpoint.");
7. }
8. public static void main(String[] args) {
9. new OptionPaneExample();
10. }
11. }
1. import javax.swing.*;
2. public class OptionPaneExample {
3. JFrame f;
4. OptionPaneExample(){
5. f=new JFrame();
6. JOptionPane.showMessageDialog(f,"Successfully Updated.","Alert",JOptionPane.WARNI
NG_MESSAGE);
7. }
8. public static void main(String[] args) {
9. new OptionPaneExample();
10. }
11. }
Output:
1. import javax.swing.*;
2. public class OptionPaneExample {
3. JFrame f;
4. OptionPaneExample(){
5. f=new JFrame();
6. String name=JOptionPane.showInputDialog(f,"Enter Name");
7. }
Output:
1. import javax.swing.*;
2. import java.awt.event.*;
3. public class OptionPaneExample extends WindowAdapter{
4. JFrame f;
5. OptionPaneExample(){
6. f=new JFrame();
7. f.addWindowListener(this);
8. f.setSize(300, 300);
9. f.setLayout(null);
10. f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
11. f.setVisible(true);
12. }
13. public void windowClosing(WindowEvent e) {
14. int a=JOptionPane.showConfirmDialog(f,"Are you sure?");
15. if(a==JOptionPane.YES_OPTION){
16. f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
17. }
18. }
19. public static void main(String[] args) {
20. new OptionPaneExample();
21. }
22. }
Output:
REFENCE BOOKS:
1. “Programming with Java” T.V.Suresh Kumar, B.Eswara Reddy, P.Raghavan Pearson Edition.
2. “Java Fundamentals - A Comprehensive Introduction”, Herbert Schildt and Dale Skrien,
Special Indian Edition, McGrawHill, 2013.
3. “Java – How to Program”, Paul Deitel, Harvey Deitel, PHI.
4. “Core Java”, NageswarRao, Wiley Publishers
UNIT-1
UNIT-2
UNIT-4
1. Define a thread? Explain how many ways to create a thread with example?
2. Explain how to create multithreads with example?
3. Explain the life cycle of threads and how to assign thread priorities to threads?
4. Explain about thread communication process with example?
5. Define an applet? Write the skeleton of and applet with an example?
6. Explain about status window in applet with example?
7. Explain how to pass parameters to applets?
8. Explain about networking classes and interfaces?
9. Explain about URI class and cookies with example?
UNIT-5
1. Explain about swing components and containers with example?
2. Explain about layout manages in java with example?
3. Explain about jbutton, jtextfield and jlable components with example?
4. Explain about how to create main menu using jmenubar, jmenu and jmenuitems?
5. Explain about a)showmessagedialog b)showconfirmdialog c)showinputdialog
d)showoptiondialog?
ASSIGNMENT QUESTIONS
UNIT-II
UNIT-III
UNIT-IV
1. What are the methods supported by the following interfaces. Explain each of them
(a) ActionListener interface
(b) MouseMotionListener interface
(c) TextListener interface
2. What is the functionality supported by java related to Fonts.
UNIT-V
Code: 15A05403
B.Tech II Year II Semester (R15) Regular Examinations May/June 2017
OBJECT ORIENTED PROGRAMMING USING JAVA
(Common to CSE & IT)
Time: 3 hours Max. Marks: 70
PART - A
(Compulsory Question)
*****
1 Answer the following: (10 X 02 = 20 Marks)
(a) Explain about commands javac, java.
(b) List any four predefined packages in java.
(c) What is multitasking?
(d) Define an event in java.
(e) Demonstrate the use of “?” operator.
(f) Differences between the object oriented program and procedural oriented programming.
(g) Explain about Bitwise operators in java.
(h) Explain the normal flow of a thread with neat diagram.
(i) List out event sources.
(j) Explain parameter passing methods in java.
PART - B
(Answer all five units, 5 X 10 = 50 Marks)
UNIT - I
2 (a) Explain briefly buzzwords of java.
(b) Explain any four object oriented programming features.
OR
3 (a) Explain about arrays in java with an example program.
(b) Write a java program to perform matrix multiplication.
UNIT - II
4 (a) Explain about StringTokenizer class in java with example.
(b) In how many ways a package can be imported. Explain with an example program.
OR
5 (a) What is a constructor? Explain constructor overloading with an example.
(b) What is a method? Explain method overloading with example.
UNIT - III
6 (a) Define a package. Write down the steps to create a package.
(b) Define an interface. Explain about implementing an interface with example.
OR
7 (a) What is an exception? Explain various exception types.
(b) Write a java program using all keywords of exception handling.
8 (a) Write a java program that creates a thread by extending the thread class.
(b) Explain about thread priorities in java with suitable example.
OR
9 (a) Explain about the ways to create an applet with example.
(b) How to pass parameters to an applet? Explain with an example.
PART - B
(Answer all five units, 5 X 10 = 50 Marks)
UNIT - I
2 (a) Explain object oriented programming.
(b) Explain control statements in java.
OR
3 (a) Explain iteration using multidimensional array in java.
(b) Write a java program for factorial of a given number n using recursion.
UNIT - II
4 (a) Write java program to add methods width, height and length for box class.
(b) Explain implementation of nested interfaces in java.
OR
5 (a) Write a java program subclass contain cube for super class contain width, height and
length for
inheritance.
(b) Explain multithreading in java.
UNIT - III
6 (a) Explain exceptional handling with an example program.
(b) Explain generic interfaces.
OR
UNIT - IV
8 (a) Explain creation of threads in Java with an example program.
(b) Write thread communication.
OR
9 (a) Explain parameter passing in applets with an example program.
(b) Explain handling mouse events.
UNIT - V
10 (a) Explain java swings different buttons with an example program.
(b) Explain network interfaces.
OR
11 (a) Write java program to create main menu and drawing rectangle.
(b) Explain event handling using swings.
*****
*****************GOOD LUCK********************