0% found this document useful (0 votes)
16 views

Java Material

Uploaded by

vasuraj9347
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Java Material

Uploaded by

vasuraj9347
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 236

Dept.

of Computer Science and Engineering

JAVA PROGRAMMING LECTURE NOTES

Prepared by:
Dr.Y.NARASIMHA REDDY
ASSOCIATE PROFESSOR
DEPT.OF CSE
SJCET

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY ANANTAPUR
B. Tech II - II sem (C.S.E) T Tu C
3 1 3
(15A05403) OBJECT ORIENTED PROGRAMMING USING THOUGH JAVA
Course Objectives:
● Study the syntax, semantics and features of Java Programming Language
● Learn the method of creating Multi-threaded programs and handle exceptions
● Learn Java features to create GUI applications & perform event handling
Course Outcomes:
Ability to solve problems using object oriented approach and implement them using Java
● Ability to write Efficient programs with multitasking ability and handle exceptions
● Create user friendly interface

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.

Data Types, Arrays and Variables:


Primitive Types, Integers, Floating-point Types, Characters, Booleans, literals, variables,
Type conversion and casting, Automatic Type Promotion in Expressions, Arrays, strings,
Pointers.
UNIT II:
Operators:
Arithmetic Operators, The Bitwise Operators, Relational Operators, Boolean Logic operators,
The assignment operator, The ? Operator, Operator Precedence, Using Parentheses.

Control Statements:
Java’s selection Statements, Iteration statements, Jump Statements.

The History and Evolution of Java:

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

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


lang.built on C and C++. It derives its syntax from C and its Object-Oriented features
are Influenced by C++. Java can be used to create two types of prgs. Those are Applications
and Applets.

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.

1) James Gosling, Mike Sheridan, and Patrick Naughton initiated


the Java language project in June 1991. The small team of sun engineers
called Green Team.

2) Originally designed for small, embedded systems in electronic


appliances like set-top boxes.

3) Firstly, it was called "Greentalk" by James Gosling and file


extension was .gt.

4) After that, it was called Oak and was developed as a part of the Green project

Why "Oak" name

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.

Why "Java" name

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.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


According to James Gosling "Java was one of the top choices along with Silk". Since java was
so unique, most of the team members preferred java.

8) Java is an island of Indonesia where first coffee was produced (called java coffee).

9) Notice that Java is just a name not an acronym.

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.

12) JDK 1.0 released in(January 23, 1996).

Java Version History


There are many java versions that has been released. Current stable release of Java is Java SE
8.

1. JDK Alpha and Beta (1995)


2. JDK 1.0 (23rd Jan, 1996)
3. JDK 1.1 (19th Feb, 1997)
4. J2SE 1.2 (8th Dec, 1998)
5. J2SE 1.3 (8th May, 2000)
6. J2SE 1.4 (6th Feb, 2002)
7. J2SE 5.0 (30th Sep, 2004)
8. Java SE 6 (11th Dec, 2006)
9. Java SE 7 (28th July, 2011)
10. Java SE 8 (18th March, 2014)

The byte code

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

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


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.

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:-

1) Standalone Application/Desktop Application


2) Web Application
3) Enterprise Application
4) Mobile Application

1) Standalone Application/Desktop Application:-


It is also known as desktop application or window-based application. An application
that we need to install on every machine such as media player, antivirus etc. AWT and
Swing are used in java for creating standalone applications.

2) Web Application:-
An application that runs on the server side and creates dynamic page, is called web
application. Currently, servlet, jsp, struts, jsf etc. technologies are used for creating web
applications in java.

3) Enterprise Application: -
An application that is distributed in nature, such as banking applications etc. 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.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Features of Java/Java Buzz Words:

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

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


● Multi Threading
● Distributed
● Networked
● Robust
● Dynamic
● Secured
● High Performance
● Interpreted
● Object Oriented

1. Simple

It is simple because of the following factors:

● 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

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


A program or technology is said to be platform independent if and only if which can run on all
available operating systems with respect to its development and compilation. (Platform
represents O.S).

3. Architectural Neutral

Architecture represents processor.

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.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


4. Portable

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

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Using this language we can create distributed applications. RMI and EJB are used for creating
distributed applications. In distributed application multiple client system depends on multiple
server systems so that even problem occurred in one server will never be reflected on any client
system.

Note: In this architecture same application is distributed in multiple server system

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

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


It is a more secure language compared to other language; In this language, all code is covered
in byte code after compilation which is not readable by human.

11. High performance

It has high performance because of following reasons;

● 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 is one of the highly interpreted programming languages.

13. Object Oriented

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.

Java OOPs Concepts:

Simula is considered as the first object-oriented programming language. The programming


paradigm where everything is represented as an object, is known as truly object-oriented
programming language.

Smalltalk is considered as the first truly object-oriented programming language.

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.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Class

Collection of objects is called class. It is a logical entity.

Inheritance

When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

Polymorphism

When one task is performed by different ways i.e. known


as polymorphism. For example: to convince the customer
differently, to draw something e.g. shape or rectangle etc.

In java, we use method overloading and method overriding to


achieve polymorphism.

Another example can be to speak something e.g. cat speaks


meaw, dog barks woof etc.

Abstraction

Hiding internal details and showing functionality is known as abstraction. For example:
phone call, we don't know the internal processing.

In java, we use abstract class and interface to achieve abstraction.

Encapsulation

Binding (or wrapping) code and data together into a single


unit is known as encapsulation. For example: capsule, it is
wrapped with different medicines.

A java class is the example of encapsulation. Java bean is the


fully encapsulated class because all the data members are private her e.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


JDK
JDK is an acronym for Java Development Kit.It physically exists. It contains JRE +
development tools.

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.

The JVM performs following main tasks:

● Loads code
● Verifies code
● Executes code
● Provides runtime environment

It is:

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


A specification where working of Java Virtual Machine is specified. But implementation
provider is independent to choose the algorithm. Its implementation has been provided by Sun
and other companies.
An implementation Its implementation is known as JRE (Java Runtime Environment).
Runtime Instance Whenever you write java command on the command prompt to run the java
class, and instance of JVM is created

Internal Architecture of JVM


Let's understand the internal architecture of JVM. It contains class loader, memory area,
execution engine etc.

1)ClassLoader
Class loader is a subsystem of JVM that is used to load class files.

2) Class (Method) Area:


Class (Method) Area stores per-class structures such as the runtime constant pool, field and
method data, the code for methods.

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.

5) Program Counter Register:


PC (program counter) registers. It contains the address of the Java virtual machine instruction
currently being executed.

6) Native Method Stack:

It contains all the native methods used in the application.

7) Execution Engine:
It contains:

1) A virtual processor

2) Interpreter: Read byte code stream then execute the instructions.

3) Just-In-Time(JIT) compiler: It is used to improve the performance.JIT compiles parts of


the byte code that have similar functionality at the same time, and hence reduces the amount
of time needed for compilation. Here the term? Compiler? refers to a translator from the
instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


SIMPLE PROGRAM

1. class Simple{
2. public static void main(String args[]){
3. System.out.println("Hello Java");
4. }
5. }

save this file as Simple.java

To compile: javac Simple.java

To execute: java Simple

Output:Hello Java

Let's see what is the meaning of class, public, static, void, main, String[], System.out.println()

● class keyword is used to declare a class in java.


● public keyword is an access modifier which represents visibility, it means it is visible
to all.
● static is a keyword, if we declare any method as static, it is known as static method.
The core advantage of static method is that there is no need to create object to invoke
the static method. The main method is executed by the JVM, so it doesn't require to
create object to invoke the main method. So it saves memory.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


● void is the return type of the method, it means it doesn't return any value.
● main represents startup of the program.
● String[] args is used for command line argument. We will learn it later.
● System.out.println() is used print statement. We will learn about the internal working
of System.out.println statement later.

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.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


To compile and run the above program, go to your current directory first; my current directory
is c:\new . Write here:

To compile: javac Simple.java

To execute: java Simple

There are 2 ways to set java path:

1. temporary
2. permanent

1) How to set Temporary Path of JDK in Windows

To set the temporary path of JDK, you need to follow following steps:

● Open command prompt


● copy the path of jdk/bin directory
● write in command prompt: set path=copied_path

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


For Example:
set path=C:\Program Files\Java\jdk1.6.0_23\bin

2) How to set Permanent Path of JDK in Windows

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

1. Internal Details of Hello Java

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.

What happens at compile time?


At compile time, java file is compiled by Java Compiler (It does not interact with OS) and
converts the java code into bytecode.

What happens at runtime?


At runtime, following steps are performed:

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Classloader: is the subsystem of JVM that is used to load class files.

Bytecode Verifier: checks the code fragments for illegal code that can violate access right to
objects.

Interpreter: read bytecode stream then execute the instructions.

Q)Can you save a java source file by other name than the class name?
Yes, like the figure given below illustrates:

To compile: javac Simple.java

To execute: java Simple

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Q) Can you have multiple classes in a java source file?
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

IDENTIFIERS & DATA TYPES:

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.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


int data=50;//Here data is variable

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.

We will have detailed learning of these variables in next chapters.

Example to understand the types of variables


class A{

int data=50;//instance variable

static int m=100;//static variable

void method(){
int n=90;//local variable
}

}//end of class

Data Types in Java


In java, there are two types of data types

● primitive data types

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


● non-primitive data types

Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

OPERATORS:

Java provides a rich set of operators to manipulate variables. We can divide all the Java
operators into the following groups:

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


● Arithmetic Operators
● Relational Operators
● Bitwise Operators
● Logical Operators
● Assignment Operators
● Misc Operators

1. The Arithmetic Operators:

Arithmetic operators are used in mathematical expressions in the same way that they are used
in algebra. The following table lists the arithmetic operators:

Assume integer variable A holds 10 and variable B holds 20, then:

Operator Description Example

+ Addition - Adds values on either side of the operator A + B will give 30

- 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

Modulus - Divides left hand operand by right hand operand and


% B % A will give 0
returns remainder

++ Increment - Increases the value of operand by 1 B++ gives 21

-- Decrement - Decreases the value of operand by 1 B-- gives 19

2. The Relational Operators:

There are following relational operators supported by Java language

Assume variable A holds 10 and variable B holds 20, then:

Operator Description Example

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 values of two operands are equal or not, if values


!= (A != B) is true.
are not equal then condition becomes true.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Checks if the value of left operand is greater than the value of
> (A > B) is not true.
right operand, if yes then condition becomes 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.

Checks if the value of left operand is less than or equal to the


<= (A <= B) is true.
value of right operand, if yes then condition becomes true.

3. The Bitwise Operators:

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&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a = 1100 0011

The following table lists the bitwise operators:

Assume integer variable A holds 60 and variable B holds 13 then:

Operator Description Example

(A & B) will give


Binary AND Operator copies a bit to the result if it exists in both
& 12 which is 0000
operands.
1100

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


(A | B) will give
| Binary OR Operator copies a bit if it exists in either operand. 61 which is 0011
1101

(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

(~A ) will give -61


which is 1100
Binary Ones Complement Operator is unary and has the effect of 0011 in 2's
~
'flipping' bits. complement form
due to a signed
binary number.

A << 2 will give


Binary Left Shift Operator. The left operands value is moved left
<< 240 which is 1111
by the number of bits specified by the right operand.
0000

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

4. The Logical Operators:

The following table lists the logical operators:

Assume Boolean variables A holds true and variable B holds false, then:

Operator Description Example

Called Logical AND operator. If both the operands are non-zero,


&& (A && B) is false.
then the condition becomes true.

Called Logical OR Operator. If any of the two operands are non-


|| (A || B) is true.
zero, then the condition becomes true.

Called Logical NOT Operator. Use to reverses the logical state of


! its operand. If a condition is true then Logical NOT operator will !(A && B) is true.
make false.

5. The Assignment Operators:

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


There are following assignment operators supported by Java language:

Operator Description Example

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

There are few other operators supported by Java Language.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Conditional Operator (? : ):

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:

variable x = (expression) ? value if true : value if false

Following is the example:

public class Test {

public static void main(String args[]){

int a , b;

a = 10;

b = (a == 1) ? 20: 30;

System.out.println( "Value of b is : " + b );

b = (a == 10) ? 20: 30;

System.out.println( "Value of b is : " + b );

This would produce the following result:

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:

(Object reference variable) instanceof (class/interface type)

PROGRAM CONTROL STATEMENTS

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.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


In Java, control statements can be divided into the following three categories:

● 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 and if-else statements


● The if-else statements
● The if-else-if statements
● The switch statements

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:

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


The if-else statements

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:

The if-else-if statements

This statement following the else keyword can be another if or if-else statement.

That would looks like this:

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.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


import java.util.Scanner;
public class IfElseIfDemo
{
public static void main( String[] args )
{
int age;
Scanner inputDevice = new Scanner( System.in );
System.out.print( "Please enter Age: " );
age = inputDevice.nextInt();
if ( age >= 18 && age <=35 )
System.out.println( "between 18-35 " );
else if(age >35 && age <=60)
System.out.println("between 36-60");
else
System.out.println( "not matched" );
}
}
Output:

The Switch Statements

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;
}

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


}
}
Output:

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.

Java provides the following loop for iteration statements:

● The while loop


● The for loop
● The do-while loop
● The for each loop

The while loop

It continually executes a statement (that is usually be a block) while a condition is true. The
condition must return a boolean value.

public class WhileDemo


{
public static void main( String[] args )
{
int i = 0;
while ( i < 5 )
{
System.out.println( "Value :: " + i );
i++;
}
}
}
Output:

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


The do-while loop

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.

public class DoWhileDemo


{
public static void main( String[] args )
{
int i = 0;
do
{
System.out.println( "value :: " + i );
i++;
}
while ( i < 5);
}
}
Output:

The for loop

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:

for(<initialization>;<condition>;<increment or decrement statement>){


<block of code>
}

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


The initialization block executes first before the loop starts. It is used to initialize the loop
variable.
The condition statement evaluates every time prior to when the statement (that is usually be a
block) executes, if the condition is true then only the statement (that is usually a block) will
execute.
The increment or decrement statement executes every time after the statement (that is usually
a block).

public class WhileDemo


{
public static void main( String[] args )
{
int i = 0;
while ( i < 5 )
{
System.out.println( "Value :: " + i );
i++;
}
}
}
Output:

The For each loop

This was introduced in Java 5. This loop is basically used to traverse the array or collection
elements.

public class ForEachDemo


{
public static void main( String[] args )
{
int[] i =
{ 1, 2, 3, 4, 5 };
for ( int j : i )
{
System.out.println( "value :: " + j );
}

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


}
}
Output:

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.

The break statement has the following two forms:

● Labeled Break Statement


● Unlabeled Break Statement

Unlabeled Break Statement: This is used to jump program control out of the specific loop on
the specific condition.

public class UnLabeledBreakDemo


{
public static void main( String[] args )
{
for ( int var = 0; var < 5; var++ )
{
System.out.println( "Var is : " + var );
if ( var == 3 )
break;
}
}
}
Output:

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Labeled Break Statement: This is used for when we want to jump the program control out
of nested loops or multiple loops.

public class LabeledBreakDemo


{
public static void main( String[] args )
{
Outer: for ( int var1 = 0; var1 < 5; var1++ )
{
for ( int var2 = 1; var2 < 5; var2++ )
{
System.out.println( "var1:" + var1 + ", var2:" + var2 );
if ( var1 == 3 )
break Outer;
}
}
}
}
Output:

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.

The continue statement has the following two forms:

● Labeled Continue Statement


● Unlabeled Continue Statement

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Unlabeled Continue Statement: This statement skips the current iteration of the innermost
for, while and do-while loop.

public class UnlabeledContinueDemo


{
public static void main( String[] args )
{
for ( int var1 = 0; var1 < 4; var1++ )
{
for ( int var2 = 0; var2 < 4; var2++ )
{
if ( var2 == 2 )
continue;
System.out.println( "var1:" + var1 + ", var2:" + var2 );
}
}
}
}
Output:

Labeled Continue Statement: This statement skips the current iteration of the loop with the
specified label.

public class LabeledContinueDemo


{
public static void main( String[] args )
{
Outer: for ( int var1 = 0; var1 < 5; var1++ )
{
for ( int var2 = 0; var2 < 5; var2++ )
{
if ( var2 == 2 )
continue Outer;
System.out.println( "var1:" + var1 + ", var2:" + var2 );
}
}
}
} Output:

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Return Statement

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.

public class ReturnDemo


{
public static void main( String[] args )
{
ReturnDemo returnDemo = new ReturnDemo();
System.out.println( "No : " + returnDemo.returnCall() );
}

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.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


An array of 10 elements.

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;

// allocates memory for 10 integers


anArray = new int[10];

// initialize first element


anArray[0] = 100;
// initialize second element
anArray[1] = 200;
// and so forth
anArray[2] = 300;
anArray[3] = 400;
anArray[4] = 500;
anArray[5] = 600;
anArray[6] = 700;
anArray[7] = 800;
anArray[8] = 900;
anArray[9] = 1000;

System.out.println("Element at index 0: "


+ anArray[0]);
System.out.println("Element at index 1: "
+ anArray[1]);
System.out.println("Element at index 2: "
+ anArray[2]);
System.out.println("Element at index 3: "
+ anArray[3]);
System.out.println("Element at index 4: "
+ anArray[4]);
System.out.println("Element at index 5: "
+ anArray[5]);
System.out.println("Element at index 6: "
+ anArray[6]);
System.out.println("Element at index 7: "
+ anArray[7]);

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


System.out.println("Element at index 8: "
+ anArray[8]);
System.out.println("Element at index 9: "
+ anArray[9]);
}
}

The output from this program is:

Element at index 0: 100


Element at index 1: 200
Element at index 2: 300
Element at index 3: 400
Element at index 4: 500
Element at index 5: 600
Element at index 6: 700
Element at index 7: 800
Element at index 8: 900

Element at index 9: 1000

Creating, Initializing, and Accessing an Array

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.

// create an array of integers


anArray = new int[10];

If this statement is missing, then the compiler prints an error like the following, and compilation
fails:

ArrayDemo.java:4: Variable anArray may not have been initialized.

The next few lines assign values to each element of the array:

anArray[0] = 100; // initialize first element


anArray[1] = 200; // initialize second element
anArray[2] = 300; // and so forth

Each array element is accessed by its numerical index:

System.out.println("Element 1 at index 0: " + anArray[0]);


System.out.println("Element 2 at index 1: " + anArray[1]);
System.out.println("Element 3 at index 2: " + anArray[2]);

Alternatively, you can use the shortcut syntax to create and initialize an array:

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


int[] anArray = {
100, 200, 300,
400, 500, 600,
700, 800, 900, 1000
};

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.

In the Java programming language, a multidimensional array is an array whose components


are themselves arrays. This is unlike arrays in C or Fortran. A consequence of this is that the
rows are allowed to vary in length, as shown in the following MultiDimArrayDemo program:

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]);
}
}

The output from this program is:

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);

STRINGs & STRING HANDLING:

1. String Handling
2. How to create string objects?
1. String literal
2. new keyword
3. Why Java uses the concept of String literal?

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


String Handling provides a lot of concepts that can be performed on a string such as
concatenating string, comparing string, substring etc.

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 ?

● Why String objects are immutable?


● How to create an immutable class?
● What is string constant pool?
● What code is written by the compiler if you concat any string by + (string concatenation
operator) ?
● What is the difference between StringBuffer and StringBuilder class?

How to create String object?

There are two ways to create String object:

1. By string literal
2. By new keyword

1) String literal

String literal is created by double quote.For Example:

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

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


In the above example only one object will be created.First time JVM will find no string object
with the name "Welcome" in string constant pool,so it will create a new object.Second time it
will find the string with the name "Welcome" in string constant pool,so it will not create new
object whether will return the reference to the same instance.

Note: String objects are stored in a special memory area known as string constant pool
inside the Heap memory.

Why java uses concept of string literal?

To make Java more memory efficient (because no new objects are created if it exists already in
string constant pool).

2) By new keyword

1. String s=new String("Welcome");//creates two objects and one reference variable

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).

What we will learn in String Handling ?

● Concept of String
● Immutable String
● String Comparison
● String Concatenation
● Concept of Substring
● String class methods and its usage

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


● StringBuffer class
● StringBuilder class
● Creating Immutable class
● toString() method
● StringTokenizer class

Immutable String in Java

In java, string objects are immutable. Immutable simply means unmodifiable or


unchangeable.

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".

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


But if we explicitely assign it to the reference variable, it will refer to "Sachin Tendulkar"
object.For example:

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.

Why string objects are immutable in java?

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.

a) String comparison 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.

There are three ways to compare String objects:

1. By equals() method

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


2. By = = operator
3. By compareTo() 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

1. //Example of equalsIgnoreCase(String) method


2. class Simple{
3. public static void main(String args[]){
4.
5. String s1="Sachin";
6. String s2="SACHIN";
7.
8. System.out.println(s1.equals(s2));//false
9. System.out.println(s1.equalsIgnoreCase(s3));//true
10. }
11. }

Output:false

true

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


2) By == operator

The = = operator compares references not values.

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.

Suppose s1 and s2 are two string variables.If:

● s1 == s2 :0
● s1 > s2 :positive value
● s1 < s2 :negative value

1. //<b><i>Example of compareTo() method:</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="Ratan";
9.
10. System.out.println(s1.compareTo(s2));//0
11. System.out.println(s1.compareTo(s3));//1(because s1>s3)
12. System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
13. }

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


14. }

Output:0

-1

b) String Concatenation in Java

Concating strings form a new string i.e. the combination of multiple strings.

There are two ways to concat string objects:

1. By + (string concatenation) operator


2. By concat() method

1) By + (string concatenation) operator

String concatenation operator is used to add strings.For Example:

1. //Example of string concatenation operator


2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s="Sachin"+" Tendulkar";
7. System.out.println(s);//Sachin Tendulkar
8. }
9. }

Output:Sachin Tendulkar

The compiler transforms this to:

1. String s=(new StringBuilder()).append("Sachin").append(" Tendulkar).toString();

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[]){

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


3.
4. String s=50+30+"Sachin"+40+40;
5. System.out.println(s);//80Sachin4040
6. }
7. }

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.

Syntax:public String concat(String another){}

1. //<b><i>Example of concat(String) method</i></b>


2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s1="Sachin ";
7. String s2="Tendulkar";
8.
9. String s3=s1.concat(s2);
10.
11. System.out.println(s3);//Sachin Tendulkar
12. }
13. }

Output:Sachin Tendulkar

c) Substring in Java

A part of string is called substring. In other words, substring is a subset of another string.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


In case of substring startIndex starts from 0 and endIndex starts from 1 or startIndex is inclusive
and endIndex is exclusive.

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:

● startIndex:starts from index 0(inclusive).


● endIndex:starts from index 1(exclusive).

Example of java substring

1. //Example of substring() method


2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s="Sachin Tendulkar";
7. System.out.println(s.substring(6));//Tendulkar
8. System.out.println(s.substring(0,6));//Sachin
9. }
10. }

Output:Tendulkar
Sachin

Methods of String class in Java

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.

Let's see the important methods of String class.

Method Description

1)public boolean equals(Object anObject) Compares this string to the specified object.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


2)public boolean equalsIgnoreCase(String Compares this String to another String,
another) ignoring case.

Concatenates the specified string to the end of


3)public String concat(String str)
this string.

4)public int compareTo(String str) Compares two strings and returns int

Compares two strings, ignoring case


5)public int compareToIgnoreCase(String str)
differences.

Returns a new string that is a substring of this


6)public String substring(int beginIndex)
string.

7)public String substring(int beginIndex,int Returns a new string that is a substring of this
endIndex) string.

Converts all of the characters in this String to


8)public String toUpperCase()
upper case

Converts all of the characters in this String to


9)public String toLowerCase()
lower case.

Returns a copy of the string, with leading and


10)public String trim()
trailing whitespace omitted.

Tests if this string starts with the specified


11)public boolean startsWith(String prefix)
prefix.

Tests if this string ends with the specified


12)public boolean endsWith(String suffix)
suffix.

13)public char charAt(int index) Returns the char value at the specified index.

14)public int length() Returns the length of this string.

Returns a canonical representation for the


15)public String intern()
string object.

16)public byte[] getBytes() Converts string into byte array.

17)public char[] toCharArray() Converts string into char array.

18)public static String valueOf(int i) converts the int into String.

19)public static String valueOf(long i) converts the long into String.

20)public static String valueOf(float i) converts the float into String.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


21)public static String valueOf(double i) converts the double into String.

22)public static String valueOf(boolean i) converts the boolean into String.

23)public static String valueOf(char i) converts the char into String.

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.

26)public void replaceAll(String


Changes the firstString with secondString.
firstString,String secondString)

First seven methods have already been discussed.Now Let's take the example of other methods:

toUpperCase() and toLowerCase() method

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

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


7. }
8. }

Output:Sachin
Sachin

startsWith() and endsWith() method

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

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


A pool of strings, initially empty, is maintained privately by the class String.

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.

Commonly used Constructors of StringBuffer class:


1. StringBuffer(): creates an empty string buffer with the initial capacity of 16.
2. StringBuffer(String str): creates a string buffer with the specified string.
3. StringBuffer(int capacity): creates an empty string buffer with the specified capacity
as length.

Commonly used methods of StringBuffer class:


1. public synchronized StringBuffer 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 synchronized StringBuffer insert(int offset, String s): is used to insert the
specified string with this string at the specified position. The insert() method is
overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float),
insert(int, double) etc.
3. public synchronized StringBuffer replace(int startIndex, int endIndex, String
str): is used to replace the string from specified startIndex and endIndex.
4. public synchronized StringBuffer delete(int startIndex, int endIndex): is used to
delete the string from specified startIndex and endIndex.
5. public synchronized StringBuffer reverse(): is used to reverse the string.
6. public int capacity(): is used to return the current capacity.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


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.

What is mutable string?


A string that can be modified or changed is known as mutable string. StringBuffer and
StringBuilder classes are used for creating mutable string.

simple example of StringBuffer class by append() method


The append() method concatenates the given argument with this string.

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. }

Example of insert() method of StringBuffer class


The insert() method inserts the given string with this string at the given position.

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. }

Example of replace() method of StringBuffer class


The replace() method replaces the given string from the specified beginIndex and endIndex.

1. class A{
2. public static void main(String args[]){

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


3.
4. StringBuffer sb=new StringBuffer("Hello");
5. sb.replace(1,3,"Java");
6.
7. System.out.println(sb);//prints HJavalo
8. }
9. }

Example of delete() method of StringBuffer class


The delete() method of StringBuffer class deletes the string from the specified beginIndex to
endIndex.

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. }

Example of reverse() method of StringBuffer class


The reverse() method of StringBuilder class reverses the current string.

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. }

Example of capacity() method of StringBuffer class


The capacity() method of StringBuffer class returns the current capacity of the buffer. The
default capacity of the buffer 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. StringBuffer sb=new StringBuffer();
5. System.out.println(sb.capacity());//default 16

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


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. }

Example of ensureCapacity() method of StringBuffer class


The ensureCapacity() method of StringBuffer 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. 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.

Commonly used Constructors of StringBuilder class:

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.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


3. StringBuilder(int length): creates an empty string Builder with the specified capacity
as length.

Commonly used methods of StringBuilder class:

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.

simple program of StringBuilder class by append() method

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. }

Example of insert() method of StringBuilder class

The insert() method inserts the given string with this string at the given position.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


1. class A{
2. public static void main(String args[]){
3.
4. StringBuilder sb=new StringBuilder("Hello ");
5. sb.insert(1,"Java");//now original string is changed
6.
7. System.out.println(sb);//prints HJavaello
8. }
9. }

Example of replace() method of StringBuilder class

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. }

Example of delete() method of StringBuilder class

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. }

Example of reverse() method of StringBuilder class

The reverse() method of StringBuilder class reverses the current string.

1. class A{
2. public static void main(String args[]){

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


3.
4. StringBuilder sb=new StringBuilder("Hello");
5. sb.reverse();
6.
7. System.out.println(sb);//prints olleH
8. }
9. }

Example of capacity() method of StringBuilder class

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. }

Example of ensureCapacity() method of StringBuilder class

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

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


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. }

Understanding toString() method

If you want to represent any object as a string, toString() method comes into existence.

The toString() method returns the string representation of the object.

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.

Advantage of the toString() method

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.

Understanding problem without toString() method

Let's see the simple code that prints reference.

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. }

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Output:Student@1fee6fc
Student@1eed786
As you can see in the above example, printing s1 and s2 prints the hashcode values of the
objects but I want to print the values of these objects. Since java compiler internally calls
toString() method, overriding this method will return the specified values. Let's understand it
with the example given below:

Example of toString() method

Now let's see the real example of toString() method.

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. }

Output:101 Raj lucknow


102 Vijay ghaziabad

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.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Constructors of StringTokenizer class

There are 3 constructors defined in the StringTokenizer class.

Constructor Description

StringTokenizer(String str) creates StringTokenizer with specified string.

StringTokenizer(String str,
creates StringTokenizer with specified string and delimeter.
String delim)

creates StringTokenizer with specified string, delimeter and


StringTokenizer(String str,
returnValue. If return value is true, delimiter characters are
String delim, boolean
considered to be tokens. If it is false, delimiter characters
returnValue)
serve to separate tokens.

Methods of StringTokenizer class

The 6 useful methods of StringTokenizer class are as follows:

Public method Description

boolean hasMoreTokens() checks if there is more tokens available.

String nextToken() returns the next token from the StringTokenizer object.

String nextToken(String delim) returns the next token based on the delimeter.

boolean hasMoreElements() same as hasMoreTokens() method.

Object nextElement() same as nextToken() but its return type is Object.

int countTokens() returns the total number of tokens.

Simple example of StringTokenizer class

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. }

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


9. }

Output:my
name
is
khan

Example of nextToken(String delim) method of StringTokenizer class

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

StringTokenizer class is deprecated now. It is recommended to use split() method of String


class or regex (Regular Expression).

********************END OF UNIT-1 && UNIT-2(Part-1)**********************

UNIT-II
Introducing Classes:

Class Fundamentals, Declaring Objects, Assuming Object reference Variables, Introducing


Methods, Constructors, The this Keyword, Garbage Collection, The Finalize() method, A Stack
class. Overloading Methods, Using Object as Parameter, Argument Passing, Returning Objects,
Recursion, Introducing Access control, Understanding static, Introducing Nested and Inner
classes, Exploring the String class, Using Command line Arguments, Varargs: variable-Length
Arguments.

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

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


type. Object is an instance of class. You may also call it as physical existence of a logical
template class.

A class is declared using class keyword. A class 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.

Rules for Java Class

● 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.

A simple class example


Suppose, Student is a class and student's name, roll number, age will be its property. Lets see
this in Java syntax
class Student.
{
String name;
int rollno;

int age;

When a reference is made to a particular student with its property then it becomes an object,
physical existence of Student class.

Student std=new Student();

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

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Q. How a class is initialized in java?

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)

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


{

//body of method

Example of a Method

public String getName(String st)

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.

Method name : Actual name of the method.

Parameter : Value passed to a method.

Method body : collection of statement that defines what method does.

Parameter Vs. Argument

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


While talking about method, it is important to know the difference between two terms
parameter and argument.

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.

call-by-value and call-by-reference

There are two ways to pass an argument to a method

1. call-by-value : In this approach copy of an argument value is pass to a method. Changes


made to the argument value inside the method will have no effect on the arguments.
2. call-by-reference : In this reference of an argument is pass to a method. Any changes
made inside the method will affect the agrument value.

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

public class Test

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


public void callByValue(int x)

x=100;

public static void main(String[] args)

int x=50;

Test t = new Test();

t.callByValue(x); //function call

System.out.println(x);

Output : 50

Example of call-by-reference

public class Test

int x=10;

int y=20;

public void callByReference(Test t)

t.x=100;

t.y=50;

public static void main(String[] args)

Test ts = new Test();

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


System.out.println("Before "+ts.x+" "+ts.y);

ts.callByReference(ts);

System.out.println("After "+ts.x+" "+ts.y);

Output :

Before 10 20

After 100 50

ANOTHER NOTES ON CLASSES:

CLASSES: Classes, Objects, Methods

1. Object in Java
2. Class in Java
3. Instance Variable in Java
4. Method in Java

In object-oriented programming technique, we design a program using objects and classes.

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.

An object has three characteristics:

● state: represents data (value) of an object.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


● behavior: represents the behavior (functionality) of an object such as deposit, withdraw
etc.
● identity: Object identity is typically implemented via a unique ID. The value of the ID
is not visible to the external user. But,it is used internally by the JVM to identify each
object uniquely.

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.

A class in java can contain:

● data member
● method
● constructor
● block
● class and interface

Syntax to declare a class:

1. class <class_name>{
2. data member;
3. method;
4. }

Simple Example of Object and Class

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. }

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


10. }
11. Output:0 null

Instance variable in Java


A variable that is created inside the class but outside the method, is known as instance
variable.Instance variable doesn't get memory at compile time.It gets memory at runtime when
object(instance) is created.That is why, it is known as instance variable.

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.

Example of Object and class that maintains the records of students


In this example, we are creating the two objects of Student class and initializing the value to
these objects by invoking the insertRecord method on it. Here, we are displaying the state
(data) of the objects by invoking the displayInformation method.

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. }

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


23. }

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.

Another Example of Object and Class


There is given another example that maintains the records of Rectangle class. Its explanation
is same as in the above Student class example.

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. }

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Output:55
45

What are the different ways to create an object in Java?


There are many ways to create an object in java. They are:

● By new keyword
● By newInstance() method
● By clone() method
● By factory method etc.

We will learn, these ways to create the object later.

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

Creating multiple objects by one type only


We can create multiple objects by one type only as we do in case of primitives.

1. Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Let us see and Example:

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 a special type of method that is used to initialize the object.

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.

Rules for creating constructor

There are basically two rules defined for the constructor.

1. Constructor name must be same as its class name

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


2. Constructor must have no explicit return type

Types of constructors

There are two types of constructors:

1. default constructor (no-arg constructor)


2. parameterized constructor

1) Default Constructor
A constructor that has no parameter is known as default constructor.

Syntax of default constructor:

1. <class_name>(){}

Example of default constructor


In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at
the time of object creation.

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. }

Output: Bike is created

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Rule: If there is no constructor in a class, compiler automatically creates a default
constructor.

Que) what is the purpose of default constructor?

Default constructor provides the default values to the object like 0, null etc. depending on the
type.

Example of default constructor that displays the default values


1. class Student{
2. int id;
3. String name;
4.
5. void display(){System.out.println(id+" "+name);}
6.
7. public static void main(String args[]){
8. Student s1=new Student();
9. Student s2=new Student();
10. s1.display();
11. s2.display();
12. }
13. }

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.

Why use parameterized constructor?

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Parameterized constructor is used to provide different values to the distinct objects.

Example of parameterized constructor


In this example, we have created the constructor of Student class that have two parameters.
We can have any number of parameters in the 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.

Example of Constructor Overloading

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);}

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


15.
16. public static void main(String args[]){
17. Student s1 = new Student(111,"Karan");
18. Student s2 = new Student(222,"Aryan",25);
19. s1.display();
20. s2.display();
21. }
22. }
Output:111 Karan 0
222 Aryan 25

What is the difference between constructor and method?


There are many differences between constructors and methods. They are given below.

Constructor Method

Method is used to expose behavior of


Constructor is used to initialize the state of an object.
an object.

Constructor must not have return type. Method must have return type.

Constructor is invoked implicitly. Method is invoked explicitly.

The java compiler provides a default constructor if you Method is not provided by compiler
don't have any constructor. in any case.

Method name may or may not be


Constructor name must be same as the class name.
same as class name.

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. }

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


8.
9. Student(Student s){
10. id = s.id;
11. name =s.name;
12. }
13. void display(){System.out.println(id+" "+name);}
14.
15. public static void main(String args[]){
16. Student s1 = new Student(111,"Karan");
17. Student s2 = new Student(s1);
18. s1.display();
19. s2.display();
20. }
21. }

Output:111 Karan
111 Karan

Copying the values of one object to another without constructor


We can copy the values of one object into another by assigning the objects values to another
object. In this case, there is no need to create the constructor.

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

Que) Does constructor return any value?


Ans: yes, that is current class instance (You cannot use return type yet it returns a value).

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Can constructor perform other tasks instead of initialization?

Yes, like object creation, starting a thread, calling method etc. You can perform any operation
in the constructor as you perform in the method.

This keyword in java

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.

Usage of java this keyword

Here is given the 6 usage of java this keyword.

1. this keyword can be used to refer current class instance variable.


2. this() can be used to invoke current class constructor.
3. this keyword can be used to invoke current class method (implicitly)
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this keyword can also be used to return the current class instance.

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.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Understanding the problem without this keyword
Let's understand the problem if we don't use this keyword by the example given below:

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.

Solution of the above problem by this keyword

1. //example of this keyword


2. class Student11{
3. int id;
4. String name;
5.
6. Student11(int id,String name){
7. this.id = id;
8. this.name = name;
9. }
10. void display(){System.out.println(id+" "+name);}
11. public static void main(String args[]){
12. Student11 s1 = new Student11(111,"Karan");
13. Student11 s2 = new Student11(222,"Aryan");
14. s1.display();
15. s2.display();
16. }
17. }

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Output111 Karan
222 Aryan

If local variables(formal arguments) and instance variables are different, there is no need to
use this keyword like in the following program:

Program where this keyword is not required

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

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


2) this() can be used to invoked current class constructor.

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.

1. //Program of this() constructor call (constructor chaining)


2.
3. class Student13{
4. int id;
5. String name;
6. Student13(){System.out.println("default constructor is invoked");}
7. Student13(int id,String name){
8. this ();//it is used to invoked current class constructor.
9. this.id = id;
10. this.name = name;
11. }
12. void display(){System.out.println(id+" "+name);}
13.
14. public static void main(String args[]){
15. Student13 e1 = new Student13(111,"karan");
16. Student13 e2 = new Student13(222,"Aryan");
17. e1.display();
18. e2.display();
19. }
20. }

Output:
default constructor is invoked
default constructor is invoked
111 Karan
222 Aryan

Where to use this() constructor call?


The this() constructor call should be used to reuse the constructor in the constructor. It
maintains the chain between the constructors i.e. it is used for constructor chaining. Let's see
the example given below that displays the actual use of this keyword.

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){

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


11. this(id,name);//now no need to initialize id and name
12. this.city=city;
13. }
14. void display(){System.out.println(id+" "+name+" "+city);}
15.
16. public static void main(String args[]){
17. Student14 e1 = new Student14(111,"karan");
18. Student14 e2 = new Student14(222,"Aryan","delhi");
19. e1.display();
20. e2.display();
21. }
22. }

Output:111 Karan null


222 Aryan delhi

Rule: Call to this() must be the first statement in constructor.

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. }

Output:Compile Time Error

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

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


1. class S{
2. void m(){
3. System.out.println("method is invoked");
4. }
5. void n(){
6. this.m();//no need because compiler does it for you.
7. }
8. void p(){
9. n();//complier will add this to invoke n() method as this.n()
10. }
11. public static void main(String args[]){
12. S s1 = new S();
13. s1.p();
14. }
15. }

Output:method is invoked

4) this keyword can be passed as an argument in the method.


The this keyword can also be passed as an argument in the method. It is mainly used in the
event handling. Let's see the example:

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();

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


11. s1.p();
12. }
13. }

Output:method is invoked

Application of this that can be passed as an argument:


In event handling (or) in a situation where we have to provide reference of a class to another
one.

5) The this keyword can be passed as argument in the constructor call.


We can pass the this keyword in the constructor also. It is useful if we have to use one object
in multiple classes. Let's see the example:

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

6) The this keyword can be used to return current class instance.


We can return the this keyword as an statement from the method. In such case, return type of
the method must be the class type (non-primitive). Let's see the example:

Syntax of this that can be returned as a statement

1. return_type method_name(){

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


2. return this;
3. }

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

Proving this keyword


Let's prove that this keyword refers to the current class instance variable. In this program, we
are printing the reference variable and this, output of both variables are same.

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

Java Garbage Collection

In java, garbage means unreferenced objects.


Garbage Collection is process of reclaiming the runtime unused memory automatically. In other
words, it is a way to destroy the unused objects.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.

Advantage of 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.

How can an object be unreferenced?

There are many ways:

o By nulling the reference


o By assigning a reference to another
o By annonymous object etc.

1) By nulling a reference:

1. Employee e=new Employee();


2. e=null;
2) By assigning a reference to another:
1. Employee e1=new Employee();
2. Employee e2=new Employee();
3. e1=e2;//now the first object referred by e1 is available for garbage collection
3) By annonymous object:
1. new Employee();
finalize() method

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:

1. protected void finalize(){}

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

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


The gc() method is used to invoke the garbage collector to perform cleanup processing. The
gc() is found in System and Runtime classes.

1. public static void gc(){}

Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC).


This thread calls the finalize() method before object is garbage collected.

Simple Example of garbage collection in java

1. public class TestGarbage1{


2. public void finalize(){System.out.println("object is garbage collected");}
3. public static void main(String args[]){
4. TestGarbage1 s1=new TestGarbage1();
5. TestGarbage1 s2=new TestGarbage1();
6. s1=null;
7. s2=null;
8. System.gc();
9. }
10. }
object is garbage collected

object is garbage collected

Note: Neither finalization nor garbage collection is guaranteed.

Java Runtime class

No. Method Description

1) public static Runtime getRuntime() returns the instance of Runtime


class.

2) public void exit(int status) terminates the current virtual


machine.

3) public void addShutdownHook(Thread hook) registers new hook thread.

4) public Process exec(String command)throws executes given command in a


IOException separate process.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


5) public int availableProcessors() returns no. of available
processors.

6) public long freeMemory() returns amount of free memory


in JVM.

7) public long totalMemory() returns amount of total memory


in JVM.

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.

The Runtime.getRuntime() method returns the singleton instance of Runtime class.

Important methods of Java Runtime class

Java Runtime exec() method

1. public class Runtime1{


2. public static void main(String args[])throws Exception{
3. Runtime.getRuntime().exec("notepad");//will open a new notepad
4. }
5. }

Java Runtime freeMemory() and totalMemory() method

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.

1. public class MemoryTest{


2. public static void main(String args[])throws Exception{
3. Runtime r=Runtime.getRuntime();
4. System.out.println("Total Memory: "+r.totalMemory());
5. System.out.println("Free Memory: "+r.freeMemory());
6.
7. for(int i=0;i<10000;i++){
8. new MemoryTest();
9. }
10. System.out.println("After creating 10000 instance, Free Memory: "+r.freeMemory());
11. System.gc();
12. System.out.println("After gc(), Free Memory: "+r.freeMemory());
13. }

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


14. }
Total Memory: 100139008

Free Memory: 99474824

After creating 10000 instance, Free Memory: 99310552

After gc(), Free Memory: 100182832

METHOD AND CONSTRUCTOR OVERLOADING:

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.

Example of Constructor Overloading

23. class Student{


24. int id;
25. String name;
26. int age;
27. Student(int i,String n){
28. id = i;
29. name = n;
30. }
31. Student(int i,String n,int a){
32. id = i;
33. name = n;
34. age=a;
35. }
36. void display(){System.out.println(id+" "+name+" "+age);}
37.
38. public static void main(String args[]){
39. Student s1 = new Student(111,"Karan");
40. Student s2 = new Student(222,"Aryan",25);
41. s1.display();
42. s2.display();
43. }
44. }

Output:111 Karan 0
222 Aryan 25

METHOD OVERLOADING

1. Different ways to overload the method


2. By changing the no. of arguments
3. By changing the datatype

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


4. Why method overloading is not possible by changing the return type
5. Can we overload the main method
6. method overloading with Type Promotion

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.

Suppose you have to perform addition of the given


numbers but there can be any number of arguments, if
you write the method such as a(int,int) for two
parameters, and b(int,int,int) for three parameters then
it may be difficult for you as well as other programmers
to understand the behaviour of the method because its
name differs. So, we perform method overloading to
figure out the program quickly.

Advantage of method overloading?

Method overloading increases the readability of the program.

Different ways to overload the method


There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

In java, Method Overloading is not possible by changing the return type of the method.

1) Example of Method Overloading by changing the no. of arguments

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. }

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


11. }

Output:30
40

2) Example of Method Overloading by changing data type of argument

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

Can we overload main () method?

Yes, by method overloading. You can have any number of main methods in a class by method
overloading. Let's see the simple example:

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


1. class Simple{
2. public static void main(int a){
3. System.out.println(a);
4. }
5.
6. public static void main(String args[]){
7. System.out.println("main() method invoked");
8. main(10);
9. }
10. }

Output:main() method invoked


10

Method Overloading and Type Promotion

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.

Example of Method Overloading with Type Promotion


1. class Calculation{
2. void sum(int a,long 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(20,20);//now second int literal will be promoted to long
8. obj.sum(20,20,20);
9. }
10. }

Output:40
60

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Example of Method Overloading with TypePromotion if matching found

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. }

Output:int arg method invoked

Example of Method Overloading with TypePromotion in case ambiguity


If there are no matching type arguments in the method, and each method promotes similar
number of arguments, there will be ambiguity.

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. }

Output:Compile Time Error

One type is not de-promoted implicitly for example double cannot be depromoted to any type
implicitly

UNDERSTANDING STATIC KEYWORD:

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.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


The static can be:

1. variable (also known as class variable)


2. method (also known as class method)
3. block
4. nested class

1) Java static variable

If you declare any variable as static, it is known static variable.

● 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.

Advantage of static variable

It makes your program memory efficient (i.e it saves memory).

Understanding problem without static variable

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.

Java static property is shared to all objects.

Example of static variable

1. //Program of static variable


2.
3. class Student8{
4. int rollno;
5. String name;
6. static String college ="ITS";
7.
8. Student8(int r,String n){
9. rollno = r;
10. name = n;
11. }
12. void display (){System.out.println(rollno+" "+name+" "+college);}
13.
14. public static void main(String args[]){

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


15. Student8 s1 = new Student8(111,"Karan");
16. Student8 s2 = new Student8(222,"Aryan");
17.
18. s1.display();
19. s2.display();
20. }
21. }

Output:111 Karan ITS


222 Aryan ITS

Program of counter without static variable

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. }

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Output:1
1
1

Program of counter by static variable


As we have mentioned above, static variable will get the memory only once, if any object
changes the value of the static variable, it will retain its value.

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

2) Java static method

If you apply static keyword with any method, it is known as static method.

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


● A static method can be invoked without the need for creating an instance of a class.
● static method can access static data member and can change the value of it.

Example of static method

1. //Program of changing the common property of all objects(static field).


2.
3. class Student9{
4. int rollno;
5. String name;
6. static String college = "ITS";
7.
8. static void change(){
9. college = "BBDIT";
10. }
11.
12. Student9(int r, String n){
13. rollno = r;

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


14. name = n;
15. }
16. void display (){System.out.println(rollno+" "+name+" "+college);}
17. public static void main(String args[]){
18. Student9.change();
19. Student9 s1 = new Student9 (111,"Karan");
20. Student9 s2 = new Student9 (222,"Aryan");
21. Student9 s3 = new Student9 (333,"Sonoo");
22. s1.display();
23. s2.display();
24. s3.display();
25. }
26. }

Output:111 Karan BBDIT


222 Aryan BBDIT
333 Sonoo BBDIT

Another example of static method that performs normal calculation

1. //Program to get cube of a given number by static method


2.
3. class Calculate{
4. static int cube(int x){
5. return x*x*x;
6. }
7.
8. public static void main(String args[]){
9. int result=Calculate.cube(5);
10. System.out.println(result);
11. }
12. }

Output:125

Restrictions for static method


There are two main restrictions for the static method. They are:

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);

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


6. }
7. }

Output:Compile Time Error

Q) why java main method is static?


Ans) because object is not required to call static method if it were non-static method, jvm create
object first then call main() method that will lead the problem of extra memory allocation.

3) Java static block

● Is used to initialize the static data member.


● It is executed before main method at the time of classloading.

Example of static block

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. }

Output:static block is invoked


Hello main

Q) Can we execute a program without main() method?

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:static block is invoked (if not JDK7)

In JDK7 and above, output will be:

Output:Error: Main method not found in class A3, please define the main method as:
public static void main(String[] args)

NESTED & INNER CLASS

1. Java Inner classes


2. Advantage of Inner class
3. Difference between nested class and inner class

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


4. Types of Nested classes

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.

Syntax of Inner class

1. class Java_Outer_class{
2. //code
3. class Java_Inner_class{
4. //code
5. }
6. }

Advantage of java inner classes

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.

3) Code Optimization: It requires less code to write.

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 ?

Difference between nested class and inner class in Java

Inner class is a part of nested class. Non-static nested classes are known as inner classes.

Types of Nested classes

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


There are two types of nested classes non-static and static nested classes.The non-static nested
classes are also known as inner classes.

1. Non-static nested class(inner class)


o a)Member inner class
o b)Annomynous inner class
o c)Local inner class
2. Static nested class

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.

Local Inner Class A class created within method.

Static Nested Class A static class created within class.

Nested Interface An interface created within class or interface.

Java Member inner class

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. }

Java Member inner class example

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. }

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


6. public static void main(String args[]){
7. TestMemberOuter1 obj=new TestMemberOuter1();
8. TestMemberOuter1.Inner in=obj.new Inner();
9. in.msg();
10. }
11. }

Output:

data is 30

Internal working of Java member inner class

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.

Internal code generated by the compiler

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:

1. Class (may be abstract or concrete).


2. Interface

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Java anonymous inner class example using class
1. abstract class Person{
2. abstract void eat();
3. }
4. class TestAnonymousInner{
5. public static void main(String args[]){
6. Person p=new Person(){
7. void eat(){System.out.println("nice fruits");}
8. };
9. p.eat();
10. }
11. }

Output:

nice fruits

Internal working of given code

1. Person p=new Person(){


2. void eat(){System.out.println("nice fruits");}
3. };
1. A class is created but its name is decided by the compiler which extends the Person
class and provides the implementation of the eat() method.
2. An object of Anonymous class is created that is referred by p reference variable of
Person type.

Internal class generated by the compiler

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. }

Java anonymous inner class example using interface

1. interface Eatable{
2. void eat();
3. }
4. class TestAnnonymousInner1{
5. public static void main(String args[]){
6. Eatable e=new Eatable(){

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


7. public void eat(){System.out.println("nice fruits");}
8. };
9. e.eat();
10. }
11. }

Output:

nice fruits

Internal working of given code

It performs two main tasks behind this code:

1. Eatable p=new Eatable(){


2. void eat(){System.out.println("nice fruits");}
3. };
1. A class is created but its name is decided by the compiler which implements the Eatable
interface and provides the implementation of the eat() method.
2. An object of Anonymous class is created that is referred by p reference variable of
Eatable type.

Internal class generated by the compiler


1. import java.io.PrintStream;
2. static class TestAnonymousInner1$1 implements Eatable
3. {
4. TestAnonymousInner1$1(){}
5. void eat(){System.out.println("nice fruits");}
6. }
Java Local inner class

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.

Java local inner class example

1. public class localInner1{


2. private int data=30;//instance variable
3. void display(){
4. class Local{
5. void msg(){System.out.println(data);}
6. }
7. Local l=new Local();
8. l.msg();
9. }
10. public static void main(String args[]){
11. localInner1 obj=new localInner1();
12. obj.display();
13. }

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


14. }

Output:

30

Internal class generated by the compiler

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. }

Rule: Local variable can't be private, public or protected.

Rules for Java Local Inner class

1) Local inner class cannot be invoked from outside the method.

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.

Example of local inner class with local variable


1. class localInner2{
2. private int data=30;//instance variable
3. void display(){
4. int value=50;//local variable must be final till jdk 1.7 only
5. class Local{
6. void msg(){System.out.println(value);}
7. }
8. Local l=new Local();
9. l.msg();
10. }
11. public static void main(String args[]){
12. localInner2 obj=new localInner2();

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


13. obj.display();
14. }
15. }

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.

o It can access static data members of outer class including private.


o Static nested class cannot access non-static (instance) data member or method.

Java static nested class example with instance method

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.

Internal class generated by the compiler


1. import java.io.PrintStream;
2. static class TestOuter1$Inner
3. {
4. TestOuter1$Inner(){}
5. void msg(){
6. System.out.println((new StringBuilder()).append("data is ")
7. .append(TestOuter1.data).toString());
8. }
9. }

Java static nested class example with static method

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


If you have the static member inside static nested class, you don't need to create instance of
static nested class.

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.

Points to remember for nested interfaces

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.

Syntax of nested interface which is declared within the interface

1. interface interface_name{
2. ...
3. interface nested_interface_name{
4. ...
5. }
6. }

Syntax of nested interface which is declared within the class

1. class class_name{
2. ...
3. interface nested_interface_name{
4. ...
5. }
6. }

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Example of nested interface which is declared within the interface

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:.

1. public static interface Showable$Message


2. {
3. public abstract void msg();
4. }

Example of nested interface which is declared within the class

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. }

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


6.
7. class TestNestedInterface2 implements A.Message{
8. public void msg(){System.out.println("Hello nested interface");}
9.
10. public static void main(String args[]){
11. A.Message message=new TestNestedInterface2();//upcasting here
12. message.msg();
13. }
14. }
Output:hello nested interface

Can we define a class inside the interface?

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. }

Java Command Line Arguments


1. Command Line Argument
2. Simple example of command-line argument
3. Example of command-line argument that prints all the values

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.

Simple example of command-line argument in java


In this example, we are receiving only one argument and printing it. To run this java
program, you must pass at least one argument 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

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Output: Your first argument is: sonoo

Example of command-line argument that prints all the values


In this example, we are printing all the arguments passed from the command-line. For this
purpose, we have traversed the array using for loop.

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

Variable Argument (Varargs):

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:

We don't have to provide overloaded methods so less code.

Syntax of varargs:

The varargs uses ellipsis i.e. three dots after the data type. Syntax is as follows:

1. return_type method_name(data_type... variableName){}

Simple Example of Varargs in java:


1.
2. class VarargsExample1{
3.
4. static void display(String... values){
5. System.out.println("display method invoked ");
6. }

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


7.
8. public static void main(String args[]){
9. display();//zero argument
10. display("my","name","is","varargs");//four arguments
11. }
12. }
13.

Output:display method invoked


display method invoked

Another Program of Varargs in java:


1.
2. class VarargsExample2{
3.
4. static void display(String... values){
5. System.out.println("display method invoked ");
6. for(String s:values){
7. System.out.println(s);
8. }
9. }
10.
11. public static void main(String args[]){
12.
13. display();//zero argument
14. display("hello");//one argument
15. display("my","name","is","varargs");//four arguments
16. }
17. }
18.

Output:display method invoked


display method invoked
hello
display method invoked
my
name
is
varargs

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Recursion
Recursion in Java

Recursion in java is a process in which a method calls itself continuously. A method in java
that calls itself is called recursive method.

It makes the code compact but complex to understand.

Syntax:

1. returntype methodname(){
2. //code to be executed
3. methodname();//calling same method
4. }

Java Recursion Example 1: Infinite times

1. public class RecursionExample1 {


2. static void p(){
3. System.out.println("hello");
4. p();
5. }
6.
7. public static void main(String[] args) {
8. p();
9. }
10. }

Output:

hello
hello
...
java.lang.StackOverflowError

Java Recursion Example 2: Finite times

1. public class RecursionExample2 {


2. static int count=0;
3. static void p(){
4. count++;
5. if(count<=5){
6. System.out.println("hello "+count);
7. p();
8. }

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


9. }
10. public static void main(String[] args) {
11. p();
12. }
13. }

Output:

hello 1
hello 2
hello 3
hello 4
hello 5

Java Recursion Example 3: Factorial Number

1. public class RecursionExample3 {


2. static int factorial(int n){
3. if (n == 1)
4. return 1;
5. else
6. return(n * factorial(n-1));
7. }
8.
9. public static void main(String[] args) {
10. System.out.println("Factorial of 5 is: "+factorial(5));
11. }
12. }

Output:

Factorial of 5 is: 120

Working of above program:

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

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Java Recursion Example 4: Fibonacci Series

1. public class RecursionExample4 {


2. static int n1=0,n2=1,n3=0;
3. static void printFibo(int count){
4. if(count>0){
5. n3 = n1 + n2;
6. n1 = n2;
7. n2 = n3;
8. System.out.print(" "+n3);
9. printFibo(count-1);
10. }
11. }
12.
13. public static void main(String[] args) {
14. int count=15;
15. System.out.print(n1+" "+n2);//printing 0 and 1
16. printFibo(count-2);//n-2 because 2 numbers are already printed
17. }
18. }

Output:

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

****************END OF UNIT-II(Part-2)***********************

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


UNIT III:
Inheritance: Basics, Using super, creating a multi level hierarchy, when constructors are
executed, method overriding, dynamic method dispatch, using abstract class, using final with
inheritance, the object class.

Packages and Interfaces:


Packages, Access protection, Importing Packages, Interfaces, Default Interfaces, Default
interface methods, Use static methods in an Interface, Final thoughts on Packages and
interfaces.
Exception Handling:
Exception handling Fundamentals, Exception Types, Uncaught Exceptions, Using try and
catch,
Multiple catch clauses, Nested try statements, throw, throws, finally, Java Built-in
Exceptions, Creating your own exception subclasses, Chained Exceptions, Three Recently
added Exceptions features, Using Exceptions

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.

Inheritance represents the IS-A relationship.

Why use Inheritance?

● For Method Overriding (So Runtime Polymorphism).


● For Code Reusability.

Syntax of Inheritance

1. class Subclass-name extends Superclass-name


2. {
3. //methods and fields
4. }

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


The keyword extends indicates that you are making a new class that derives from an existing
class. In the terminology of Java, a class that is inherited is called a superclass. The new class
is called a subclass.

Understanding the simple example 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. }

Output:Programmer salary is:40000.0

Bonus of programmer is:10000

In the above example,Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Types of Inheritance

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.

Multiple inheritance is not supported in java in case of class.

When a class extends multiple classes i.e. known as multiple inheritance. For Example:

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Que) Why multiple inheritance is not supported in java?

● 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

If a class has an entity reference, it is known as Aggregation. Aggregation represents HAS-A


relationship.

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.

Why use Aggregation?

● For Code Reusability.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Simple Example of Aggregation

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

When use Aggregation?

● 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.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Understanding meaningful example of Aggregation

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

1. public class Address {


2. String city,state,country;
3.
4. public Address(String city, String state, String country) {
5. this.city = city;
6. this.state = state;
7. this.country = country;
8. }
9.
10. }

Emp.java

1. public class Emp {


2. int id;
3. String name;
4. Address address;
5.
6. public Emp(int id, String name,Address address) {
7. this.id = id;
8. this.name = name;
9. this.address=address;
10. }
11.
12. void display(){
13. System.out.println(id+" "+name);
14. System.out.println(address.city+" "+address.state+" "+address.country);
15. }
16.
17. public static void main(String[] args) {
18. Address address1=new Address("gzb","UP","india");
19. Address address2=new Address("gno","UP","india");
20.
21. Emp e=new Emp(111,"varun",address1);
22. Emp e2=new Emp(112,"arun",address2);
23.
24. e.display();
25. e2.display();
26.
27. }
28. }

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Output:111 varun

gzb UP india

112 arun

gno UP india

Super keyword in java

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.

super keyword in java

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.

Usage of java super Keyword

1. super can be used to refer immediate parent class instance variable.


2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

1) super is used to refer immediate parent class instance 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[]){

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


13. Dog d=new Dog();
14. d.printColor();
15. }}

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.

2) super can be used to invoke parent class method

The super keyword can also be used to invoke parent class method. It should be used 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.

To call the parent class method, we need to use super keyword.

3) super is used to invoke parent class constructor.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


The super keyword can also be used to invoke the parent class constructor. Let's see a simple
example:

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

Note: super() is added in each class constructor automatically by compiler if there is no


super() or this().

As we know well that default constructor is provided by compiler automatically if there is no


constructor. But, it also adds super() as the first statement.

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. }

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


4. class Dog extends Animal{
5. Dog(){
6. System.out.println("dog is created");
7. }
8. }
9. class TestSuper4{
10. public static void main(String args[]){
11. Dog d=new Dog();
12. }}

Output:

animal is created
dog is created

super example: real use

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:

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


1 ankit 45000

Method Overriding in Java


1. Understanding problem without method overriding
2. Can we override the static method
3. method overloading vs method overriding

If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in java.

In other words, If subclass provides the specific implementation of the method that has been
provided by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding


o Method overriding is used to provide specific implementation of a method that is
already provided by its super class.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. method must have same name as in the parent class
2. method must have same parameter as in the parent class.
3. must be IS-A relationship (inheritance).

Understanding the problem without 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.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Example of 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

Real example of Java Method Overriding

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.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


1. class Bank{
2. int getRateOfInterest(){return 0;}
3. }
4. class SBI extends Bank{
5. int getRateOfInterest(){return 8;}
6. }
7. class ICICI extends Bank{
8. int getRateOfInterest(){return 7;}
9. }
10. class AXIS extends Bank{
11. int getRateOfInterest(){return 9;}
12. }
13. class Test2{
14. public static void main(String args[]){
15. SBI s=new SBI();
16. ICICI i=new ICICI();
17. AXIS a=new AXIS();
18. System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
19. System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
20. System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


21. }
22. }
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

Can we override static method?

No, static method cannot be overridden. It can be proved by runtime polymorphism, so we will
learn it later.

Why we cannot override static method?

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.

Can we override java main method?

No, because main is a static method.

Difference between method Overloading and Method Overriding in java

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:

No. Method Overloading Method


Overriding

1) Method overloading is used to increase the Method overriding is used to


readability of the program. provide the specific
implementation of the method
that is already provided by its
super class.

2) Method overloading is performed within Method overriding occurs in two


class. classes that have IS-A
(inheritance) relationship.

3) In case of method overloading, parameter In case of method


must be different. overriding, parameter must be
same.

4) Method overloading is the example Method overriding is the example


of compile time polymorphism. of run time polymorphism.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


5) In java, method overloading can't be Return type must be same or
performed by changing return type of the covariant in method overriding.
method only. Return type can be same or
different in method overloading. But you
must have to change the parameter.

Abstract class in Java

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.

Ways to achieve Abstaction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

Abstract class in Java

A class that is declared as abstract is known as abstract class. It needs to be extended and its
method implemented. It cannot be instantiated.

Example abstract class

1. abstract class A{}


2. abstract method

A method that is declared as abstract and does not have implementation is known as abstract
method.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


3. Example 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.

1. abstract class Bike{


2. abstract void run();
3. }
4. class Honda4 extends Bike{
5. void run(){System.out.println("running safely..");}
6. public static void main(String args[]){
7. Bike obj = new Honda4();
8. obj.run();
9. }
10. }

running safely..

Understanding the real scenario of abstract class

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

1. abstract class Shape{


2. abstract void draw();
3. }
4. //In real scenario, implementation is provided by others i.e. unknown by end user
5. class Rectangle extends Shape{
6. void draw(){System.out.println("drawing rectangle");}
7. }
8. class Circle1 extends Shape{
9. void draw(){System.out.println("drawing circle");}
10. }

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


11. //In real scenario, method is called by programmer or user
12. class TestAbstraction1{
13. public static void main(String args[]){
14. Shape s=new Circle1();//In real scenario, object is provided through method e.g. getS
hape() method
15. s.draw();
16. }
17. }
18. drawing circle

Another example of abstract class in java


File: TestBank.java

1. abstract class Bank{


2. abstract int getRateOfInterest();
3. }
4. class SBI extends Bank{
5. int getRateOfInterest(){return 7;}
6. }
7. class PNB extends Bank{
8. int getRateOfInterest(){return 8;}
9. }
10.
11. class TestBank{
12. public static void main(String args[]){
13. Bank b;
14. b=new SBI();
15. System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
16. b=new PNB();
17. System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
18. }}

Rate of Interest is: 7 %


Rate of Interest is: 8 %

Abstract class having constructor, data member, methods etc

An abstract class can have data member, abstract method, method body, constructor and even
main() method.

File: TestAbstraction2.java

1. //example of abstract class that have method body


2. abstract class Bike{
3. Bike(){System.out.println("bike is created");}
4. abstract void run();
5. void changeGear(){System.out.println("gear changed");}
6. }
7.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


8. class Honda extends Bike{
9. void run(){System.out.println("running safely..");}
10. }
11. class TestAbstraction2{
12. public static void main(String args[]){
13. Bike obj = new Honda();
14. obj.run();
15. obj.changeGear();
16. }
17. }

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. }

compile time error

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.

Another real scenario of abstract class

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");}

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


16. }
17.
18. class Test5{
19. public static void main(String args[]){
20. A a=new M();
21. a.a();
22. a.b();
23. a.c();
24. a.d();
25. }}

Output:I am a
I am b
I am c
I am d

Difference between abstract class and interface

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.

Abstract class Interface

Interface can have only abstract methods. Since


1) Abstract class can have abstract and
Java 8, it can have default and static methods
non-abstract methods.
also.

2) Abstract class doesn't support multiple


Interface supports multiple inheritance.
inheritance.

3) Abstract class can have final, non-final,


Interface has only static and final variables.
static and non-static variables.

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();
}
}

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully
abstraction (100%).

Using final

Final Keyword In Java

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.

1) Java final variable

If you make any variable as final, you cannot change the value of final variable (It will be
constant).

Example of final variable

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


There is a final variable speedlimit, we are going to change the value of this variable, but It
can't be changed because final variable once assigned a value can never be changed.

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

Output:Compile Time Error

2) Java final method

If you make any method as final, you cannot override it.

Example of final method

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. }

Output:Compile Time Error

3) Java final class

If you make any class as final, you cannot extend it.

Example of final class

1. final class Bike{}


2.
3. class Honda1 extends Bike{
4. void run(){System.out.println("running safely with 100kmph");}
5.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


6. public static void main(String args[]){
7. Honda1 honda= new Honda();
8. honda.run();
9. }
10. }

Output:Compile Time Error

Q) Is final method inherited?

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...

Q) What is blank or uninitialized final variable?

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.

It can be initialized only in constructor.

Example of blank final variable

1. class Student{
2. int id;
3. String name;
4. final String PAN_CARD_NUMBER;
5. ...
6. }

Que) Can we initialize blank final variable?

Yes, but only in constructor. For example:

1. class Bike10{
2. final int speedlimit;//blank final variable
3.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


4. Bike10(){
5. speedlimit=70;
6. System.out.println(speedlimit);
7. }
8. public static void main(String args[]){
9. new Bike10();
10. }
11. }

Output:70

static blank final variable

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.

Example of static blank final variable

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. }

Q) What is final parameter?

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. }

Output:Compile Time Error

Q) Can we declare a constructor final?

No, because constructor is never inherited.

Object class in Java

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


The Object class is the parent class of all the classes in java by default. In other words, it is the
topmost class of java.

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

returns the Class class object of this object. The


public final Class getClass() Class class can further be used to get the metadata
of this class.

public int hashCode() returns the hashcode number for this object.

public boolean equals(Object obj) compares the given object to this object.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Protected Object clone() throws creates and returns the exact copy (clone) of this
CloneNotSupportedException object.

public String toString() returns the string representation of this object.

wakes up single thread, waiting on this object's


public final void notify()
monitor.

wakes up all the threads, waiting on this object's


public final void notifyAll()
monitor.

causes the current thread to wait for the specified


public final void wait(long timeout)throws
milliseconds, until another thread notifies (invokes
InterruptedException
notify() or notifyAll() method).

causes the current thread to wait for the specified


public final void wait(long timeout,int
milliseconds and nanoseconds, until another thread
nanos)throws InterruptedException
notifies (invokes notify() or notifyAll() method).

causes the current thread to wait, until another


Public final void wait()throws
thread notifies (invokes notify() or notifyAll()
InterruptedException
method).

is invoked by the garbage collector before object is


protected void finalize()throws Throwable
being garbage collected.

Packages and Interfaces:


Java Package
1. Java Package
2. Example of package
3. Accessing package
1. By import packagename.*
2. By import packagename.classname
3. By fully qualified name
4. Subpackage
5. Sending class file to another directory
6. -classpath switch
7. 4 ways to load the class file or jar file
8. How to put two public class in a package
9. Static Import
10. Package class

A java package is a group of similar types of classes, interfaces and sub-packages.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Package in java can be categorized in two form, built-in package and user-defined package.

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.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

Simple example of java package

The package keyword is used to create a package in java.

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. }

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


7. }

How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

1. javac -d directory javafilename

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).

How to run java package program

You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java

To Run: java mypack.Simple

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.

How to access package from another package?

There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;
3. fully qualified name.

1) Using packagename.*

If you use package.* then all the classes and interfaces of this package will be accessible but
not subpackages.

The import keyword is used to make the classes and interface of another package accessible to
the current package.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Example of package that import the packagename.*

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.

Example of package by import package.classname

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

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


3) Using fully qualified name

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.

Example of package by import fully qualified name

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

Note: If you import a package, subpackages will not be imported.

If you import a package, all the classes and interface of that package will be imported excluding
the classes and interfaces of the subpackages. Hence, you need to import the subpackage as
well.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Note: Sequence of the program must be package then import then class.

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.

The standard of defining package is domain.company.package e.g. com.javatpoint.bean or


org.sssit.dao.

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

To Run: java com.javatpoint.core.Simple

Output:Hello subpackage

How to send the class file to another directory or drive?

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


There is a scenario, I want to put the class file of A.java source file in classes folder of c: drive.
For example:

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:

e:\sources> javac -d c:\classes Simple.java

To Run:
To run this program from e:\source directory, you need to set classpath of the directory where
the class file resides.

e:\sources> set classpath=c:\classes;.;

e:\sources> java mypack.Simple

Another way to run this program by -classpath switch of java:

The -classpath switch can be used with javac and java tool.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


To run this program from e:\source directory, you can use -classpath switch of java that tells
where to look for class file. For example:

e:\sources> java -classpath c:\classes mypack.Simple

Output:Welcome to package

Ways to load the class files or jar files


There are two ways to load the class files temporary and permanent.

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 C.java otherwise Compilte Time Error


2.
3. class A{}
4. class B{}
5. public class C{}

How to put two public classes in a package?


If you want to put two public classes in a package, have two java source files containing one
public class, but keep the package name same. For example:

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

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


1. Interface
2. Example of Interface
3. Multiple inheritance by Interface
4. Why multiple inheritance is supported in Interface while it is not supported in case of
class.
5. Marker Interface
6. Nested Interface

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.

Java Interface also represents IS-A relationship.

It cannot be instantiated just like abstract class.

Why use Java interface?

There are mainly three reasons to use interface. They are given below.

● It is used to achieve abstraction.


● By interface, we can support the functionality of multiple inheritance.
● It can be used to achieve loose coupling.

Java 8 Interface Improvement

Since Java 8, interface can have default and static methods which is discussed later.

Internal addition by compiler

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.

Understanding relationship between classes and interfaces

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


As shown in the figure given below, a class extends another class, an interface extends another
interface but a class implements an interface.

Java Interface Example

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

Java Interface Example: Drawable

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

1. //Interface declaration: by first user


2. interface Drawable{

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


3. void draw();
4. }
5. //Implementation: by second user
6. class Rectangle implements Drawable{
7. public void draw(){System.out.println("drawing rectangle");}
8. }
9. class Circle implements Drawable{
10. public void draw(){System.out.println("drawing circle");}
11. }
12. //Using interface: by third user
13. class TestInterface1{
14. public static void main(String args[]){
15. Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDra
wable()
16. d.draw();
17. }}

Output:

drawing circle

Java Interface Example: Bank

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

Multiple inheritance in Java by interface

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known
as multiple inheritance.

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

Q) Multiple inheritance is not supported through class in java but it is possible by


interface, why?

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{

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


5. void print();
6. }
7.
8. class TestTnterface3 implements Printable, Showable{
9. public void print(){System.out.println("Hello");}
10. public static void main(String args[]){
11. TestTnterface1 obj = new TestTnterface1();
12. obj.print();
13. }
14. }

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

A class implements interface but one interface extends another interface .

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

Java 8 Default Method in Interface

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Since Java 8, we can have method body in interface. But we need to make it default method.
Let's see an example:

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

Java 8 Static Method in Interface

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

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Q) What is marker or tagged interface?

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.

1. //How Serializable interface is written?


2. public interface Serializable{
3. }

Nested Interface in Java

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. }

Exception Handling in Java


1. Exception Handling
2. Advantage of Exception Handling
3. Hierarchy of Exception classes
4. Types of Exception
1. Checked Exception
2. Unchecked Exception
3. Error
5. Scenarios where exception may occur

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

● Dictionary Meaning:Exception is an abnormal condition.


● In java, exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.

Exception Handling

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Exception Handling is a mechanism to handle runtime errors.

Advantage of 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 ?

Hierarchy of Exception classes

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Types of Exception:

There are mainly two types of exceptions: checked and unchecked where error is considered as
unchecked exception. The sun microsystem says there are three types of exceptions:

1. Checked Exception
2. Unchecked Exception
3. Error

What is the difference between checked and unchecked exceptions ?

1)Checked Exception

The classes that extend Throwable class except RuntimeException and Error are known as
checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at
compile-time.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


2)Unchecked Exception

The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time rather they are checked at runtime.

3)Error

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Common scenarios of Exception Handling where exceptions may occur

There are given some scenarios where unchecked exceptions can occur. They are as follows:

1) Scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

1. int a=50/0;//ArithmeticException

2) Scenario where NullPointerException occurs

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

3) Scenario where NumberFormatException occurs

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

4) Scenario where ArrayIndexOutOfBoundsException occurs

If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


1. int a[]=new int[5];
2. a[10]=50; //ArrayIndexOutOfBoundsException

Use of try-catch block in Exception handling:

Five keywords used in Exception handling:


1. try
2. catch
3. finally
4. throw
5. throws

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.

Syntax of try with catch block

1. try{
2. ...
3. }catch(Exception_class_Name reference){}

Syntax of try with finally block

1. try{
2. ...
3. }finally{}

catch block
Catch block is used to handle the Exception. It must be used after the try block.

Problem without exception handling

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. }

Output:Exception in thread main java.lang.ArithmeticException:/ by zero


As displayed in the above example, rest of the code is not executed i.e. rest of the code...
statement is not printed. Let's see what happens behind the scene:

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


What happens behind the code int a=50/0;
The JVM firstly checks whether the exception is handled or not. If exception is not handled,
JVM provides a default exception handler that performs the following tasks:

● Prints out exception description.


● Prints the stack trace (Hierarchy of methods where the exception occurred).
● Causes the program to terminate.

But if exception is handled by the application programmer, normal flow of the application is
maintained i.e. rest of the code is executed.

Solution by exception handling

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. }

Output:Exception in thread main java.lang.ArithmeticException:/ by zero


rest of the code...
Now, as displayed in the above example, rest of the code is executed i.e. rest of the code...
statement is printed.

Multiple catch blocks:

If you have to perform different tasks at the occurrence of different Exceptions, use multiple
catch block.

1. <b><i>Example of multiple catch block</i></b>


2.
3. class Excep4{
4. public static void main(String args[]){
5. try{
6. int a[]=new int[5];
7. a[5]=30/0;
8. }
9. catch(ArithmeticException e){System.out.println("task1 is completed");}
10. catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed"
);}
11. catch(Exception e){System.out.println("common task completed");}
12.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


13. System.out.println("rest of the code...");
14. }
15. }

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. }

Output: Compile-time error


Nested try block:

try block within a try block is known as nested try block.

Why use nested try block?

Sometimes a situation may arise where a part of a block may cause one error and the entire
block itself may cause another error. In such cases, exception handlers have to be nested

Syntax:

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. {

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


13. }
14. }
15. catch(Exception e)
16. {
17. }
18. ....

Example:

1. <b><i>Example of nested try block</i></b>


2.
3. class Excep6{
4. public static void main(String args[]){
5. try{
6. try{
7. System.out.println("going to divide");
8. int b =39/0;
9. }catch(ArithmeticException e){System.out.println(e);}
10.
11. try{
12. int a[]=new int[5];
13. a[5]=4;
14. }catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
15.
16. System.out.println("other statement);
17. }catch(Exception e){System.out.println("handeled");}
18.
19. System.out.println("normal flow..");
20. }
21. }

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.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Note:Before terminating the program, JVM executes finally block(if any).

Note:finally must be followed by try or catch block.

Why use finally block?


● finally block can be used to put "cleanup" code such as closing a file,closing connection 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

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


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(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:finally block is always executed


Exception in thread main java.lang.ArithmeticException:/ by zero

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. }

Output:Exception in thread main java.lang.ArithmeticException:/ by zero


finally block is always executed
rest of the code...

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

The throw keyword is used to explictily throw an exception.


We can throw either checked or uncheked exception. The throw keyword is mainly used to
throw custom exception. We will see custom exceptions later.
Example of throw keyword

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


In this example, we have created the validate method that takes integer value as a parameter. If
the age is less than 18, we are throwing the ArithmeticException otherwise print a message
welcome to vote.

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. }

Output:Exception in thread main java.lang.ArithmeticException:not valid

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.

Rule: By default Unchecked Exceptions are forwarded in calling chain (propagated).


Program of 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. }

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Output:exception handled
normal flow...

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. }

Output:Compile Time Error

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


throws keyword

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.

Syntax of throws keyword:

1. void method_name() throws exception_class_name{


2. ...
3. }

Que) Which exception should we declare?

Ans) checked exception only, because:

● unchecked Exception: under your control so correct your code.


● error: beyond your control e.g. you are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.

Advantage of throws keyword:

Now Checked Exception can be propagated (forwarded in call stack).

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();

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


17. System.out.println("normal flow...");
18. }
19. }

Output:exception handled
normal flow...

Rule: If you are calling a method that declares an exception, you must either caught or
declare the exception.

There are two cases:

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.

Case1: You handle the exception

● 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...

Case2: You declare the exception

● 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.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


A)Program if exception does not occur

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. }

Output:device operation performed


normal flow...

B)Program if exception occurs

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

Difference between throw and throws:

throw keyword throws keyword


1)throw is used to explicitly throw an
throws is used to declare an exception.
exception.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


2)checked exception can not be propagated checked exception can be propagated with
without throws. throws.
3)throw is followed by an instance. throws is followed by class.
4)throw is used within the method. throws is used with the method signature.
You can declare multiple exception e.g.
5)You cannot throw multiple exception public void method()throws
IOException,SQLException.

Que) Can we rethrow an exception?

Yes by throwing same exception in catch block.

ExceptionHandling with MethodOverriding


There are many rules if we talk about methodoverriding with exception handling. The Rules are
as follows:

● If the superclass method does not declare an exception


o If the superclass method does not declare an exception, subclass overridden
method cannot declare the checked exception but it can declare unchecked
exception.
● If the superclass method declares an exception
o If the superclass method declares an exception, subclass overridden method can
declare same, subclass exception or no exception but cannot declare parent
exception.

If the superclass method does not declare an 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. }

Output:Compile Time Error

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


2) Rule: If the superclass method does not declare an exception, subclass overridden method
cannot declare the checked exception but can declare unchecked 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 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

If the superclass method declares an exception

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.

Example in case subclass overridden method declares 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. }

Output:Compile Time Error

Example in case subclass overridden method declares same exception

1. import java.io.*;
2. class Parent{
3. void msg()throws Exception{System.out.println("parent");}

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


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. }

Output:child

Example in case subclass overridden method declares subclass exception

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

Example in case subclass overridden method declares no exception

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){}

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


14. }
15. }

Output:child

Custom Exception

If you are creating your own Exception that is known as custom exception or user-defined
exception.

1. class InvalidAgeException extends Exception{


2. InvalidAgeException(String s){
3. super(s);
4. }
5. }

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. }

Output:Exception occured: InvalidAgeException:not valid


rest of the code...

*****************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.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


I/O, Applets, and Other Topics:

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

Multithreading in java is a process of executing multiple threads simultaneously.

Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing


and multithreading, both are used to achieve multitasking.

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.

Java Multithreading is mostly used in games, animation etc.

Advantage of Java Multithreading

1) It doesn't block the user because threads are independent and you can perform multiple
operations at same time.

2) You can perform many operations together so it saves time.

3) Threads are independent so it doesn't affect other threads if exception occur in a single
thread.

Multitasking

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to


utilize the CPU. Multitasking can be achieved by two ways:

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


● Process-based Multitasking(Multiprocessing)
● Thread-based Multitasking(Multithreading)

1) Process-based Multitasking (Multiprocessing)

● 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.

2) Thread-based Multitasking (Multithreading)

● Threads share the same address space.


● Thread is lightweight.
● Cost of communication between the thread is low.

Note: At least one process is required for each thread.

What is Thread in java

A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of


execution.

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.

Note: At a time one thread is executed only.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Do You Know

● How to perform two tasks by two threads ?


● How to perform multithreading by annonymous class ?
● What is the Thread Schedular and what is the difference between preemptive
scheduling and time slicing ?
● What happens if we start a thread twice ?
● What happens if we call the run() method instead of start() method ?
● What is the purpose of join method ?
● Why JVM terminates the daemon thread if there is no user threads remaining ?
● What is the shutdown hook?
● What is garbage collection ?
● What is the purpose of finalize() method ?
● What does gc() method ?
● What is synchronization and why use synchronization ?
● What is the difference between synchronized method and synchronized block ?
● What are the two ways to perform static synchronization ?
● What is deadlock and when it can occur ?
● What is interthread-communication or cooperation ?

What we will learn in Multithreading

● 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

Life cycle of a Thread (Thread States)

1. Life cycle of a thread


1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


5. Terminated

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

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


The thread is in running state if the thread scheduler has selected it.

4) Non-Runnable (Blocked)

This is the state when the thread is still alive, but is currently not eligible to run.

5) Terminated

A thread is in terminated or dead state when its run() method exits.

How to create thread

There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

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.

Commonly used Constructors of Thread class:

● Thread()
● Thread(String name)
● Thread(Runnable r)
● Thread(Runnable r,String name)

Commonly used methods of Thread class:

1. public void run(): is used to perform action for a thread.


2. public void start(): starts the execution of the thread.JVM calls the run() method on the
thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing thread.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


11. public int getId(): returns the id of the thread.
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily pause
and allow other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been interrupted.

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().

1. public void run(); is used to perform action for a thread.

Starting a thread:

start() method of Thread class is used to start a newly created thread. It performs following
tasks:

● A new thread starts(with new callstack).


● The thread moves from New state to the Runnable state.
● When the thread gets a chance to execute, its target run() method will run.

1)By extending Thread class:

1. class Multi extends Thread{


2. public void run(){
3. System.out.println("thread is running...");
4. }
5. public static void main(String args[]){
6. Multi t1=new Multi();
7. t1.start();
8. }
9. }

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Output:thread is running...

Who makes your class object as thread object?

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.

2)By implementing the Runnable interface:

1. class Multi3 implements Runnable{


2. public void run(){
3. System.out.println("thread is running...");
4. }
5.
6. public static void main(String args[]){
7. Multi3 m1=new Multi3();
8. Thread t1 =new Thread(m1);
9. t1.start();
10. }
11. }

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

Thread scheduler in java is the part of the JVM that decides which thread should run.

There is no guarantee that which runnable thread will be chosen to run by the thread scheduler.

Only one thread at a time can run in a single process.

The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the
threads.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.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Sleep method in java

The sleep() method of Thread class is used to sleep a thread for the specified amount of time.

Syntax of sleep() method in java

The Thread class provides two methods for sleeping a thread:

● public static void sleep(long miliseconds)throws InterruptedException


● public static void sleep(long miliseconds, int nanos)throws InterruptedException

Example of sleep method in java

1. class TestSleepMethod1 extends Thread{


2. public void run(){
3. for(int i=1;i<5;i++){
4. try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
5. System.out.println(i);
6. }
7. }
8. public static void main(String args[]){
9. TestSleepMethod1 t1=new TestSleepMethod1();
10. TestSleepMethod1 t2=new TestSleepMethod1();
11.
12. t1.start();
13. t2.start();
14. }
15. }
Output:

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.

Can we start a thread twice

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.

Let's understand it by the example given below:

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


1. public class TestThreadTwice1 extends Thread{
2. public void run(){
3. System.out.println("running...");
4. }
5. public static void main(String args[]){
6. TestThreadTwice1 t1=new TestThreadTwice1();
7. t1.start();
8. t1.start();
9. }
10. }

running

Exception in thread "main" java.lang.IllegalThreadStateException

getName(),setName(String) and getId() method:

public String getName()

public void setName(String name)

public long getId()

1. class TestJoinMethod3 extends Thread{


2. public void run(){
3. System.out.println("running...");
4. }
5. public static void main(String args[]){
6. TestJoinMethod3 t1=new TestJoinMethod3();
7. TestJoinMethod3 t2=new TestJoinMethod3();
8. System.out.println("Name of t1:"+t1.getName());
9. System.out.println("Name of t2:"+t2.getName());
10. System.out.println("id of t1:"+t1.getId());
11.
12. t1.start();
13. t2.start();
14.
15. t1.setName("Sonoo Jaiswal");
16. System.out.println("After changing name of t1:"+t1.getName());
17. }
18. }

Output:Name of t1:Thread-0

Name of t2:Thread-1

id of t1:8

running...

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


After changling name of t1:Sonoo Jaiswal

running

The currentThread() method:

The currentThread() method returns a reference to the currently executing thread object.

Syntax:

public static Thread currentThread()

Example of currentThread() method

1. class TestJoinMethod4 extends Thread{


2. public void run(){
3. System.out.println(Thread.currentThread().getName());
4. }
5. }
6. public static void main(String args[]){
7. TestJoinMethod4 t1=new TestJoinMethod4();
8. TestJoinMethod4 t2=new TestJoinMethod4();
9.
10. t1.start();
11. t2.start();
12. }
13. }

Output:Thread-0

Thread-1

Naming a thread:

The Thread class provides methods to change and get the name of a thread.

1. public String getName(): is used to return the name of a thread.


2. public void setName(String name): is used to change the name of a thread.

Example of naming a thread:

1. class TestMultiNaming1 extends Thread{


2. public void run(){
3. System.out.println("running...");
4. }
5. public static void main(String args[]){
6. TestMultiNaming1 t1=new TestMultiNaming1();
7. TestMultiNaming1 t2=new TestMultiNaming1();

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


8. System.out.println("Name of t1:"+t1.getName());
9. System.out.println("Name of t2:"+t2.getName());
10.
11. t1.start();
12. t2.start();
13.
14. t1.setName("Sonoo Jaiswal");
15. System.out.println("After changing name of t1:"+t1.getName());
16. }
17. }

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:

The currentThread() method returns a reference to the currently executing thread object.

Syntax of currentThread() method:

● public static Thread currentThread(): returns the reference of currently running


thread.

Example of currentThread() method:

1. class TestMultiNaming2 extends Thread{


2. public void run(){
3. System.out.println(Thread.currentThread().getName());
4. }
5. }
6. public static void main(String args[]){
7. TestMultiNaming2 t1=new TestMultiNaming2();
8. TestMultiNaming2 t2=new TestMultiNaming2();
9.
10. t1.start();
11. t2.start();
12. }
13. }

Output:Thread-0
Thread-1

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Priority of a Thread (Thread Priority):
Each thread have a priority. Priorities are represented by a number between 1 and 10. In most
cases, thread schedular schedules the threads according to their priority (known as preemptive
scheduling). But it is not guaranteed because it depends on JVM specification that which
scheduling it chooses.

3 constants defiend in Thread class:

1. public static int MIN_PRIORITY


2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and


the value of MAX_PRIORITY is 10.

Example of priority of a Thread:

1. class TestMultiPriority1 extends Thread{


2. public void run(){
3. System.out.println("running thread name is:"+Thread.currentThread().getName());
4. System.out.println("running thread priority is:"+Thread.currentThread().getPriority(
));
5.
6. }
7. public static void main(String args[]){
8. TestMultiPriority1 m1=new TestMultiPriority1();
9. TestMultiPriority1 m2=new TestMultiPriority1();
10. m1.setPriority(Thread.MIN_PRIORITY);
11. m2.setPriority(Thread.MAX_PRIORITY);
12. m1.start();
13. m2.start();
14.
15. }
16. }

Output:running thread name is:Thread-0


running thread priority is:10
running thread name is:Thread-1
running thread priority is:1

How to perform single task by multiple threads?


If you have to perform single task by many threads, have only one run() method.For example:

Program of performing single task by multiple threads

1. class TestMultitasking1 extends Thread{

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


2. public void run(){
3. System.out.println("task one");
4. }
5. public static void main(String args[]){
6. TestMultitasking1 t1=new TestMultitasking1();
7. TestMultitasking1 t2=new TestMultitasking1();
8. TestMultitasking1 t3=new TestMultitasking1();
9.
10. t1.start();
11. t2.start();
12. t3.start();
13. }
14. }

Output:task one

task one

task one

Program of performing single task by multiple threads

1. class TestMultitasking2 implements Runnable{


2. public void run(){
3. System.out.println("task one");
4. }
5.
6. public static void main(String args[]){
7. Thread t1 =new Thread(new TestMultitasking2());//passing annonymous object of Te
stMultitasking2 class
8. Thread t2 =new Thread(new TestMultitasking2());
9.
10. t1.start();
11. t2.start();
12.
13. }
14. }

Output:task one

task one

Note: Each thread run in a separate callstack.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


How to perform multiple tasks by multiple threads (multitasking in multithreading)?

If you have to perform multiple tasks by multiple threads,have multiple run() methods.For
example:

Program of performing two tasks by two threads

1. class Simple1 extends Thread{


2. public void run(){
3. System.out.println("task one");
4. }
5. }
6.
7. class Simple2 extends Thread{
8. public void run(){
9. System.out.println("task two");
10. }
11. }
12.
13. class TestMultitasking3{
14. public static void main(String args[]){
15. Simple1 t1=new Simple1();
16. Simple2 t2=new Simple2();
17.
18. t1.start();
19. t2.start();
20. }
21. }

Output:task one

task two

Same example as above by annonymous class that extends Thread class:

Program of performing two tasks by two threads

1. class TestMultitasking4{

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


2. public static void main(String args[]){
3. Thread t1=new Thread(){
4. public void run(){
5. System.out.println("task one");
6. }
7. };
8. Thread t2=new Thread(){
9. public void run(){
10. System.out.println("task two");
11. }
12. };
13.
14.
15. t1.start();
16. t2.start();
17. }
18. }

Output:task one

task two

Same example as above by annonymous class that implements Runnable interface:

Program of performing two tasks by two threads

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

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


task two

Inter-thread communication in Java

Inter-thread communication or Co-operation is all about allowing synchronized threads to


communicate with each other.

Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running


in its critical section and another thread is allowed to enter (or lock) in the same critical section
to be executed.It is implemented by following methods of Object class:

● 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()throws InterruptedException waits until object is notified.

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:

public final void notify()

3) notifyAll() method

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Wakes up all threads that are waiting on this object's monitor. Syntax:

public final void notifyAll()

Understanding the process of inter-thread communication

The point to point explanation of the above diagram is as follows:

1. Threads enter to acquire lock.


2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it
releases the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable
state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor state of the
object.

Why wait(), notify() and notifyAll() methods are defined in Object class not Thread class?

It is because they are related to lock and object has a lock.

Difference between wait and sleep?

Let's see the important differences between wait and sleep methods.

wait() sleep()

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


wait() method releases the lock sleep() method doesn't release the lock.

is the method of Object class is the method of Thread class

is the non-static method is the static method

is the non-static method is the static method

should be notified by notify() or notifyAll() after the specified amount of time, sleep is
methods completed.

Example of inter thread communication in java

Let's see the simple example of inter thread communication.

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. }}

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Output: going to withdraw...

Less balance; waiting for deposit...

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

There are many advantages of applet. They are as follows:

● It works at client side so less response time.


● Secured
● It can be executed by browsers running under many plateforms, including Linux,
Windows, Mac Os etc.

Drawback of Applet

● Plugin is required at client browser to execute 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 ?

Hiereachy of GUI classes

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Difference between Applet and Application:

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

LIFE CYCLE OF APPLET

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


TYPES OF APPLETS:
There are two types of applets are there.
1. Using Applet class.This Applet class use the AWT(Abstract Window Toolkit) to
provide graphic user interface(Using the Graphics class).This style is available since
java was created.
2.The second type of applets are based on Swing class JApplet.Swing Applets use the
Swing class to provide GUI.Swing offer richer and often easier to use user interface
than AWT.Thus swing based applets are most popular.
Note: Because JApplet inherits the Applet,all the features of Applet are also available
in JApplet

An HTML APPLET tag:

<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>]

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


[<PARAM NAME=AttritubuteName VALUE=AttributeValue>]

Lifecycle methods for Applet:

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:

The Component class provides 1 life cycle method of applet.

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.

Who is responsible to manage the life cycle of an applet?

Java Plug-in software.

How to run an Applet?

There are two ways to run an applet

1. By html file.
2. By appletViewer tool (for testing purpose).

Simple example of Applet by html file:

To execute the applet by html file, create an applet and compile it. After that create an html file
and place the applet code in html file. Now click the html file.

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){

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


7. g.drawString("welcome",150,150);
8. }
9.
10. }

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

Otherwise open the myapplet.html page in web browser

Applet Skeleton:

//An Applet Skeleton

Import java.awt.*;

Import java.applet.*;

/*<applet code=”AppletSke” width=300 height=100>

</applet>*/

public class AppletSke extends Applet {

//Called First

public void init() {

// Initialization

/*Called second,after init().Also called whenever the applet is restarted

public void start() {

//start or resume of execution

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


//Called when applet is stopped

public void stop() {

//suspends execution

/*Called when applet is terminated. This is the last method executed

public void destroy() {

//perform shutdown activity

//Called when an applet’s window must be restored

public void paint(Graphics g) {

//redisplay contents of window

Commonly used methods of Graphics class:

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.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Live Demo:
Simple example of Applet by appletviewer tool:

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. */

To execute the applet by appletviewer tool, write in command prompt:

c:\>javac First.java
c:\>appletviewer First.java

Example of Graphics in applet:

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>

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


6. </html>

Displaying Image in Applet

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.

Syntax of drawImage() method:

1. public abstract boolean drawImage(Image img, int x, int y, ImageObserver


observer): is used draw the specified image.

How to get the object of Image:

The java.applet.Applet class provides getImage() method that returns the object of Image.
Syntax:

1. public Image getImage(URL u, String image){}

Other required methods of Applet class to display image:

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.

Example of displaying image in applet:

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. }

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


In the above example, drawImage() method of Graphics class is used to display the image. The
4th argument of drawImage() method of is ImageObserver object. The Component class
implements ImageObserver interface. So current class object would also be treated as
ImageObserver because Applet class indirectly extends the Component class.

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****************

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


UNIT V:
Introduction the AWT: Working with windows, graphics and Text:
AWT classes, window fundamentals, working with frame windows, creating a frame window
in a an AWT Based applet, creating a window program, displaying information within a
window, Graphics, working with color, setting the paint mode, working with fonts, managing
text output using font metrics,.
Using AWT controls, Layout Mangers, and Menus:
AWT control fundamentals, Labels, using buttons, applying check boxes, check box group,
choice controls, using lists, Managing scroll bars, using a Text field, Using a Text area,
understanding layout managers, Menu bars and Menus, dialog boxes, file dialog, Overriding
paint().

AWT Controls

Every user interface considers the following three main aspects:

● 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.

Every AWT controls inherits properties from Component class.

AWT Component Class

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

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Following is the declaration for java.awt.Component class:

public abstract class Component


extends Object
implements ImageObserver, MenuContainer, Serializable

Field

Following are the fields for java.awt.Component class:

● static float BOTTOM_ALIGNMENT -- Ease-of-use constant for getAlignmentY.


● static float CENTER_ALIGNMENT -- Ease-of-use constant for getAlignmentY and
getAlignmentX.
● static float LEFT_ALIGNMENT -- Ease-of-use constant for getAlignmentX.
● static float RIGHT_ALIGNMENT -- Ease-of-use constant for getAlignmentX.
● static float TOP_ALIGNMENT -- Ease-of-use constant for getAlignmentY().

Class constructors

S.N. Constructor & Description


Protected Component()
1
This creates a new Component.

AWT Components:

1. Label

2. Button

3. CheckBox

4. CheckBoxGroup

5. List

6. TextField

7. TextArea

8. Choice

1. AWT Label Class

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Introduction

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

Following is the declaration for java.awt.Label class:

public class Label


extends Component
implements Accessible

Field

Following are the fields for java.awt.Component class:

● static int CENTER -- Indicates that the label should be centered.


● static int LEFT -- Indicates that the label should be left justified.
● static int RIGHT -- Indicates that the label should be right justified.

Class constructors

S.N. Constructor & Description


Label()
1
Constructs an empty label.
Label(String text)
2
Constructs a new label with the specified string of text, left justified.
Label(String text, int alignment)
3 Constructs a new label that presents the specified string of text with the specified
alignment.

Class methods

S.N. Method & Description


Void addNotify()
1
Creates the peer for this label.
AccessibleContext getAccessibleContext()
2
Gets the AccessibleContext associated with this Label.
Int getAlignment()
3
Gets the current alignment of this label.
String getText()
4
Gets the text of this label.
Protected String paramString()
5
Returns a string representing the state of this Label.
Void setAlignment(int alignment)
6
Sets the alignment for this label to the specified alignment.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Void setText(String text)
7
Sets the text for this label to the specified text.

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();
}
}

2.AWT Button Class

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

Following is the declaration for java.awt.Button class:

public class Button


extends Component
implements Accessible

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Class constructors

S.N. Constructor & Description


Button()
1
Constructs a button with an empty string for its label.
Button(String text)
2
Constructs a new button with specified label.

Class methods

S.N. Method & Description


Void addActionListener(ActionListener l)
1
Adds the specified action listener to receive action events from this button.
Void addNotify()
2
Creates the peer of the button.
AccessibleContext getAccessibleContext()
3
Gets the AccessibleContext associated with this Button.
String getActionCommand()
4
Returns the command name of the action event fired by this button.
ActionListener[] getActionListeners()
5
Returns an array of all the action listeners registered on this button.
String getLabel()
6
Gets the label of this button.
<T extends EventListener> T[] getListeners(Class<T> listenerType)
7
Returns an array of all the objects currently registered as FooListeners upon this Button.
Protected String paramString()
8
Returns a string representing the state of this Button.
Protected void processActionEvent(ActionEvent e)
9 Processes action events occurring on this button by dispatching them to any registered
ActionListener objects.
Protected void processEvent(AWTEvent e)
10
Processes events on this button.
Void removeActionListener(ActionListener l)
11 Removes the specified action listener so that it no longer receives action events from this
button.
Void setActionCommand(String command)
12
Sets the command name for the action event fired by this button.
Void setLabel(String label)
13 Sets the button's label to be the specified string.

import java.awt.*;
import java.applet.*;
public class ButtonDemo extends Frame
{
ButtonDemo()
{

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Button one=new Button("yes");
//one.setBounds(30,100,80,30);
Button two=new Button("no");
//two.setBounds(60,200,80,30);//
add(one);
add(two);
setSize(300,300);
setLayout(new FlowLayout());
setVisible(true);
}
public static void main(String []args)
{
ButtonDemo b=new ButtonDemo();
}
}

3.AWT CheckBox Class

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

Following is the declaration for java.awt.Checkbox class:

public class Checkbox


extends Component
implements ItemSelectable,Accessible

Class constructors

S.N. Constructor & Description


Checkbox()
1
Creates a check box with an empty string for its label.
Checkbox(String label)
2
Creates a check box with the specified label.
Checkbox(String label, Boolean state)
3
Creates a check box with the specified label and sets the specified state.
Checkbox(String label, Boolean state, CheckboxGroup group)
4 Constructs a Checkbox with the specified label, set to the specified state, and in the
specified check box group.
Checkbox(String label, CheckboxGroup group, Boolean state)
5 Creates a check box with the specified label, in the specified check box group, and set to
the specified state.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Class methods

S.N. Method & Description


Void addItemListener(ItemListener l)
1
Adds the specified item listener to receive item events from this check box.
Void addNotify()
2
Creates the peer of the Checkbox.
AccessibleContext getAccessibleContext()
3
Gets the AccessibleContext associated with this Checkbox.
CheckboxGroup getCheckboxGroup()
4
Determines this check box's group.
ItemListener[] getItemListeners()
5
Returns an array of all the item listeners registered on this checkbox.
String getLabel()
6
Gets the label of this check box.
<T extends EventListener>T[] getListeners(Class<T> listenerType)
7 Returns an array of all the objects currently registered as FooListeners upon this
Checkbox.
Object[] getSelectedObjects()
8 Returns an array (length 1) containing the checkbox label or null if the checkbox is not
selected.
Boolean getState()
9
Determines whether this check box is in the on or off state.
Protected String paramString()
10
Returns a string representing the state of this Checkbox.
Protected void processEvent(AWTEvent e)
11
Processes events on this check box.
Protected void processItemEvent(ItemEvent e)
12 Processes item events occurring on this check box by dispatching them to any registered
ItemListener objects.
Void removeItemListener(ItemListener l)
13 Removes the specified item listener so that the item listener no longer receives item events
from this check box.
Void setCheckboxGroup(CheckboxGroup g)
14
Sets this check box's group to the specified check box group.
Void setLabel(String label)
15
Sets this check box's label to be the string argument.
Void setState(Boolean state)
16
Sets the state of this check box to the specified state.

import java.awt.*;
import java.applet.*;
public class CheckBoxDemo extends Frame
{
CheckBoxDemo()
{
Checkbox c1=new Checkbox("apple");

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Checkbox c2=new Checkbox("mango");
Checkbox c3=new Checkbox("apple");
add(c1);
add(c2);
add(c3);
setSize(300,300);
setLayout(new FlowLayout());
setVisible(true);
}
public static void main(String []args)
{
CheckBoxDemo b=new CheckBoxDemo();
}
}

4. AWT CheckBoxGroup Class

Introduction

The CheckboxGroup class is used to group the set of checkbox.

Class declaration

Following is the declaration for java.awt.CheckboxGroup class:

public class CheckboxGroup


extends Object
implements Serializable

Class constructors

S.N. Constructor & Description


CheckboxGroup() ()
1
Creates a new instance of CheckboxGroup.

Class methods

S.N. Method & Description


Checkbox getCurrent()
1
Deprecated. As of JDK version 1.1, replaced by getSelectedCheckbox().
Checkbox getSelectedCheckbox()
2
Gets the current choice from this check box group.
Void setCurrent(Checkbox box)
3
Deprecated. As of JDK version 1.1, replaced by setSelectedCheckbox(Checkbox).
Void setSelectedCheckbox(Checkbox box)
4
Sets the currently selected check box in this group to be the specified check box.
String toString()
5 Returns a string representation of this check box group, including the value of its current
selection.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


import java.awt.*;
import java.applet.*;
public class CheckBoxGroupDemo extends Frame
{
CheckBoxGroupDemo()
{
CheckboxGroup cbg=new CheckboxGroup();
Checkbox c1=new Checkbox("apple",cbg,true);
Checkbox c2=new Checkbox("mango",cbg,false);
Checkbox c3=new Checkbox("grape",cbg,false);
add(c1);
add(c2);
add(c3);
setSize(300,300);
setLayout(new FlowLayout());
setVisible(true);
}
public static void main(String []args)
{
CheckBoxGroupDemo b=new CheckBoxGroupDemo();
}
}

5.AWT List Class(choice list)

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

Following is the declaration for java.awt.List class:

public class List


extends Component
implements ItemSelectable, Accessible

Class constructors

S.N. Constructor & Description


List()
1
Creates a new scrolling list.
List(int rows)
2
Creates a new scrolling list initialized with the specified number of visible lines.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


List(int rows, Boolean multipleMode)
3
Creates a new scrolling list initialized to display the specified number of rows.

Class methods

<T extends EventListener> T[] getListeners(Class<T> listenerType)


Returns an array of all the objects currently registered as FooListeners upon this List.
S.N. Method & Description
Void add(String item)
1
Adds the specified item to the end of scrolling list.
Void add(String item, int index)
2
Adds the specified item to the the scrolling list at the position indicated by the index.
Void addActionListener(ActionListener l)
3
Adds the specified action listener to receive action events from this list.
Void addItem(String item)
4
Deprecated. replaced by add(String).
Void addItem(String item, int index)
5
Deprecated. replaced by add(String, int).
Void addItemListener(ItemListener l)
6
Adds the specified item listener to receive item events from this list.
Void addNotify()
7
Creates the peer for the list.
Boolean allowsMultipleSelections()
8
Deprecated. As of JDK version 1.1, replaced by isMultipleMode().
Void clear()
9
Deprecated. As of JDK version 1.1, replaced by removeAll().
Int countItems()
10
Deprecated. As of JDK version 1.1, replaced by getItemCount().
Void delItem(int position)
11
Deprecated. replaced by remove(String) and remove(int).
Void delItems(int start, int end)
12 Deprecated. As of JDK version 1.1, Not for public use in the future. This method is
expected to be retained only as a package private method.
Void deselect(int index)
13
Deselects the item at the specified index.
AccessibleContext getAccessibleContext()
14
Gets the AccessibleContext associated with this List.
ActionListener[] getActionListeners()
15
Returns an array of all the action listeners registered on this list.
String getItem(int index)
16
Gets the item associated with the specified index.
Int getItemCount()
17
Gets the number of items in the list.
ItemListener[] getItemListeners()
18
Returns an array of all the item listeners registered on this list.
String[] getItems()
19
Gets the items in the list.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Dimension getMinimumSize()
20
Determines the minimum size of this scrolling list.
Dimension getMinimumSize(int rows)
21
Gets the minumum dimensions for a list with the specified number of rows.
Dimension getPreferredSize()
22
Gets the preferred size of this scrolling list.
Dimension getPreferredSize(int rows)
23
Gets the preferred dimensions for a list with the specified number of rows.
Int getRows()
24
Gets the number of visible lines in this list.
Int getSelectedIndex()
25
Gets the index of the selected item on the list,
int[] getSelectedIndexes()
26
Gets the selected indexes on the list.
String getSelectedItem()
27
Gets the selected item on this scrolling list.
String[] getSelectedItems()
28
Gets the selected items on this scrolling list.
Object[] getSelectedObjects()
29
Gets the selected items on this scrolling list in an array of Objects.
Int getVisibleIndex()
30
Gets the index of the item that was last made visible by the method makeVisible.
Boolean isIndexSelected(int index)
31
Determines if the specified item in this scrolling list is selected.
Boolean isMultipleMode()
32
Determines whether this list allows multiple selections.
Boolean isSelected(int index)
33
Deprecated. As of JDK version 1.1, replaced by isIndexSelected(int).
Void makeVisible(int index)
34
Makes the item at the specified index visible.
Dimension minimumSize()
35
Deprecated. As of JDK version 1.1, replaced by getMinimumSize().
Dimension minimumSize(int rows)
36
Deprecated. As of JDK version 1.1, replaced by getMinimumSize(int).
Protected String paramString()
37
Returns the parameter string representing the state of this scrolling list.
Dimension preferredSize()
38
Deprecated. As of JDK version 1.1, replaced by getPreferredSize().
Dimension preferredSize(int rows)
39
Deprecated. As of JDK version 1.1, replaced by getPreferredSize(int).
Protected void processActionEvent(ActionEvent e)
40 Processes action events occurring on this component by dispatching them to any registered
ActionListener objects.
Protected void processEvent(AWTEvent e)
41
Processes events on this scrolling list.
Protected void processItemEvent(ItemEvent e)
42 Processes item events occurring on this list by dispatching them to any registered
ItemListener objects.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Void remove(int position)
43
Removes the item at the specified position from this scrolling list.
Void remove(String item)
44
Removes the first occurrence of an item from the list.
Void removeActionListener(ActionListener l)
45 Removes the specified action listener so that it no longer receives action events from this
list.
Void removeAll()
46
Removes all items from this list.
Void removeItemListener(ItemListener l)
47
Removes the specified item listener so that it no longer receives item events from this list.
Void removeNotify()
48
Removes the peer for this list.
Void replaceItem(String newValue, int index)
49
Replaces the item at the specified index in the scrolling list with the new string.
Void select(int index)
50
Selects the item at the specified index in the scrolling list.
Void setMultipleMode(Boolean b)
51
Sets the flag that determines whether this list allows multiple selections.
Void setMultipleSelections(Boolean b)
52
Deprecated. As of JDK version 1.1, replaced by setMultipleMode(boolean)

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)
{

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


ListDemo b=new ListDemo();
}
}

6.AWT TextField Class

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

Following is the declaration for java.awt.TextField class:

public class TextField


extends TextComponent

Class constructors

S.N. Constructor & Description


TextField()
1
Constructs a new text field.
TextField(int columns)
2
Constructs a new empty text field with the specified number of columns.
TextField(String text)
3
Constructs a new text field initialized with the specified text.
TextField(String text, int columns)
4 Constructs a new text field initialized with the specified text to be displayed, and wide
enough to hold the specified number of columns.

Class methods

S.N. Method & Description


Void addActionListener(ActionListener l)
1
Adds the specified action listener to receive action events from this text field.
Void addNotify()
2
Creates the TextField's peer.
Boolean echoCharIsSet()
3
Indicates whether or not this text field has a character set for echoing.
AccessibleContext getAccessibleContext()
4
Gets the AccessibleContext associated with this TextField.
ActionListener[] getActionListeners()
5
Returns an array of all the action listeners registered on this textfield.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Int getColumns()
6
Gets the number of columns in this text field.
Char getEchoChar()
7
Gets the character that is to be used for echoing.
<T extends EventListener> T[] getListeners(Class<T> listenerType)
8
Returns an array of all the objects currently registered as FooListeners upon this TextField.
Dimension getMinimumSize()
9
Gets the minumum dimensions for this text field.
Dimension getMinimumSize(int columns) Gets the minumum dimensions for a text
10
field with the specified number of columns.
Dimension getPreferredSize()
11
Gets the preferred size of this text field.
Dimension getPreferredSize(int columns)
12
Gets the preferred size of this text field with the specified number of columns.
Dimension minimumSize()
13
Deprecated. As of JDK version 1.1, replaced by getMinimumSize().
Dimension minimumSize(int columns)
14
Deprecated. As of JDK version 1.1, replaced by getMinimumSize(int).
Protected String paramString()
15
Returns a string representing the state of this TextField.
Dimension preferredSize()
16
Deprecated. As of JDK version 1.1, replaced by getPreferredSize().
Dimension preferredSize(int columns)
17
Deprecated. As of JDK version 1.1, replaced by getPreferredSize(int).
Protected void processActionEvent(ActionEvent e)
18 Processes action events occurring on this text field by dispatching them to any registered
ActionListener objects.
Protected void processEvent(AWTEvent e)
19
Processes events on this text field.
Void removeActionListener(ActionListener l)
20 Removes the specified action listener so that it no longer receives action events from this
text field.
Void setColumns(int columns)
21
Sets the number of columns in this text field.
Void setEchoChar(char c)
22
Sets the echo character for this text field.
Void setEchoCharacter(char c)
23
Deprecated. As of JDK version 1.1, replaced by setEchoChar(char).
Void setText(String t)
24
Sets the text that is presented by this text component to be the specified text.

import java.awt.*;
public class TextFieldDemo extends Frame
{
TextFieldDemo()
{
Label namep=new Label("Name",Label.RIGHT);

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Label passp=new Label("Password:",Label.RIGHT);
TextField name=new TextField(12);
TextField pass=new TextField(8);
pass.setEchoChar('?');
add(namep);add(name);
add(passp);

add(pass);
setSize(300,300);
setLayout(new FlowLayout());
setVisible(true);
}
public static void main(String []args)
{
TextFieldDemo tf=new TextFieldDemo();
}
}

7. AWT TextArea Class

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

Following is the declaration for java.awt.TextArea class:

public class TextArea


extends TextComponent

Field

Following are the fields for java.awt.TextArea class:

● 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

S.N. Constructor & Description

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


TextArea()
1
Constructs a new text area with the empty string as text.
TextArea(int rows, int columns)
2 Constructs a new text area with the specified number of rows and columns and the empty
string as text.
TextArea(String text)
3
Constructs a new text area with the specified text.
TextArea(String text, int rows, int columns)
4 Constructs a new text area with the specified text, and with the specified number of rows
and columns.
TextArea(String text, int rows, int columns, int scrollbars)
5 Constructs a new text area with the specified text, and with the rows, columns, and scroll
bar visibility as specified.

Class methods

S.N. Method & Description


Void addNotify()
1
Creates the TextArea's peer.
Void append(String str)
2
Appends the given text to the text area's current text.
Void appendText(String str)
3
Deprecated. As of JDK version 1.1, replaced by append(String).
AccessibleContext getAccessibleContext()
4
Returns the AccessibleContext associated with this TextArea.
Int getColumns()
5
Returns the number of columns in this text area.
Dimension getMinimumSize()
6
Determines the minimum size of this text area.
Dimension getMinimumSize(int rows, int columns)
7 Determines the minimum size of a text area with the specified number of rows and
columns.
Dimension getPreferredSize()
8
Determines the preferred size of this text area.
Dimension getPreferredSize(int rows, int columns)
9 Determines the preferred size of a text area with the specified number of rows and
columns.
Int getRows()
10
Returns the number of rows in the text area.
Int getScrollbarVisibility()
11
Returns an enumerated value that indicates which scroll bars the text area uses.
Void insert(String str, int pos)
12
Inserts the specified text at the specified position in this text area.
Void insertText(String str, int pos)
13
Deprecated. As of JDK version 1.1, replaced by insert(String, int).
Dimension minimumSize()
14
Deprecated. As of JDK version 1.1, replaced by getMinimumSize().

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Dimension minimumSize(int rows, int columns)
15
Deprecated. As of JDK version 1.1, replaced by getMinimumSize(int, int).
Protected String paramString()
16
Returns a string representing the state of this TextArea.
Dimension preferredSize()
17
Deprecated. As of JDK version 1.1, replaced by getPreferredSize().
Dimension preferredSize(int rows, int columns)
18
Deprecated. As of JDK version 1.1, replaced by getPreferredSize(int, int).
Void replaceRange(String str, int start, int end)
19 Replaces text between the indicated start and end positions with the specified replacement
text.
Void replaceText(String str, int start, int end)
20
Deprecated. As of JDK version 1.1, replaced by replaceRange(String, int, int).
Void setColumns(int columns)
21
Sets the number of columns for this text area.
Void setRows(int rows)
22
Sets the number of rows for this text area.

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();
}
}

8. AWT Choice Class

Introduction

Choice control is used to show pop up menu of choices. Selected choice is shown on the top of
the menu.

Class declaration

Following is the declaration for java.awt.Choice class:

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


public class Choice
extends Component
implements ItemSelectable, Accessible

Class constructors

S.N. Constructor & Description


Choice()
1
Creates a new choice menu.

Class methods

S.N. Method & Description


Void add(String item)
1
Adds an item to this Choice menu.
Void addItem(String item)
2
Obsolete as of Java 2 platform v1.1.
Void addItemListener(ItemListener l)
3
Adds the specified item listener to receive item events from this Choice menu.
Void addNotify()
4
Creates the Choice's peer.
Int countItems()
5
Deprecated. As of JDK version 1.1, replaced by getItemCount().
AccessibleContext getAccessibleContext()
6
Gets the AccessibleContext associated with this Choice.
String getItem(int index)
7
Gets the string at the specified index in this Choice menu.
Int getItemCount()
8
Returns the number of items in this Choice menu.
ItemListener[] getItemListeners()
9
Returns an array of all the item listeners registered on this choice.
<T extends EventListener> T[] getListeners(Class<T> listenerType)
10
Returns an array of all the objects currently registered as FooListeners upon this Choice.
Int getSelectedIndex()
11
Returns the index of the currently selected item.
String getSelectedItem()
12
Gets a representation of the current choice as a string.
Object[] getSelectedObjects()
13
Returns an array (length 1) containing the currently selected item.
Void insert(String item, int index)
14
Inserts the item into this choice at the specified position.
Protected String paramString()
15
Returns a string representing the state of this Choice menu.
Protected void processEvent(AWTEvent e)
16
Processes events on this choice.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Protected void processItemEvent(ItemEvent e)
17 Processes item events occurring on this Choice menu by dispatching them to any registered
ItemListener objects.
Void remove(int position)
18
Removes an item from the choice menu at the specified position.
Void remove(String item)
19
Removes the first occurrence of item from the Choice menu.
Void removeAll()
20
Removes all items from the choice menu.
Void removeItemListener(ItemListener l)
21 Removes the specified item listener so that it no longer receives item events from this
Choice menu.
Void select(int pos)
22
Sets the selected item in this Choice menu to be the item at the specified position.
Void select(String str)
23 Sets the selected item in this Choice menu to be the item whose name is equal to the
specified string.

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();
}
}

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


LayoutManagers:

LayoutManagers:

The LayoutManagers are used to arrange components in a particular manner. LayoutManager


is an interface that is implemented by all the classes of layout managers. There are following
classes that represents the layout managers:

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:

1. public static final int NORTH


2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

Constructors of BorderLayout class:

● 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.*;

public class Border {


Frame f;
Border(){
f=new Frame();

Button b1=new Button("NORTH");;


Button b2=new Button("SOUTH");;
Button b3=new Button("EAST");;
Button b4=new Button("WEST");;
Button b5=new Button("CENTER");;

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);

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.

Constructors of GridLayout class:

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);

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


21.
22. f.setLayout(new GridLayout(3,3));
23. //setting grid layout of 3 rows and 3 columns
24.
25. f.setSize(300,300);
26. f.setVisible(true);
27. }
28. public static void main(String[] args) {
29. new MyGridLayout();
30. }
31. }

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.

Fields of FlowLayout class:

1. public static final int LEFT


2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING

Constructors of FlowLayout class:

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.*;

public class MyFlowLayout{


Frame f;
MyFlowLayout(){
f=new Frame();

Button b1=new Button("1");


Button b2=new Button("2");
Button b3=new Button("3");

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Button b4=new Button("4");
Button b5=new Button("5");

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.

Constructors of CardLayout class:

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.

Commonly used methods of CardLayout class:

● 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();

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


12. card=new CardLayout(40,30);
13. //create CardLayout object with 40 hor space and 30 ver space
14. c.setLayout(card);
15.
16. b1=new JButton("Apple");
17. b2=new JButton("Boy");
18. b3=new JButton("Cat");
19. b1.addActionListener(this);
20. b2.addActionListener(this);
21. b3.addActionListener(this);
22. c.add("a",b1);c.add("b",b2);c.add("c",b3);
23. }
24. public void actionPerformed(ActionEvent e) {
25. card.next(c);
26. }
27.
28. public static void main(String[] args) {
29. CardLayoutExample cl=new CardLayoutExample();
30. cl.setSize(400,400);
31. cl.setVisible(true);
32. cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
33. }
34. }

Output:flow layout and border layout

Output:Grid Layout and Card layout

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Menu Hiearchy

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.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Java AWT MenuItem and Menu

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.

AWT MenuItem class declaration

1. public class MenuItem extends MenuComponent implements Accessible

AWT Menu class declaration

1. public class Menu extends MenuItem implements MenuContainer, Accessible

Java AWT MenuItem and Menu Example

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. {

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


28. new MenuExample();
29. }
30. }

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.

JOptionPane class declaration

1. public class JOptionPane extends JComponent implements Accessible

Common Constructors of JOptionPane class

Constructor Description

JOptionPane() It is used to create a JOptionPane with a test message.

JOptionPane(Object message) It is used to create an instance of JOptionPane to display a me

JOptionPane(Object message, int It is used to create an instance of JOptionPane to display a


messageType message type and default options.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Common Methods of JOptionPane class

Methods Description

JDialog createDialog(String title) It is used to create and return a new


parentless JDialog with the specified
title.

static void showMessageDialog(Component It is used to create an information-


parentComponent, Object message) message dialog titled "Message".

static void showMessageDialog(Component It is used to create a message dialog with


parentComponent, Object message, String given title and messageType.
title, int messageType)

static int showConfirmDialog(Component It is used to create a dialog with the


parentComponent, Object message) options Yes, No and Cancel; with the
title, Select an Option.

static String showInputDialog(Component It is used to show a question-message


parentComponent, Object message) dialog requesting input from the user
parented to parentComponent.

void setInputValue(Object newValue) It is used to set the input value that was
selected or input by the user.

Java JOptionPane Example: showMessageDialog()

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. }

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


Output:

Java JOptionPane Example: showMessageDialog()

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:

Java JOptionPane Example: showInputDialog()

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. }

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


8. public static void main(String[] args) {
9. new OptionPaneExample();
10. }
11. }

Output:

Java JOptionPane Example: showConfirmDialog()

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:

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


TEXT BOOKS:
1.”Java The Complete Reference”, Herbert Schildt, MC GRAW HILL Education, 9 th
Edition,2016.

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

*********** END OF UNIT-5 *******************

BRINDAVAN INSTITUTE OF TECHNOLOGY AND SCIENCE (BITS-KNL)

Department of Computer Science & Engineering

JAVA PROGRAMMING QUESTION BANK

UNIT-1

1. Explain the key attributes of Object Oriented Programming?


2. Explain the class and object with simple example?
3. Explain about the different operators using in java?
4. Define an array? Explain the different types of arrays with example?
5. Write a program to calculate matrix multiplication?
6. What is string? How define a string? Explain about string handling functions?

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


7. Explain about the ways of how to compare Strings in java?

UNIT-2

1. Explain about types Constructors? What are usages of using constructors?


2. Explain about Access modifiers in java with example?
3. Explain about how to pass objects as arguments to methods?
4. Explain about method overloading and constructor overloading with example?
5. Explain about nested and inner classes?
6. Explain the usage of static keyword with example?
7. What is inheritance process? Explain its multilevel hierarchy?
8. Explain the usage of super keyword with example?
9. What is method overriding? How to restrict the method overriding?
10. Explain the usage of abstract keyword?
11. Explain the usage of final keyword and explain with example?
12. Explain how to define and import an interface with example?
UNIT-3
1. Define an exception? Explain the types of exceptions and define its hierarchy?
2. Explain about multiple catch clauses with example?
3. Explain the concept of nesting try blocks with example?
4. Define an exception? Explain how to handle an exception with examples?
5. Explain about usage of finally, throw, and throws keywords with examples?
6. Explain how to define User defined exceptions?
7. Explain the various ways of defining streams?
8. Explain how read and write files using byte streams?
9. Explain how read and write binary data?
10. Explain how to perform File I/O using character streams?
11. Explain the usage of Wrapper classes? Explain and its types?

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

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


UNIT-I

1. Explain about the key attributes of java programming.


2. Write a Java program to find the sum and product of two matrices.
3. Explain the different control statements with an example program.
4. Write a Java program to find the roots of a quadratic equation.
5. Write a Java program to generate the Fibonacci sequence.
6. Write a Java program to sort the given the names.
7. Explain about the different Java key words and Identifiers.

UNIT-II

1. What is the constructor? Explain about constructor overloading.


2. Describe the passing objects and arguments to the methods in Java.
3. Write short notes on the keywords abstract and final
4. Discuss how to create and implement the infterfaces.
5. Write a java program to demonstrate multi-level hierarchy.
6. Explain how to define and implement package.
7. Explain about nested and inner classes.
8. What is meant by method overloading? Explain with an example.

UNIT-III

1. Explain the following exceptions with the help of examples:


(a) ArithmeticException
(b) NullPointerException
(c) NumberFormatException
2. With the help of an example, explain multithreading by extending thread class.
3. Implementing Runnable interface and extending thread, which method you prefer for
multithreading and why.
4. In JAVA, is exception handling implicit or explicit or both. Explain with the help of
example java programs.
5. Define multithreading. Give an example of an application that needs multithreading
6. How multithreading in single processor system is different from multithreading in
multiprocessor system. Explain
7. Explain throws statement in Java with the help of an example program.
8. What is the difference between throw and throws statement.
9. Explain how threads with different priorities execute in environment which supports
priorities and which doesn’t support priorities.
10. What are the functions available in java related to priority.

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.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


3. How using different fonts improves the user interface
4. What are the methods supported by Key Listener interface and Mouse Listener
interface. Explain each of them with examples.
5. How event driven programming is different from Procedure oriented programming
6. Give overview of Java’s event handling mechanism.
7. Define Graphics context. How do you obtain graphics context
8. Explain in brief different drawing functions of Java?
9. What is Delegation Event model? Explain it. What are its benefits
10. Define Event? Give examples of events. Define event handler. How it handles events.

UNIT-V

1. What is the use of JPasswordField? Explain with an aid of an application program


2. What are the differences between JPopupMenu and JMenu?
3. Differentiate following with suitable examples:
(a) Frame, JFrame (b) Applet, JApplet (c) Menu, Jmenu
4. Explain the following:
(a) Creating an applet (b) Passing parameters to applets
(c) Adding graphics and colors to applets
5. Explain various methods of Applet class with necessary examples.
6. What are containers? List various containers. Explain the usage of JPanel with
example.
7. What is JFC? Explain the differences between JTextArea, JTextComponent,
JTextField with examples.
8. What do you mean by URL? How to create an URL? Explain several methods
provided by URL? Give appropriate examples.
9. (a) What are accessor methods
(b) How will you create strings and stringbuffers? How will you modify them?
10. (a) Discuss briefly about the following: TCP, UDP, URL
(b) What is InetAddress? How to create an InetAddress? What is its use?
11. Define sockets. Use socket programming to design a client/server application that takes
the password as input and checks whether it is correct. The program should print the
appropriate message.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


PREVIOUS QUESTION PAPERS

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.

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


UNIT - V
10 (a) List and explain various AWT components in java.
(b) Explain about event delegation model.
OR
11 Explain the following layout managers.
(a) Border layout.
(b) Grid layout.
(c) Flow layout

B.Tech II Year II Semester (R13) Supplementary Examinations May/June 2017


JAVA PROGRAMMING
(Common to IT & CSE)
Time: 3 hours Max. Marks: 70
PART - A
(Compulsory Question)
*****
1 Answer the following: (10 X 02 = 20 Marks)
(a) What is overridden method?
(b) What are the logical operators?
(c) What is operator?
(d) What is function overloading?
(e) Define switch statement.
(f) What is overloading constructor?
(g) Define nested loops.
(h) What are try and catch keywords in java? Explain.
(i) What is synchronization?
(j) What is deadlock?

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

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY


7 (a) Explain reading and writing strings in java with an example program.
(b) Explain reading and writing files in java.

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********************

SJCET JAVA PROGRAMMING Y.NARASIMHA REDDY

You might also like