Java Notes 2021

Download as pdf or txt
Download as pdf or txt
You are on page 1of 125

Programming in Java

Unit – I

 Introduction: Java is a high-level programming language originally developed by James Gosling at


Sun Microsystems and released in 1995 and later acquired by Oracle Corporation. The original name of
JAVA is OAK (which is a tree name). In the year 1995, OAK was revised and developed software called
JAVA (which is a coffee seed name). It is one of the most used programming languages. Java runs on a
variety of platforms, such as Windows, Mac,OS, and the various versions of UNIX.
JAVA released to the market in three categories J2SE (JAVA 2 Standard Edition), J2EE (JAVA 2
Enterprise Edition) and J2ME (JAVA 2 Micro/Mobile Edition).

i. J2SE is basically used for developing client side applications/programs.


ii. J2EE is used for developing server side applications/programs.
iii. J2ME is used for developing server side applications/programs.

 Java versions

Version Name Code Name Release Date


1. JDK 1.0 Oak January 1996
2. JDK 1.1 (none) February 1997
3. J2SE 1.2 Playground December 1998
4. J2SE 1.3 Kestrel May 2000
5. J2SE 1.4 Merlin February 2002
6. J2SE 5.0 Tiger September 2004
7. Java SE 6 Mustang December 2006
8. Java SE 7 Dolphin July 2011
9. Java SE 8 Spider March 2014
10. Java SE 9 September, 21st 2017
11. Java SE 10 March, 20th 2018

 Java Essentials:
Java produces applets (browser-run programs), which facilitate graphical user interface (GUI) and
object interaction by internet users. Prior to java applets, Web pages were typically static and non-
interactive. Java applets have diminished in popularity with the release of competing products, such as
Adode Flash and Microsoft Silver light.
Java applets run in a Web browser with Java Virtual Machine (JVM), which translates Java byte
code into native processor instructions and allows indirect OS or platform program execution.JVM
provides the majority of components needed to run byte code, which is usually smaller than executable
programs written through other programming languages. Byte code cannot run if a system lacks required
JVM.
Java program development requires a Java software development kit(SDK) that typically includes a
compiler, interpreter, documentation generator and other tools used to produce a complete application.
Development time may be accelerated through the use of integrated development environments
(IDE)-such as JBuilder, Netbeans, Eclipse or JCreator. IDEs facilitate the development of GUIs, which
include buttons, text boxes, panels, frames, scrollbars and other objects via drag-and-drop and point-and-
click actions.

Programming in Java P.SowmyaSree Page 1


Java Essentials include the following:
1. Programming Environment:
An ideal Java environment is critical to write Java code with ease and personal convenience.
We recommend using the Eclipse IDE from the very beginning for all your Java as well as Android
related programming. Android App Developers must have programming environment i.e. Eclipse.

2. Primitive Data types:


Data types form the very basic and the core of programming with java. It’s important to
learn in great detail about almost all data types that come in handy in day-to-day programming.
They include character type, int type, float type, boolean etc.

3. Strings:
Strings also form an essential part of java programming. Implementations of concatenation,
searching parts of string etc. are an important part of Java and prove on to be highly useful
programming tools in the long run.

4. Selection Control Structures:


Conditional statements like if, if..else, switch etc. are essential when it comes to carrying out
operations when certain conditions are fulfilled. They too form the crux of carrying out
programming in any language.

5. Methods:
There are many instances when similar tasks need to be carried out multiple times within a
program. Functions or methods come handy here. You will use hundreds of functions when
programming in any language hence it’s crucial to become adept at using them.

6. Classes:
In the real world, you will find many similar objects of the same kind. Java is essentially an
object-oriented language, an aspect of it which differentiates it from many low-level programming
languages such as C. Let’s take the example of a bicycle in the real world. Bicycles share properties
of having two wheels, a seat etc. We can say that someone’s bicycle is an instance of the class of
objects, bicycles. Even when programming in Java, you might have to create classes that contain
similar attributes and functions within them. Objects of that class can be called in a variety of
situations to make programming efficient, simpler and more concise.

7. Inheritance, Interfaces and Abstract Classes:


Objects define their interaction with the outside world through the methods that they explose.
Methods form the object’s interface with the outside world; the buttons on the front of your
television set for example, are the interface between you and the electrical wiring on the other side
of its plastic casing. You press the “power” button to turn the television on and off. In its most
common form, an interface is a group of related methods with empty bodies. A bicycle’s behavior,
if specified as an interface, might appear as follows:
interface Bicycle
{
void changeGear(int newValue);
void speedup(int increment);
void apply Brakes(int decrement);}

Programming in Java P.SowmyaSree Page 2


8. Arrays:
An array is a container object that holds a fixed number of values of a single type. They are
important in storing data of a particular type and are highly convenient when accessing data.

 JVM

JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't
physically exist. It is a specification that provides a runtime environment in which Java bytecode can be
executed. It can also run those programs which are written in other languages and compiled to Java
bytecode.

JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are platform
dependent because the configuration of each OS is different from each other. However, Java is platform
independent. There are three notions of the JVM: specification, implementation, and instance.

The JVM performs the following main tasks:

o Loads code
o Verifies code
o Executes code
o Provides runtime environment

 JRE

JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java Runtime
Environment is a set of software tools which are used for developing Java applications. It is used to provide
the runtime environment. It is the implementation of JVM. It physically exists. It contains a set of libraries
+ other files that JVM uses at runtime.

The implementation of JVM is also actively released by other companies besides Sun Micro Systems.

 JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software development
environment which is used to develop Java applications and applets. It physically exists. It contains JRE +
development tools.

JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation:

Standard Edition Java Platform


Enterprise Edition Java Platform
Micro Edition Java Platform
The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc), etc. to
complete the development of a Java Application.

Programming in Java P.SowmyaSree Page 3


 Difference between Java and C++

Java C++

Java is pure object oriented programming C++ is semi object oriented language because
language. We can't design and develop our we can design and develop our programs and
programs and applications without object. applications, with and without object.

Java is Dynamic, Java allocates memory at run- C++ is static, C++ allocates memory at
time. compile-time.

Java doesn't support pointers, goto statement, C++ does support pointers, goto statement,
operator overloading, templates, etc. operator overloading, templates.

Java doesn't support multiple inheritance. Java


C++ does support multiple inheritance.
uses interface for multiple inheritance.

C++ does support destructors, which is


Java supports automatic garbage collection. Java
automatically invoked when the object goes
does not support destructors as C++ does.
out of scope.

Java does not support default argument value. C++ does support default argument value.

C++ has no built in support for threads.


Java has built in support for threads. Instead, c++ relies entirely upon the operating
system to provide this threads.

Java compiler converts source code into byte C++ generates object code and the same code
code, which is platform independent. may not run on different platforms.

 Java Features

A list of most important features of Java language is given below

1. Simple
2. Object-Oriented

Programming in Java P.SowmyaSree Page 4


3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic

1. Simple

Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to Sun, Java
language is a simple programming language because:

o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit pointers,
operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic Garbage
Collection in Java.

2. Object-oriented

Java is an object-oriented programming language. Everything in Java is an object. Object-oriented means


we organize our software as a combination of different types of objects that incorporates both data and
behavior.

Object-oriented programming (OOPs) is a methodology that simplifies software development and


maintenance by providing some rules.

Basic concepts of OOPs are:

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

Programming in Java P.SowmyaSree Page 5


3. Platform Independent
Java is platform independent because it is different from other languages like C, C++, etc. which
are compiled into platform specific machines while Java is a write once, run anywhere language. A
platform is the hardware or software environment in which a program runs.
There are two types of platforms software-based and hardware-based. Java provides a software-based
platform.

The Java platform differs from most other platforms in the sense that it is a software-based platform that
runs on the top of other hardware-based platforms. It has two components:

1. Runtime Environment
2. API(Application Programming Interface)

Java code can be run on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS, etc. Java
code is compiled by the compiler and converted into bytecode. This bytecode is a platform-independent
code because it can be run on multiple platforms, i.e., Write Once and Run Anywhere(WORA).

4. Secured

Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because:

o No explicit pointer
o Java Programs run inside a virtual machine sandbox

o Classloader: Classloader in Java is a part of the Java Runtime Environment(JRE) which is used to
load Java classes into the Java Virtual Machine dynamically. It adds security by separating the
package for the classes of the local file system from those that are imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate access right to
objects.
o Security Manager: It determines what resources a class can access such as reading and writing to
the local disk.

Java language provides these securities by default. Some security can also be provided by an application
developer explicitly through SSL, JAAS, Cryptography, etc.
Programming in Java P.SowmyaSree Page 6
5. Robust

Robust simply means strong. Java is robust because:

o It uses strong memory management.


o There is a lack of pointers that avoids security problems.
o There is automatic garbage collection in java which runs on the Java Virtual Machine to get rid of
objects which are not being used by a Java application anymore.
o There are exception handling and the type checking mechanism in Java. All these points make Java
robust.

6. Architecture-neutral

Java is architecture neutral because there are no implementation dependent features, for example, the size
of primitive types is fixed.

In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory
for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-bit architectures in
Java.

7. Portable

Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any
implementation.

8. High-performance

Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to
native code. It is still a little bit slower than a compiled language (e.g., C++). Java is an interpreted
language that is why it is slower than compiled languages, e.g., C, C++, etc.

9. Distributed

Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are
used for creating distributed applications. This feature of Java makes us able to access files by calling the
methods from any machine on the internet.
Programming in Java P.SowmyaSree Page 7
10. Multi-threaded

A thread is like a separate program, executing concurrently. We can write Java programs that deal with
many tasks at once by defining multiple threads. The main advantage of multi-threading is that it doesn't
occupy memory for each thread. It shares a common memory area. Threads are important for multi-media,
Web applications, etc.

11. Dynamic

Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded on demand.
It also supports functions from its native languages, i.e., C and C++.

Java supports dynamic compilation and automatic memory management (garbage collection).

 Creation and Execution of Programs

In this page, we will learn how to write the simple program of java. We can write a simple hello java
program easily after installing the JDK.

To create a simple java program, you need to create a class that contains the main method. Let's understand
the requirement first.

The requirement for Java Hello World Example


For executing any java program, you need to

o Install the JDK if you don't have installed it, download the JDK and install it.
o Set path of the jdk/bin directory.
o Create the java program
o Compile and run the java program

Creating Hello World Example

Let's create the hello java program: open the notepad and ttype the following code

1. class Simple
2. {
3. public static void main(String args[])
4. {
5. System.out.println("Hello Java");
6. }
7. }
save this file as Simple.java

Programming in Java P.SowmyaSree Page 8


To compile: javac Simple.java

To execute: java Simple

Output:

 Compilation Flow:

When we compile Java program using javac tool, java compiler converts the source code into byte code.

To write the simple program, you need to open notepad by start menu -> All Programs -> Accessories -
> notepad and write a simple program as displayed below:

Programming in Java P.SowmyaSree Page 9


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 the command prompt by start menu
-> All Programs -> Accessories -> command prompt

Parameters used in First Java Program

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

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


o public keyword is an access modifier which represents visibility. It means it is visible to all.
o static is a keyword. If we declare any method as static, it is known as the static method. The core
advantage of the static method is that there is no need to create an object to invoke the static

Programming in Java P.SowmyaSree Page 10


method. The main method is executed by the JVM, so it doesn't require to create an object to invoke
the main method. So it saves memory.
o void is the return type of the method. It means it doesn't return any value.
o main represents the starting point of the program.
o String[] args is used for command line argument. We will learn it later.
o System.out.println() is used to print statement. Here, System is a class, out is the object of
PrintStream class, println() is the method of PrintStream class. We will learn about the internal
working of System.out.println statement later.

Now let us understand what happens at runtime:


When a java program is compiled the Compiler will perform the following operations on the
program.
Class file

Class loader

Bytecode verifier

Interpreter

Runtime

Hardware
After the file is compiled successfully, byte code(.class file) is generated by the Compiler. When byte
code(.class file) is executed, the following steps are performed at runtime:

• Class loader which is in subsystem of JVM(Java Virtual Machine) loads the java class.
• Byte Code verifier checks the code fragments for illegal codes that can violate access right to the
object.
• Interpreter reads the byte code stream and then executes the instructions, step by step.

 Data Types:

Data types specify the different sizes and values that can be stored in the variable. There are two types of
data types in Java:

Programming in Java P.SowmyaSree Page 11


1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float
and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.

Primitive Data Types

In Java language, primitive data types are the building blocks of data manipulation. These are the most
basic data types available in Java language.

There are 8 types of primitive data types:

o boolean data type


o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double data type

Data Type Default Default size


Value

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

Programming in Java P.SowmyaSree Page 12


 Boolean Data Type

The Boolean data type is used to store only two possible values: true and false. This data type is used for
simple flags that track true/false conditions.

The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.

Example: Boolean one = false

 Byte Data Type

The byte data type is an example of primitive data type. It isan 8-bit signed two's complement integer. Its
value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and maximum value is 127. Its
default value is 0.

The byte data type is used to save memory in large arrays where the memory savings is most required. It
saves space because a byte is 4 times smaller than an integer. It can also be used in place of "int" data type.

Example: byte a = 10, byte b = -20

 Short Data Type

The short data type is a 16-bit signed two's complement integer. Its value-range lies between -32,768 to
32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its default value is 0.

The short data type can also be used to save memory just like byte data type. A short data type is 2 times
smaller than an integer.

Example: short s = 10000, short r = -5000

 int Data Type

The int data type is a 32-bit signed two's complement integer. Its value-range lies between - 2,147,483,648
(-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is - 2,147,483,648and maximum value
is 2,147,483,647. Its default value is 0.

The int data type is generally used as a default data type for integral values unless if there is no problem
about memory.

Example: int a = 100000, int b = -200000

Programming in Java P.SowmyaSree Page 13


 long Data Type

The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum value
is - 9,223,372,036,854,775,808and maximum value is 9,223,372,036,854,775,807. Its default value is 0.
The long data type is used when you need a range of values more than those provided by int.

Example: long a = 100000L, long b = -200000L

 float Data Type

The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is unlimited. It is
recommended to use a float (instead of double) if you need to save memory in large arrays of floating point
numbers. The float data type should never be used for precise values, such as currency. Its default value is
0.0F.

Example: float f1 = 234.5f

 double Data Type

The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is unlimited. The
double data type is generally used for decimal values just like float. The double data type also should never
be used for precise values, such as currency. Its default value is 0.0d.

Example: double d1 = 12.3

 char Data Type

The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or 0) to
'\uffff' (or 65,535 inclusive).The char data type is used to store characters.

Example: char letterA = 'A'

 Type Conversion ,casting

Type casting is when you assign a value of one primitive data type to another type.

In Java, there are two types of casting:

• Widening Casting (automatically) - converting a smaller type to a larger type size


byte -> short -> char -> int -> long -> float -> double

• Narrowing Casting (manually) - converting a larger type to a smaller size type


double -> float -> long -> int -> char -> short -> byte

Programming in Java P.SowmyaSree Page 14


 Widening Casting
Widening casting is done automatically when passing a smaller size type to a larger size type:

Example program

class MyClass
{
public static void main(String[] args)
{
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double

System.out.println(myInt);
System.out.println(myDouble);
}
}

Output:

D:\sowmya\javaprg>javac MyClass.java
D:\sowmya\javaprg>java MyClass
9
9.0

 Narrowing Casting
Narrowing casting must be done manually by placing the type in parentheses in front of the value:
Example program
public class MyClass1
{
public static void main(String[] args)
{
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int

System.out.println(myDouble);
System.out.println(myInt);
}
}

Output:

D:\sowmya\javaprg>javac MyClass1.java
D:\sowmya\javaprg>java MyClass1
9.78
9

Programming in Java P.SowmyaSree Page 15


 Conditional Statements
When a program breaks the sequential flow and jumps to another part of the code, it is called
branching. When the branching is based on a particular condition, it is known as conditional branching. If
branching takes place without any decision, it is known as unconditional branching.

 Branching Statements:

The Java if statement is used to test the condition. It checks boolean condition: true or false. There are
various types of if statement in java.

o if statement
o if-else statement
o if-else-if ladder
o nested if statement

Java if Statement

The Java if statement tests the condition. It executes


the if block if condition is true.

Syntax:

if(condition)
{
//code to be executed
}

Example program on if

public class IfExample


{
Output:
public static void main(String[] args)
{ D:\sowmya\javaprg>javac IfExample.java
int age=20; D:\sowmya\javaprg>java IfExample
if(age>18) Age is greater than 18
{
Programming in Java P.SowmyaSree Page 16
System.out.print("Age is greater than 18");
}
}
}

Java if-else Statement


The Java if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed.
Syntax:
if(condition)
{ //code if condition is true }
else
{ //code if condition is false }

Example program on if-else

//It is a program of odd and even number.


public class IfElseExample Output:
{
public static void main(String[] args) D:\sowmya\javaprg>javac IfElseExample.java
{ D:\sowmya\javaprg>java IfElseExample
int number=13; odd number

Programming in Java P.SowmyaSree Page 17


if(number%2==0)
{
System.out.println("even number");
}
else
{
System.out.println("odd number");
}
}
}

Java if-else-if ladder Statement

The if-else-if ladder statement executes one condition from multiple statements.

Syntax:

if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
...
else
{
//code to be executed if all the conditions are false
}

Programming in Java P.SowmyaSree Page 18


Example program on if-else-if ladder

//It is a program of grading system for fail, D grade, C grade, B grade, A grade and A+.
public class IfElseIfExample
{
public static void main(String[] args)
{
int marks=65;

if(marks<50)
{
System.out.println("fail");
}
else if(marks>=50 && marks<60)
{
System.out.println("D grade");
}
else if(marks>=60 && marks<70)
{ Output:
System.out.println("C grade");
D:\sowmya\javaprg>javac IfElseIfExample.java
}
D:\sowmya\javaprg>java IfElseIfExample
else if(marks>=70 && marks<80)
C grade
{
System.out.println("B grade");
}
else if(marks>=80 && marks<90)
{
System.out.println("A grade");
}
else if(marks>=90 && marks<100)
{
System.out.println("A+ grade");
}
else
{
System.out.println("Invalid!");
}
}
}

Java Nested if statement

The nested if statement represents the if block within another if block. Here, the inner if block condition
executes only when outer if block condition is true.

Syntax:

if(condition)

Programming in Java P.SowmyaSree Page 19


{
//code to be executed
if(condition)
{
//code to be executed
}
}

Programming in Java P.SowmyaSree Page 20


Example program on Nested if:

public class JavaNestedIfExample2 {


public static void main(String[] args) {
//Creating two variables for age and weight
int age=25;
int weight=48;
//applying condition on age and weight
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood");
} else{
System.out.println("You are not eligible to donate blood");
}
} else{
System.out.println("Age must be greater than 18");
}
} }
Output:

D:\sowmya\javaprg>javac JavaNestedIfExample2.java

D:\sowmya\javaprg>java JavaNestedIfExample2
You are not eligible to donate blood

 Java Switch Statement


The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder
statement. The switch statement works with byte, short, int, long, enum types, String and some wrapper
types like Byte, Short, Int, and Long. Since Java 7, you can use strings in the switch statement.

Syntax:
switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......

Programming in Java P.SowmyaSree Page 21


default:
code to be executed if all cases are not matched; }

Example Program on Switch statement

public class SwitchExample


{ Output:
public static void main(String[] args)
{ D:\sowmya\javaprg>javac SwitchExample.java
int number=20; D:\sowmya\javaprg>java SwitchExample
switch(number) 20
{

Programming in Java P.SowmyaSree Page 22


case 10: System.out.println("10");
break;
case 20: System.out.println("20");
break;
case 30: System.out.println("30");
break;
default:System.out.println("Not in 10, 20 or 30");
}
}
}

 Loops

In programming languages, loops are used to execute a set of instructions/functions repeatedly when some
conditions become true. There are three types of loops in java.

o for loop
o while loop
o do-while loop

Java For Loop

The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it
is recommended to use for loop.

There are three types of for loops in java.

o Simple For Loop


o For-each or Enhanced For Loop
o Labeled For Loop

Simple For Loop

A simple for loop is the same as C/C++. We can initialize the variable, check condition and
increment/decrement value. It consists of four parts:

1. Initialization: It is the initial condition which is executed once when the loop starts. Here, we can
initialize the variable, or we can use an already initialized variable. It is an optional condition.
2. Condition: It is the second condition which is executed each time to test the condition of the loop.
It continues execution until the condition is false. It must return boolean value either true or false. It
is an optional condition.
3. Statement: The statement of the loop is executed each time until the second condition is false.
4. Increment/Decrement: It increments or decrements the variable value. It is an optional condition.

Programming in Java P.SowmyaSree Page 23


Syntax:

for(initialization;condition;incr/decr)
{
//statement or code to be executed
}

Example program on simple for loop Output:

public class ForExample D:\sowmya\javaprg>javac ForExample.java


{
D:\sowmya\javaprg>java ForExample
1
public static void main(String[] args)
2
{ 3
for(int i=1;i<=10;i++) 4
{ 5
System.out.println(i); 6
} 7
}
8
9
}
10
Nested For Loop

If we have a for loop inside the another loop, it is known as nested for loop. The inner loop executes
completely whenever outer loop executes.

Syntax:

for(initialization;condition;incr/decr)
{
for(initialization;condition;incr/decr)
{
//statement or code to be executed
}
Statement
}

Example program on nested for loop

public class NestedForExample


{
public static void main(String[] args)
{
//loop of i
for(int i=1;i<=3;i++)

Programming in Java P.SowmyaSree Page 24


{
//loop of j
for(int j=1;j<=3;j++)
{
System.out.println(i+" "+j);
}//end of i
}//end of j
}
}

Output:

D:\sowmya\javaprg>javac NestedForExample.java
D:\sowmya\javaprg>java NestedForExample
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

for-each Loop

The for-each loop is used to traverse array or collection in java. It is easier to use than simple for loop
because we don't need to increment value and use subscript notation.

It works on elements basis not index. It returns element one by one in the defined variable.

Syntax:

for(Type var:array)
{
//code to be executed
}

Example program on for-each loop


public class ForEachExample
{
public static void main(String[] args)
{
//Declaring an array
int arr[]={12,23,44,56,78};

Programming in Java P.SowmyaSree Page 25


//Printing array using for-each loop
for(int i:arr)
{
System.out.println(i);
}
}
}

Output:

D:\sowmya\javaprg>javac ForEachExample.java
D:\sowmya\javaprg>java ForEachExample
12
23
44
56
78

Labeled For Loop

We can have a name of each Java for loop. To do so, we use label before the for loop. It is useful if we
have nested for loop so that we can break/continue specific for loop.

Usually, break and continue keywords breaks/continues the innermost for loop only.

Syntax:

labelname:
for(initialization;condition;incr/decr)
{
//code to be executed
}

Example Program on labeled loop

public class LabeledForExample


{
public static void main(String[] args)
{
//Using Label for outer and for loop
aa:
for(int i=1;i<=3;i++)
{
bb:

Programming in Java P.SowmyaSree Page 26


for(int j=1;j<=3;j++)
{
if(i==2&&j==2)
{
break aa;
}
System.out.println(i+" "+j);
}
}
}
}

Output:

D:\sowmya\javaprg>javac LabeledForExample.java
D:\sowmya\javaprg>java LabeledForExample
1 1
1 2
1 3
2 1

While Loop

The Java while loop is used to iterate a part of the program several times. If the number of iteration is not
fixed, it is recommended to use while loop.

Syntax:

while(condition)
{
//code to be executed
}
Output:
Example program on while loop
D:\sowmya\javaprg>javac WhileExample.java
D:\sowmya\javaprg>java WhileExample
class WhileExample 1
{ 2
3
public static void main(String[] args) 4
{ 5
6
int i=1; 7
while(i<=10) 8
{ 9
10
System.out.println(i);

Programming in Java P.SowmyaSree Page 27


i++;
}
}
}

do-while Loop

The Java do-while loop is used to iterate a part of the program several times. If the number of iteration is
not fixed and you must have to execute the loop at least once, it is recommended to use do-while loop.

The Java do-while loop is executed at least once because condition is checked after loop body.

Syntax:

do
{
//code to be executed
}while(condition);

Example on do-while Loop Output:

D:\sowmya\javaprg>javac DoWhileExample.java
class DoWhileExample D:\sowmya\javaprg>java DoWhileExample
{ 1
public static void main(String[] args) 2
3
{ 4
int i=1; 5
6
do{
7
System.out.println(i); 8
i++; 9
10
}while(i<=10);
}
}

 Classes

A class is an entity that determines how an object will behave and what the object will contain.
In other words, it is a blueprint or a set of instruction to build a specific type of object.
Syntax: class Declaration

class <class_name>
{
field;
method;

Programming in Java P.SowmyaSree Page 28


}

 Object:

An object is nothing but a self-contained component which consists of methods and properties to make a
particular type of data useful. Object determines the behavior of the class. When you send a message to an
object, you are asking the object to invoke or execute one of its methods.

From a programming point of view, an object can be a data structure, a variable or a function. It has a
memory location allocated. The object is designed as class hierarchies.

Syntax: object creation

ClassName ReferenceVariable = new ClassName();

Example program on class declaration and object creation:

class Student{
//defining fields
int id=15;//field or data member or instance variable
String name="Sowmya";
//creating main method inside the Student class
public static void main(String args[])
{
//Creating an object or instance
Student s1=new Student();//creating an object of Student
//Printing values of the object
System.out.println("id="+s1.id);//accessing member through reference variable
System.out.println("name="+s1.name);
}
}

Output:

D:\sowmya\javaprg>javac Student.java

D:\sowmya\javaprg>java Student
id=15
name=Sowmya

Programming in Java P.SowmyaSree Page 29


Unit – II
Chapter 1:

 Method Declaration and Invocation


A method is a collection of statements that perform some specific task and return the result to the caller. A
method can perform some specific task without returning anything. Methods allow us to reuse the code
without retyping the code.
Syntax: method declaration
modifier returnType nameOfMethod (Parameter List)
{
// method body
}
The syntax shown above includes −
• modifier − It defines the access type of the method and it is optional to use.
• returnType − Method may return a value.
• nameOfMethod − This is the method name. The method signature consists of the method name
and the parameter list.
• Parameter List − The list of parameters, it is the type, order, and number of parameters of a
method. These are optional, method may contain zero parameters.
• method body − The method body defines what the method does with the statements.

Method calling

For using a method, it should be called. There are two ways in which a method is called i.e., method
returns a value or returning nothing (no return value).

Example program on method creation and invocation

class Student
{
int rollno; Output:
String name;
void insertRecord(int r, String n) D:\sowmya\javaprg>javac TestStudent4.java
{ D:\sowmya\javaprg>java TestStudent4
rollno=r; 111 kiran
name=n; 222 Raju
}
void displayInformation()
{System.out.println(rollno+" "+name);}
}
class TestStudent4

Programming in Java P.SowmyaSree Page 30


{
public static void main(String args[])
{
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"kiran");
s2.insertRecord(222,"Raju");
s1.displayInformation();
s2.displayInformation();
}
}

 Method overloading:

If two or more method in a class have same name but different parameters, it is known as method
overloading. Overloading always occur in the same class

Method overloading is one of the ways through which java supports polymorphism. Method overloading
can be done by changing number of arguments or by changing the data type of arguments. If two or more
method have same name and same parameter list but differs in return type are not said to be overloaded
method

Example program on Method overloading:

class Calculate
{ Output:
void sum (int a, int b)
{ D:\sowmya\javaprg>javac Calculate.java
D:\sowmya\javaprg>java Calculate
System.out.println("sum is "+(a+b)) ;
sum is 13
} sum is 8.4
void sum (float a, float b)
{
System.out.println("sum is "+(a+b));
}
public static void main (String[] args)
{
Calculate cal = new Calculate();
cal.sum (8,5); //sum(int a, int b) is method is called.
cal.sum (4.6f, 3.8f); //sum(float a, float b) is called.
}
}

Programming in Java P.SowmyaSree Page 31


 Constructor:

In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is
created. At the time of calling constructor, memory for the object is allocated in the memory.

It is a special type of method which is used to initialize the object.

Every time an object is created using the new() keyword, at least one constructor is called.

Characteristics of constructor

• Constructor name class name must be same.


• Constructor doesn't return value.
• Constructor is invoked automatically, when the object of class is created.

Types of Constructor

• Default Constructor
• Parameterize Constructor

 Default Constructor:

A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax
<class_name>()
{
}

Example program on Default Constructor:


class Bike1
{
//creating a default constructor
Bike1() Output:
{
System.out.println("Bike is created"); D:\sowmya\javaprg>javac Bike1.java
} D:\sowmya\javaprg>java Bike1
public static void main(String args[]) Bike is created
{
//calling a default constructor
Bike1 b=new Bike1();
}
}

Programming in Java P.SowmyaSree Page 32


Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized
constructor.

Example program on parameterized constructor:

class Employee
{
int Id;
String Name;
int Age;
long Salary;

Employee(int i,String nm,int a,long s) // Parameterize Constructor


{
Id = i;
Name = nm;
Age = a;
Salary = s;
}

void PutData()
{
System.out.print("\n\tEmployee Id : "+Id);
System.out.print("\n\tEmployee Name : "+Name);
System.out.print("\n\tEmployee Age : "+Age);
System.out.print("\n\tEmployee Salary : "+Salary);
}

public static void main(String args[])


{

Employee E = new Employee(2,"Sumit",31,35000);


// Creating object and passing values to constructor.

E.PutData(); // Calling PutData()

}
}

Output:

D:\sowmya\javaprg>javac Employee.java
D:\sowmya\javaprg>java Employee

Employee Id : 2
Employee Name : Sumit
Employee Age : 31

Programming in Java P.SowmyaSree Page 33


Employee Salary : 35000

 Constructor Overloading:
In Java, a constructor is just like a method but without return type. It can also be overloaded like Java
methods.

Constructor overloading in Java is a technique of having more than one constructor with different
parameter lists. They are arranged in a way that each constructor performs a different task. They are
differentiated by the compiler by the number of parameters in the list and their types.

Example of Constructor Overloading


class Student
{
int Roll;
String Name;
double Marks;

Student(int R,String N,double M)


{
Roll = R;
Name = N;
Marks = M;
Output:
}

Student(String N,double M,int R) D:\sowmya\javaprg>javac ConstructorOverloading.java


{ D:\sowmya\javaprg>java ConstructorOverloading
Roll = R; Roll Name Marks
Name = N; 1 Kumar 78.53
Marks = M; 2 Sumit 89.42
}

void Display()
{
System.out.print("\n\t" + Roll+"\t" + Name+"\t" + Marks);
}
}

class ConstructorOverloading
{
public static void main(String[] args)
{
Student S1 = new Student(1,"Kumar",78.53);
Student S2 = new Student("Sumit",89.42,2);

System.out.print("\n\tRoll\tName\tMarks\n");
S1.Display();
S2.Display();
Programming in Java P.SowmyaSree Page 34
}
}

 Cleaning-up unused Objects


In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming the
runtime unused memory automatically. It is a way to destroy the unused objects. To do so, we use free()
function in C language and delete() in C++. But in java it is performed automatically. Hence, java provides
better memory management.
Advantage of Garbage Collection:
1. It makes java memory efficient because garbage collector removes the unreferenced objects
from heap memory.
2. It is automatically done by the garbage collector (a part of JVM) so we don’t need to make extra
efforts.
There are 3 many ways in which an object can be unreferenced:
1. By nulling the reference:
Example:
Employee e=new Employee();
e=null;
2. By assigning a reference to another:
Example:
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2; //now the first object referred by e1 is available for garbage collection.
3. By anonymous object etc
Example:
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.
Syntax:
protected void finalize()
{
}
gc() method:
The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is
found in System and Runtime classes.
Syntax:
public static void gc() Output:
{
D:\sowmya\javaprg>javac TestGarbage1.java
} D:\sowmya\javaprg>java TestGarbage1
//Program to show garbage collection in java Object in garbage collected
public class TestGarbage1 Object in garbage collected
{
public void finalize()
{
System.out.println("Object in garbage collected");
Programming in Java P.SowmyaSree Page 35
}
public static void main(String args[])
{
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}

 Class Variables & Methods-static Keyword


Class variables also known as static variables are declared with the static keyword in a class, but
outside a method, constructor or a block. There would only be one copy of each class variable per class,
regardless of how many objects are created from it.

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 an
instance of the class.

The static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block

Class variable(Static variable):

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


• The static variable can be used to refer to the common property of all objects (which is not unique
for each object), for example, the company name of employees, college name of students, etc.
• The static variable gets memory only once in the class area at the time of class loading.

Syntax
static <datatype><variable_name>;

Output:
Example program:
D:\sowmya\javaprg>javac StaticVariable1.java
class Student D:\sowmya\javaprg>java StaticVariable1
{ 111 Kiran AV College
int rollno;//instance variable 222 Ramu AV College
String name;

Programming in Java P.SowmyaSree Page 36


static String college ="AV College";//static variable

Student(int r, String n)
{
rollno = r;
name = n;
}

void display()
{
System.out.println(rollno+" "+name+" "+college);
}
}

public class StaticVariable1


{
public static void main(String args[])
{
Student s1 = new Student(111,"Kiran");
Student s2 = new Student(222,"Ramu");
s1.display();
s2.display();
}
}

Class method(static method):

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

o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.

Example program on static method


class Student
{
int rollno;
String name;
static String college = "AV College";
//static method to change the value of static variable
static void change()
{ Output:
college = "Nizam College";
} D:\sowmya\javaprg>javac StaticMethod.java
D:\sowmya\javaprg>java StaticMethod
Student(int r, String n) 111 Kiran Nizam College
{ 222 Ramu Nizam College

Programming in Java P.SowmyaSree Page 37


rollno = r;
name = n;
}

void display()
{
System.out.println(rollno+" "+name+" "+college);
}
}

public class StaticMethod


{
public static void main(String args[])
{
Student.change();
Student s1 = new Student(111,"Kiran");
Student s2 = new Student(222,"Ramu");

s1.display();
s2.display();

}
}

static block
o Is used to initialize the static data member.
o It is executed before the main method at the time of classloading.

Example of static block


class A2
{
Static Output:
{
D:\sowmya\javaprg>javac A2.java
System.out.println("static block is invoked"); D:\sowmya\javaprg>java A2
} static block is invoked
public static void main(String args[]) Hello main

{
System.out.println("Hello main");
}
}

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

Programming in Java P.SowmyaSree Page 38


Usage of java this keyword

Here is given the 6 usage of java this keyword.

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


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
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 can be used to return the current class instance from the method.

1) this: to refer current class instance variable

The this keyword can be used to refer current class instance variable. If there is ambiguity between the
instance variables and parameters, this keyword resolves the problem of ambiguity.

Example

class Student
{ Output:
introllno;
String name; C:>javac TestThis2.java
float fee;
C:>java TestThis2
Student(introllno,Stringname,float fee) 111 ankit 5000
{ 112 sumit 6000
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);
}
}

class TestThis2
{
public static void main(String args[])
{
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}
}

Programming in Java P.SowmyaSree Page 39


2) this: to invoke current class method

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.

Example Program

class A{ Output:
void m(){System.out.println("hello m");}
void n(){ C:>javac TestThis4.java
System.out.println("hello n"); c:>java TestThis4
//m();//same as this.m() hello n
hello m
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}}

3) this() : to invoke current class constructor


The this() constructor call can be used to invoke the current class constructor. It is used to reuse the
constructor. In other words, it is used for constructor chaining.

Example Program

class A
{ Output:
A()
{ C:>javac TestThis5.java
System.out.println("hello a"); c:>java TestThis5
hello a
} 10
A(int x)
{
this();
System.out.println(x);
}
}
class TestThis5
{
public static void main(String args[])
{
A a=new A(10);
}}

Programming in Java P.SowmyaSree Page 40


 Arrays

Java array is an object which contains elements of a similar data type. Additionally, The elements of an
array are stored in a contiguous memory location. It is a data structure where we store similar elements. We
can store only a fixed set of elements in a Java array.

Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored
on 1st index and so on.

Types of Array in java

There are two types of array.

o Single Dimensional Array


o Multidimensional Array

 Single Dimensional Array in Java /One Dimensional Array

Syntax to Declare an Array in Java

dataType[] arr; (or)


dataType []arr; (or)
dataType arr[];

Example of Java Array


classTestarray
{
public static void main(String args[])
{
int a[]=new int[5];//declaration and instantiation Output:

a[0]=10;//initialization C:>javac Testarray.java


C:>java Testarray
a[1]=20; 10
20
a[2]=70;
70
a[3]=40; 40
50
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array

Programming in Java P.SowmyaSree Page 41


System.out.println(a[i]);
}}

Declaration, Instantiation and Initialization of Java Array

We can declare, instantiate and initialize the java array together by:

int a[]={33,3,4,5};//declaration, instantiation and initialization


Example :
Output:
class Testarray1
{ C:>javac Testarray1.java
public static void main(String args[]) C:>java Testarray1
33
{
3
int a[]={33,3,4,5};//declaration, instantiation and initialization 4
//printing array 5
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}

For-each Loop for Java Array

We can also print the Java array using for-each loop. The Java for-each loop prints the array elements one
by one. It holds an array element in a variable, then executes the body of the loop.

The syntax of the for-each loop is given below:

for(data_type variable:array)
{
//body of the loop
}
Example:

class Testarray1 Output:


{
public static void main(String args[]) C:>javac Testarray1.java
{ C:>java Testarray1
33
int arr[]={33,3,4,5};
3
//printing array using for-each loop 4
for(int i:arr) 5
System.out.println(i);
}}

Programming in Java P.SowmyaSree Page 42


 Two Dimensional Array

Syntax
1. dataType[][] arrayRefVar; (or)
2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];

Example to instantiate Two-dimensional Array in Java

int[][] arr=new int[3][3];//3 row and 3 column

Example to initialize Two-dimensional Array in Java

1. arr[0][0]=1;
2. arr[0][1]=2;
3. arr[0][2]=3;
4. arr[1][0]=4;
5. arr[1][1]=5;
6. arr[1][2]=6;
7. arr[2][0]=7;
8. arr[2][1]=8;
9. arr[2][2]=9;

Example Program:
class Testarray3
{
public static void main(String args[]) Output:
{
C:>javac Testarray3.java
//declaring and initializing 2D array C:>java Testarray
int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; 1 2 3
//printing 2D array 2 4 5
4 4 5
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}

Programming in Java P.SowmyaSree Page 43


Example program to print matrix multiplication Output
C:>javac MatrixMultiplication.java
classMatrixMultiplication
{ C:>java MatrixMultiplication
public static void main(String args[]){ Matrix a is
//creating two matrices
int a[][]={{1,1,1},{2,2,2},{3,3,3}}; 111
int b[][]={{1,1,1},{2,2,2},{3,3,3}}; 222
333
//creating another matrix to store the multiplication of
two matrices Matrix b is
int c[][]=new int[3][3]; //3 rows and 3 columns
System.out.println("Matrix a is\n"); 111
for(int i=0;i<3;i++) 222
{ 333
for(int j=0;j<3;j++)
{ Multiplication of two matrices is
System.out.print(a[i][j]+" ");
} 666
System.out.println(); 12 12 12
} 18 18 18
System.out.println("\nMatrix b is\n");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(b[i][j]+" ");
}
System.out.println();
}
//multiplying and printing multiplication of 2 matrices
System.out.println("\nMultiplication of two matrices is\n");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}//end of k loop
System.out.print(c[i][j]+" "); //printing matrix element
}//end of j loop
System.out.println();//new line
}
}
}

Programming in Java P.SowmyaSree Page 44


 Command line argument

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.

Simple example of command-line argument


class CommandLineExample
Output:
{
public static void main(String args[]) C:>javac CommandLineExample.java
{ C:>java CommandLineExamplesowmya
System.out.println("Your first argument is: "+args[0]); Your first argument is sowmya
}
}

Example of command-line argument that prints all the values


class A
{
public static void main(String args[])
{ Output:
for(int i=0;i<args.length;i++)
System.out.println(args[i]); C:>javac A.java
C:>java A 1 2 hello
1
} 2
} hello
 Inner Classes

Java inner class or nested class is a class which is 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


class Java_Outer_class
{
//code
class Java_Inner_class
{ //code }
}

Programming in Java P.SowmyaSree Page 45


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.

Example program on Inner Classes:.


class Outer
{ int n;
class Inner
{
void print()
{
System.out.println("This is an inner class");
}
}
void display()
{
Inner i=new Inner(); Output:
System.out.println("This is an Outer class");
i.print(); C:>javac Myclass.java
} C:>java Myclass
} This is an Outer class
classMyclass This is an inner class
{
public static void main(String args[])
{
Outer o=new Outer();
o.display();
}
}

Programming in Java P.SowmyaSree Page 46


Chapter 2:

 Inheritance:
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a
parent object.

Why use inheritance in java


o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.

Terms used in Inheritance


o Class: A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived
class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is
also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the
fields and methods of the existing class when you create a new class. You can use the same fields
and methods already defined in the previous class.

 extends Keyword
extends is the keyword used to inherit the properties of a class.
Syntax:

class Base
{
.....
.....
}
class Derived extends Base
{
.....
.....
}

Programming in Java P.SowmyaSree Page 47


 Types of inheritance in java

On the basis of class, there can be three types of inheritance in java:

single, multilevel and hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only.

1.Single inheritance: In single inheritance, subclasses inherit the features of one superclass.

Example program on Single Inheritance :


Output:
class Animal
{ C:>javac TestInheritance.java
void eat() C:>java TestInheritance
{ barking…
System.out.println("eating..."); eating…
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");
}
}
classTestInheritance
{
public static void main(String args[])
{
Dog d=new Dog();
d.bark();
d.eat();
}
}

Programming in Java P.SowmyaSree Page 48


2.Multilevel Inheritance : In Multilevel Inheritance, a derived class will be
inheriting a base class and as well as the derived class also act as the base class to
other class.

Example program on Multilevel Inheritance :

class Animal
{
void eat()
{System.out.println("eating...");}
}
class Dog extends Animal
{
void bark()
{System.out.println("barking...");}
}
classBabyDog extends Dog
{
void weep()
{System.out.println("weeping...");}
}
class TestInheritance2
{ Output:
public static void main(String args[])
{ C:>javac TestInheritance2.java
BabyDog d=new BabyDog(); C:>java TestInheritance2
d.weep(); Weeping…
d.bark(); barking…
d.eat(); eating…
}
}

3.Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a superclass (base class) for
more than one sub class

Example program on Hierarchical Inheritance :

class Animal
{
void eat()
{System.out.println("eating...");}
}
class Dog extends Animal
{
void bark()
{System.out.println("barking...");}
}
class Cat extends Animal

Programming in Java P.SowmyaSree Page 49


{
void meow()
{System.out.println("meowing...");}
}
class TestInheritance3
{
public static void main(String args[]) Output:
{
Cat c=new Cat(); C:>javac TestInheritance3.java
c.meow(); C:>java TestInheritance3
Meowing…
c.eat();
eating…
//c.bark();//Compile time Error
}
}

4.Multiple Inheritance: In Multiple inheritance ,one class can


have more than one superclass and inherit features from all
parent classes.

5.Hybrid Inheritance:

Note :For examples of multiple and hybrid inheritance refer interface topic :

 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 a subclass provides the specific implementation of the method that has been declared by
one of its parent class, it is known as method overriding.

Programming in Java P.SowmyaSree Page 50


Usage of Java Method Overriding
o Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


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

Example program on Method overriding:

class Vehicle
{
//defining a method
void run()
{System.out.println("Vehicle is running");}
} Output:
//Creating a child class
class Bike2 extends Vehicle C:>javac Bike2.java
C:>java Bike2
{
//defining the same method as in the parent class Bike is running safely
void run()
{System.out.println("Bike is running safely");}

public static void main(String args[])


{
Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}

 Super Keyword

The super keyword in Java is a reference variable which is used to refer immediate parent class object.

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.

Programming in Java P.SowmyaSree Page 51


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.

Example:
class Animal
{ Output:
String color="white";
} C:>javac TestSuper1.java
class Dog extends Animal C:>java TestSuper1
{ black
String color="black"; white
voidprintColor()
{
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1
{
public static void main(String args[])
{
Dog d=new Dog();
d.printColor();
}
}

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.

Example:
class Animal
{
void eat()
{System.out.println("eating...");}
}
class Dog extends Animal
{ Output:
void eat()
{System.out.println("eating bread...");} C:>javac TestSuper2.java
void bark() C:>java TestSuper2
{System.out.println("barking...");} eating…
void work() barking…
{
super.eat();

Programming in Java P.SowmyaSree Page 52


bark();
}
}
class TestSuper2
{
public static void main(String args[])
{
Dog d=new Dog();
d.work();
}
}

3) super is used to invoke parent class constructor.

The super keyword can also be used to invoke the parent class constructor.

Example:

class Animal
{
Animal() Output:
{System.out.println("animal is created");}
} C:>javac TestSuper3.java
class Dog extends Animal C:>java TestSuper3
{ animal is created
Dog() dog is created
{
super();
System.out.println("dog is created");
}
}
class TestSuper3
{
public static void main(String args[])
{
Dog d=new Dog();
}
}

 Final Keyword:

The final keyword in java is used to restrict the user. The java final keyword can be used in many context.
Final can be:

1. variable
2. method

Programming in Java P.SowmyaSree Page 53


3. class

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


class Bike9 Output:
{
final int speedlimit=90;//final variable C:>javac Bike9.java
void run() C:>java Bike9
Bike9.java:6: error: cannot assign a value to final
{
variable speedlimit
speedlimit=400; speedlimit=400;
} ^
public static void main(String args[]) 1 error
{
Bike9 obj=new Bike9();
obj.run();
}
}

2) Java final method

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

Example of final method Output:


class Bike
{ C:>javac Honda.java
final void run() C:>java Honda
{System.out.println("running");} Honda.java:9: error: run() in Honda cannot override
} run() in Bike
void run()
class Honda extends Bike ^
{ overridden method is final
void run() 1 error
{System.out.println("running safely with 100kmph");}

public static void main(String args[])


{
Honda honda= new Honda();
honda.run();
}
}

Programming in Java P.SowmyaSree Page 54


3) Java final class

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

Example of final class Output:


final class Bike
C:>javac Honda.java
{
C:>java Honda
Honda1.java:6: error: cannot inherit from final Bike
}
class Honda1 extends Bike
^
class Honda1 extends Bike 1 error
{
void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[])


{
Honda1 honda= new Honda1();
honda.run();
}
}

 Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only functionality to the user.

Another way, it shows only essential things to the user and hides the internal details, for example, sending
SMS where you type the text and send the message. You don't know the internal processing about the
message delivery.

Abstract class in Java

A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract
methods. It needs to be extended and its method implemented. It cannot be instantiated.

Programming in Java P.SowmyaSree Page 55


Syntax of abstract class:

abstract class classname


{

Abstract Method in Java

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

Syntax

abstract void methodname();//no method body and abstract

Example program on abstract classes

abstract class Bike


{ Output:
abstract void run();
} C:>javac Honda4.java
class Honda4 extends Bike C:>java Honda4
{ running safely
void run()
{System.out.println("running safely");}
public static void main(String args[])
{
Bike obj = new Honda4();
obj.run();
}
}

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

Why use Java interface?

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

o It is used to achieve abstraction.


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

Programming in Java P.SowmyaSree Page 56


How to declare an interface?

An interface is declared by using the interface keyword. It provides total abstraction; means all the methods
in an interface are declared with the empty body, and all the fields are public, static and final by default. A
class that implements an interface must implement all the methods declared in the interface.

Syntax:
interface <interface_name>
{

// declare constant fields


// declare methods that abstract
// by default.
}
The relationship between classes and interfaces

a class extends another class, an interface extends another interface, but a class implements an interface.

Interface Example(Multiple Inheritance)

interface Printable
{
void print();
Output:
}
interface Showable C:>javac A7.java
{ C:>java A7
void show(); Hello
} Welcome
class A7 implements Printable,Showable
{
public void print()
{System.out.println("Hello");}
public void show()
{System.out.println("Welcome");}
Programming in Java P.SowmyaSree Page 57
public static void main(String args[])
{
A7 obj = new A7();
obj.print();
obj.show();
}
}
Difference between abstract class and interface

Sno Abstract class Interface


1 Abstract class can have abstract and Interface can have only abstract methods. Since Java 8,
non-abstract methods. it can have default and static methods also.
2 Abstract class doesn't support Interface supports multiple inheritance.
multiple inheritance.
3 Abstract class can have final, non- Interface has only static and final variables.
final, static and non-static variables.
4 Abstract class can provide the Interface can't provide the implementation of abstract
implementation of interface. class.
5 The abstract keyword is used to The interface keyword is used to declare interface.
declare abstract class.
6 An abstract class can extend another An interface can extend another Java interface only.
Java class and implement multiple
Java interfaces.
7 An abstract class can be extended An interface can be implemented using keyword
using keyword "extends". "implements".
8 A Java abstract class can have class Members of a Java interface are public by default.
members like private, protected, etc.
9 Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

Programming in Java P.SowmyaSree Page 58


Chapter 3
Pakages

 Definition:A package is a collection of classes,interfaces and sub-packages.


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

Built-in packages are

 Creating package:
While creating a package, you should choose a name for the package and include a package statement
along with that name at the top of every source file that contains the classes, interfaces, enumerations, and
annotation types that you want to include in the package.
The package statement should be the first line in the source file. There can be only one package statement
in each source file, and it applies to all types in the file.

Syntax: package pack_name;


public class firstClass
{
. . . . . . . . //body of the class.
........
}

Example program: Output:


C:>javac –d . Simple.java
//save as Simple.java
C:>java mypack.Simple
package mypack; Welcome to package
public class Simple{
public static void main(String args[]){

Programming in Java P.SowmyaSree Page 59


System.out.println("Welcome to package");
}
}

How to compile java package?


javac -d directory javafilename.java

Example to compile java package

javac -d . Simple.java

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 run java package program


To Compile: javac -d . Simple.java
To Run: java mypack.Simple

 Access Protection

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.

Example of package that import the packagename.*


//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");

Programming in Java P.SowmyaSree Page 60


}
}
//save by B.java Output:
package mypack; C:>javac –d . A.java
import pack.*; C:>javac -d . B.java
class B C:>java mypack.B
{ Hello
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}

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


//save by A.java
package pack;
public class A
{
public void msg()
{ Output:
System.out.println("Hello");
C:>javac –d . A.java
} C:>javac -d . B.java
} C:>java mypack.B
Hello
//save by B.java
package mypack;
import pack.A;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}

Programming in Java P.SowmyaSree Page 61


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


//save by A.java
package pack;
public class A
{ Output:
public void msg()
C:>javac –d . A.java
{ C:>javac -d . B.java
System.out.println("Hello"); C:>java mypack.B
} Hello
}

//save by B.java
package mypack;
class B
{
public static void main(String args[])
{
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}

 Subpackage in java

Package inside the package is called the subpackage. It should be created to categorize the package further.

Example Program on Subpackages3


Output:
package com.javaprg.core;
class Simple1 C:>javac –d . Simple1.java
{ C:>java com.javaprg.core.Simple1
public static void main(String args[]) Hello subpackage
{
System.out.println("Hello subpackage");
}
}

Programming in Java P.SowmyaSree Page 62


 Wrapper classes:
The wrapper class in Java provides the mechanism to convert primitive into object and object
into primitive.

Use of Wrapper classes in Java


o Change the value in Method: Java supports only call by value. So, if we pass a primitive value, it
will not change the original value. But, if we convert the primitive value in an object, it will change
the original value.
o Serialization: We need to convert the objects into streams to perform the serialization. If we have a
primitive value, we can convert it in objects through the wrapper classes.
o Synchronization: Java synchronization works with objects in Multithreading.
o java.util package: The java.util package provides the utility classes to deal with objects.
o Collection Framework: Java collection framework works with objects only. All classes of the
collection framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet,
PriorityQueue, ArrayDeque, etc.) deal with objects only.
o The eight classes of the java.lang package are known as wrapper classes in Java. The list of eight
wrapper classes are given below:

Primitive Type Wrapper class

boolean Boolean

char Character

byte Byte

short Short

int Integer

long Long

float Float

double Double

Programming in Java P.SowmyaSree Page 63


Autoboxing

The automatic conversion of primitive data type into its corresponding wrapper class is known as
autoboxing, for example, byte to Byte, char to Character, int to Integer, long to Long, float to Float,
boolean to Boolean, double to Double, and short to Short.

Wrapper class Example: Primitive to Wrapper

//Java program to convert primitive into objects Output:


//Autoboxing example of int to Integer
public class WrapperExample1 C:>javac WrapperExample1.java
{ C:>javac WrapperExample1
public static void main(String args[]) 20 20 20
{
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer explicitly
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally

System.out.println(a+" "+i+" "+j);


}
}

Unboxing

The automatic conversion of wrapper type into its corresponding primitive type is known as unboxing. It is
the reverse process of autoboxing.

Wrapper class Example: Wrapper to Primitive

//Java program to convert object into primitives


//Unboxing example of Integer to int Output:
public class WrapperExample2
{ C:>javac WrapperExample2.java
public static void main(String args[]) C:>java WrapperExample2
333
{
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue();//converting Integer to int explicitly
int j=a;//unboxing, now compiler will write a.intValue() internally

System.out.println(a+" "+i+" "+j);


}
}

Programming in Java P.SowmyaSree Page 64


 String class

String is a sequence of characters. In java, objects of String are immutable which means a constant and
cannot be changed once created.

 Creating a String
There are two ways to create string in Java:
• String literal
String s = “AV College”;

• Using new keyword


String s = new String (“AV College”);

Example Program on String.


Output:
public class StringExample
{ C:>javac SrtingExample.java
public static void main(String args[]) C:>java StringExample
{ java
String s1="java";//creating string by java string literal strings
char ch[]={'s','t','r','i','n','g','s'}; example
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}

 String class methods:

The java.lang.String class provides many useful methods to perform operations on sequence of char values.

1. Char charAt(int i): Returns the character at ith index


The index number starts from 0 and goes to n-1, where n is length of the string

Example Program:
Output:
public class CharAtExample
{ C:>javac CharAtExample.java
public static void main(String args[]) C:>java CharAtExample
{ l
String name="hello world";
System.out.println(name.charAt(3));
}
}

Programming in Java P.SowmyaSree Page 65


2. int length():It returns count of total number of characters.

Example Program: Output:


C:>javac LengthExample.java
public class LengthExample C:>java LengthExample
String length is:6
{

public static void main(String args[])

String s1="python";

System.out.println("string length is: "+s1.length());

}}

3. String substring(int beginIndex):The java string substring() method returns a part of the string.

We pass begin index and end index number position in the java substring method where start index is inclusive and end index is
exclusive. In other words, start index starts from 0 whereas end index starts from 1.

public class SubstringExample


{ Output:
public static void main(String args[]) C:>javac SubstringExample.java
{ C:>java SubstringExample
String s1="Avcollege"; Co
College
System.out.println(s1.substring(2,4));
System.out.println(s1.substring(2));
}

4. boolean contains(CharSequence s): The java string contains() method searches the sequence of characters in
this string. It returns true if sequence of char values are found in this string otherwise returns false.

Example program:
Output:
class ContainsExample
C:>javac ContainsExample.java
C:>java ContainsExample
{ true
public static void main(String args[]) true
false
{
String name="what do you know about me";
System.out.println(name.contains("do you know"));
System.out.println(name.contains("about"));

Programming in Java P.SowmyaSree Page 66


System.out.println(name.contains("hello"));
}
}

5. static String join(CharSequence delimiter, CharSequence... elements):


The java string join() method returns a string joined with given delimiter. In string join
method, delimiter is copied for each elements.

Example program:
Output:
public class StringJoinExample C:>javac StringJoinExample.java
{ C:>java StringJoinExample
welcome-to-java-language
public static void main(String args[])
{
String joinString1=String.join("-","welcome","to","java language");
System.out.println(joinString1);
}
}

6. boolean equals(Object another) : The java string equals() method compares the two given strings based on the
content of the string. If any character is not matched, it returns false. If all characters are matched, it returns true.

Example program:

public class EqualsExample


{ Output:
public static void main(String args[]) C:>javac EqualsExample.java
{ C:>java EqualsExample
true
String s1="java"; false
String s2="java"; false
String s3="JAVA";
String s4="python";
System.out.println(s1.equals(s2));//true because content and case is same
System.out.println(s1.equals(s3));//false because case is not same
System.out.println(s1.equals(s4));//false because content is not same
}
}

7. boolean isEmpty():The java string isEmpty() method checks if this string is empty or not. It returns true, if length of
string is 0 otherwise false. In other words, true is returned if string is empty otherwise it returns false.

Output:
Example program:
C:>javac IsEmptyExample.java
C:>java IsEmptyExample
public class IsEmptyExample true
{ false

Programming in Java P.SowmyaSree Page 67


public static void main(String args[])
{
String s1="";
String s2="javalanguage";

System.out.println(s1.isEmpty());
System.out.println(s2.isEmpty());
}
}
8. String concat(String str): The java string concat() method combines specified string at the end of this string. It returns
combined string. It is like appending another string.

Example program:
public class ConcatExample
{
public static void main(String args[])
{ Output:
String s1="java string"; C:>javac ConcatExample.java
s1.concat("is immutable"); C:>java ConcatExample
java string
System.out.println(s1); java string is immutable so
s1=s1.concat(" is immutable so assign it explicitly"); assign it explicitly
System.out.println(s1);
}}

9. String replace(char old, char new): The java string replace() method returns a string replacing all the old char or
CharSequence to new char or CharSequence.

Example program:
Output:
public class ReplaceExample1
C:>javac ReplaceExample1.java
{ C:>java ReplaceExample1
public static void main(String args[]) Jeve is e progremming lenguege
{
String s1="java is a programming language ";
String replaceString=s1.replace('a','e');
System.out.println(replaceString);
}
}

10. int indexOf(int ch): The java string indexOf() method returns index of given character value or substring. If it is not
found, it returns -1. The index counter starts from zero.

There are 4 types of indexOf method in java.

Programming in Java P.SowmyaSree Page 68


No. Method Description

1 int indexOf(int ch) returns index position for the given char value

2 int indexOf(int ch, int fromIndex) returns index position for the given char value and from index

3 int indexOf(String substring) returns index position for the given substring

4 int indexOf(String substring, int returns index position for the given substring and from index
fromIndex)

Example program:

a. String indexOf(String substring)


public class IndexOfExample2 { Output:
public static void main(String[] args) { C:>javac IndexOfExample2.java
C:>java IndexOfExample2
String s1 = "This is indexOf method";
index of substring 16
// Passing Substring
int index = s1.indexOf("method"); //Returns the index of this substring
System.out.println("index of substring "+index);
}

b. String indexOf(String substring, int fromIndex)


public class IndexOfExample3
{ Output:
public static void main(String[] args) C:>javac IndexOfExample3.java
{ C:>java IndexOfExample3
index of substring 16
String s1 = "This is indexOf method"; index of substring -1
int index = s1.indexOf("method", 10);
System.out.println("index of substring "+index);
index = s1.indexOf("method", 20);
System.out.println("index of substring "+index);
}
}

Programming in Java P.SowmyaSree Page 69


c. String indexOf(int char, int fromIndex)
public class IndexOfExample4
{ Output:
C:>javac IndexOfExample4.java
public static void main(String[] args)
C:>java IndexOfExample4
{ index of char 17
String s1 = "This is indexOf method";
// Passing char and index from
int index = s1.indexOf('e', 12); //Returns the index of this char
System.out.println("index of char "+index);
}
}

11. String toLowerCase():The java string toLowerCase() method returns the string in lowercase letter. In other words, it
converts all characters of the string into lower case letter.

Example program:
Output:
public class StringLowerExample
{ C:>javac StringLowerExample.java
public static void main(String args[]) C:>java StringLowerExample
{ Java language hello string
String s1="JAVA LANGUAGE HELLO stRIng";
String s1lower=s1.toLowerCase();
System.out.println(s1lower);
}}

12. String toUpperCase():The java string toUpperCase() method returns the string in uppercase letter. In other words, it
converts all characters of the string into upper case letter.

Example program:
Output:

public class StringUpperExample C:>javac StringUpperExample.java


{ C:>java StringUpperExample
public static void main(String args[]) HELLO STRING
{
String s1="hello string";
String s1upper=s1.toUpperCase();
System.out.println(s1upper);
}
}

Programming in Java P.SowmyaSree Page 70


StringBuffer class

Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in java is same as String class
except it is mutable i.e. it can be changed.

Constructors of StringBuffer class

Constructor Description method


s of
StringBuffer() creates an empty string buffer with the initial capacity of 16.
StringB
StringBuffer(String str) creates a string buffer with the specified string. uffer
class
StringBuffer(int creates an empty string buffer with the specified capacity as length.
capacity)
1.
append(String
1) The append() method concatenates the given argument with this string.

Exmple Program

class StringBufferExample Output:


{ C:>javac StringBufferExample.java
public static void main(String args[]) C:>java StringBufferExample
{
Hello Java
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");
System.out.println(sb);
}
}

2. insert()
It is used to insert the specified string with this string at the specified position.

Exmple Program
Output:
class StringBufferExample2 C:>javac StringBufferExample2.java
{ C:>java StringBufferExample2
public static void main(String args[]) HJavaello
{
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");
System.out.println(sb);
}}

Programming in Java P.SowmyaSree Page 71


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

Exmple program:
Output:
class StringBufferExample3 C:>javac StringBufferExample3.java
{ C:>java StringBufferExample3
public static void main(String args[]) HJavalo
{
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);
}
}

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

Example Program:
Output:
class StringBufferExample4 C:>javac StringBufferExample4.java
{
C:>java StringBufferExample4
Hlo
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}

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

Example Program:

class StringBufferExample5 Output:


{ C:>javac StringBufferExample5.java
public static void main(String args[]) C:>java StringBufferExample5
olleH
{
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}

Programming in Java P.SowmyaSree Page 72


6. capacity():

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.

Example Program:
Output:
C:>javac StringBufferExample5.java
class StringBufferExample6
C:>java StringBufferExample5
{ 16
public static void main(String args[]) 16
{ 34
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}

Programming in Java P.SowmyaSree Page 73


UNIT-III
Chapter I
Exception
Introduction :
An exception (or exceptional event) is a problem that arises during the execution of a program. When
an Exception occurs the normal flow of the program is disrupted and the program/Application terminates
abnormally, which is not recommended, therefore, these exceptions are to be handled.
An exception can occur for many different reasons. Following are some scenarios where an exception
occurs.
• A user has entered an invalid data.
• A file that needs to be opened cannot be found.
• A network connection has been lost in the middle of communications or the JVM has run out of
memory.
Some of these exceptions are caused by user error, others by programmer error, and others by physical
resources that have failed in some manner.

Types of exceptions
we have three Types of Exceptions. You need to understand them to know how exception handling works
in Java.

• Checked exceptions − A checked exception is an exception that is checked (notified) by the


compiler at compilation-time, these are also called as compile time exceptions. These exceptions
cannot simply be ignored, the programmer should take care of (handle) these exceptions.
For example, if you use FileReader class in your program to read data from a file, if the
file specified in its constructor doesn't exist, then a FileNotFoundException occurs, and the
compiler prompts the programmer to handle the exception.

• Unchecked exceptions − An unchecked exception is an exception that occurs at the time of


execution. These are also called as Runtime Exceptions. These include programming bugs, such
as logic errors or improper use of an API. Runtime exceptions are ignored at the time of
compilation.
For example, if you have declared an array of size 5 in your program, and trying to call the
6th element of the array then an ArrayIndexOutOfBoundsExceptionexception occurs.

• Errors − These are not exceptions at all, but problems that arise beyond the control of the user or
the programmer. Errors are typically ignored in your code because you can rarely do anything
about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at
the time of compilation.

Hierarchy Exception classes

The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited by two
subclasses: Exception and Error. A hierarchy of Java Exception classes are given below.

Programming in Java P.SowmyaSree Page 74


Exception Handling Techniques
There are 5 keywords which are used in handling exceptions in Java.
Keyword Description

try The "try" keyword is used to specify a block where we should place exception
code. The try block must be followed by either catch or finally. It means, we can't
use try block alone.

catch The "catch" block is used to handle the exception. It must be preceded by try
block which means we can't use catch block alone. It can be followed by finally
block later.

finally The "finally" block is used to execute the important code of the program. It is
executed whether an exception is handled or not.

Programming in Java P.SowmyaSree Page 75


throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It doesn't throw an


exception. It specifies that there may occur an exception in the method. It is
always used with method signature.

Common Scenarios of Java Exceptions

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

1) A scenario where ArithmeticException occurs


If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException

2) A scenario where NullPointerException occurs


If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException

3) A scenario where NumberFormatException occurs


The wrong formatting of any value may occurNumberFormatException. Suppose I have a string variable
that has characters, converting this variable into digit will occurNumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs


If you are inserting any value in the wrong index, it would result in ArrayIndexOutOfBoundsException as
shown below:
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException

Java try-catch block

Java try block:


Java try block is used to enclose the code that might throw an exception. It must be used within
the method.

If an exception occurs at the particular statement of try block, the rest of the block code will
not execute. So, it is recommended not to keeping the code in try block that will not throw an exception.
Java try block must be followed by either catch or finally block.

Java catch block:

Programming in Java P.SowmyaSree Page 76


Java catch block is used to handle the Exception by declaring the type of exception within the
parameter. The declared exception must be the parent class exception ( i.e., Exception) or the generated
exception type. However, the good approach is to declare the generated type of exception.
The catch block must be used after the try block only. You can use multiple catch block with a single try
block.

Syntax: try
{
// Block of code to try
}
catch(Exception e)
{
// Block of code to handle errors
}

Example Program without try catch


classExceptionDemo
{
public static void main(String[] args)
{
int a=10, b=0,c;
c=a/b;
System.out.println("The value after dividing "+c);
}
}
Output:
D:\sowmya java>javac ExceptionDemo.java
D:\sowmya java>java ExceptionDemo
Exception in thread "main" java.lang.ArithmeticException: / by zero
atExceptionDemo.main(ExceptionDemo.java:6)

Example program with try-catch


class ExceptionDemo1
{
public static void main(String[] args)
{
int a=10, b=0,c; Output:
try
D:\sowmya java>javac ExceptionDemo1.java
{
D:\sowmya java>java ExceptionDemo1
c=a/b;
Denominator should not be zero
}
catch (Exception e)
{
System.out.println("Denominator should not be zero");
}

Programming in Java P.SowmyaSree Page 77


}
}

Java finally block

Java finally block is a block that is used to execute important code such as closing
connection, stream etc.
Java finally block is always executed whether exception is handled or not.
Java finally block follows try or catch block.

Example program on finally block


class TestFinallyBlock
{
public static void main(String args[])
{
try{ Output:
int data=25/5;
System.out.println(data); D:\sowmya java>javac TestFinallyBlock.java
} D:\sowmya java>java TestFinallyBlock
catch(NullPointerException e) finally block is always executed
{ rest of the code...
System.out.println(e);
}
Finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}

Java throw keyword


The Java throw keyword is used to explicitly throw an exception.We can throw either checked
or unchekedexception in java by throw keyword. The throw keyword is mainly used to throw custom
exception. We will see custom exceptions later.

The syntax of java throw keyword is given below.


throw exception;
Output:
Example program on throw keyword:
public class TestThrow1 D:\sowmya java>javacTestThrow1.java
{ D:\sowmya java>java TestThrow1
static void validate(int age) Exception in thread main
{ java.lang.ArithmeticException:not valid
if(age<18)
throw new ArithmeticException("not valid");
else
Programming in Java P.SowmyaSree Page 78
System.out.println("welcome to vote");
}
public static void main(String args[])
{
validate(13);
System.out.println("rest of the code...");
}
}

throws keyword

The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to provide the exception
handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers fault that he is not performing check
up before the code being used.

Syntax of java throws


return_typemethod_name() throws exception_class_name
{
//method code
}

Example program on throws keyword:


importjava.io.IOException;
class Testthrows1
{
void m()throws IOException
{
throw new IOException("device error");//checked exception
}
void n()throws IOException
{
m(); Output:
}
void p() D:\sowmya java>javac Testthrows1.java
{ D:\sowmya java>java Testthrows1
Try exception handled
{ normal flow...
n();
}
catch(Exception e)
{
System.out.println("exception handled");
}
}

Programming in Java P.SowmyaSree Page 79


public static void main(String args[])
{
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}

User-Defined Exception

If you are creating your own Exception that is known as custom exception or user-defined exception. Java
custom exceptions are used to customize the exception according to user need.
By the help of custom exception, you can have your own exception and message.

Example Program:
class TestCustomException1
{
static void validate(int age)throws InvalidAgeException
{
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
Output:
public static void main(String args[])
{ D:\sowmya java>javacTestCustomException1.java
try D:\sowmya java>java TestCustomException1
{
validate(13); Output:Exceptionoccured: InvalidAgeException:not valid
} rest of the code..
catch(Exception m)
{
System.out.println("Exception occured: "+m);.
}
System.out.println("rest of the code...");
}
}

Programming in Java P.SowmyaSree Page 80


Chapter-II
Multithreading

Multitasking: Multitasking means running more than one process simultaneously is called Multitasking.
There are two types of multitasking:
• Process based
• Thread based

Process based multitasking : Running more than one processes simultaneously and each process is an
independent process of different application is called process based multitasking. Example, It allows us to
listen music using mp3 player while creating PowerPoint presentation using MS PowerPoint. Both Mp3
player and MS PowerPoint are independent applications.

Thread based multitasking : Running more than one processes simultaneously and each process is an
independent process of same application is called thread based multitasking. Example, While writing MS
word document, MS word can check the spelling and grammatical errors, at the same time it can also
auto-correct these spelling and grammatical errors. Both, error checking and auto-correct are independent
processes and comes under the same application.

Java Multithreading
Thread is an independent process of a single application. In Java, main() method is called the "main
thread" of our application and other program level threads are called child thread.

create thread

There are two ways to create a thread:


a) Extends Thread Class
b) Implements 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:
o Thread()
o Thread(String name)
o Thread(Runnable r)
o 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. publicintgetPriority(): returns the priority of the thread.
7. publicintsetPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.

Programming in Java P.SowmyaSree Page 81


9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing thread.
11. publicintgetId(): returns the id of the thread.
12. publicThread.StategetState(): returns the state of the thread.
13. publicbooleanisAlive(): 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. publicbooleanisDaemon(): 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. publicbooleanisInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been interrupted.

Thread creation by extending the thread class:

We create a class that extends the java.lang.Thread class. This class overrides the run() method available
in the Thread class. A thread begins its life inside run() method. We create an object of our new class and
call start() method to start the execution of a thread. Start() invokes the run() method on the Thread object.

Example program
class Multi extends Thread
{ Output:
public void run()
{ D:\sowmya java>javac Multi.java
System.out.println("thread is running..."); D:\sowmya java>java Multi
} thread is running...
public static void main(String args[]).
{
Multi t1=new Multi();
t1.start();
}
}

Thread creation by implementing the Runnable Interface


We create a new class which implements java.lang.Runnable interface and override run()
method. Then we instantiate a Thread object and call start() method on this object.

Example Program
class Multi3 implements Runnable
{
public void run()
{
System.out.println("thread is running...");
}

Programming in Java P.SowmyaSree Page 82


Output:
public static void main(String args[])
D:\sowmya java>javacMulti3.java
{
D:\sowmya java>java Multi3
Multi3 m1=new Multi3();
thread is running...
Thread t1 =new Thread(m1);
t1.start();
}
}

Thread Life Cycle:-

A thread can be in one of the following states ,


1. New born state(New)
2. Ready to run state (Runnable)
3. Running state(Running)
4. Blocked state
5. Dead state

New Born State:--


• The thread enters the new born state as soon as it is created. The thread is created using the new
operator.
• From the new born state the thread can go to ready to run mode or dead state.
• If start( ) method is called then the thread goes to ready to run mode. If the stop( ) method is called
then the thread goes to dead state.

Ready to run mode (Runnable Mode):--


• If the thread is ready for execution but waiting for the CPU the thread is said to be in ready to run
mode.

Programming in Java P.SowmyaSree Page 83


• All the events that are waiting for the processor are queued up in the ready to run mode and are
served in FIFO manner or priority scheduling.
• From this state the thread can go to running state if the processor is available using the scheduled( )
method.
• From the running mode the thread can again join the queue of runnable threads.
• The process of allotting time for the threads is called time slicing.

Running State:--
• If the thread is in execution then it is said to be in running state.
• The thread can finish its work and end normally.
• The thread can also be forced to give up the control when one of the following conditions arise
1. A thread can be suspended by suspend( ) method. A suspended thread can be revived by
using the resume() method.
2. A thread can be made to sleep for a particular time by using the sleep(milliseconds) method.
The sleeping method re-enters runnable state when the time elapses.
3. A thread can be made to wait until a particular event occur using the wait() method, which can be run
again using the notify( ) method.

Blocked State:--
• A thread is said to be in blocked state if it prevented from entering into the runnable state and so the
running state.
• The thread enters the blocked state when it is suspended, made to sleep or wait.
• A blocked thread can enter into runnable state at any time and can resume execution.
Dead State:--
• The running thread ends its life when it has completed executing the run() method which is called
natural dead.
• The thread can also be killed at any stage by using the stop( ) method.

//A.java
public class A extends Thread {
public void run()
{
System.out.println("Thread A");
System.out.println("i in Thread A ");
for(int i=1;i<=5;i++)
{
System.out.println("i = " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Thread A Completed.");
}
}

Programming in Java P.SowmyaSree Page 84


//B.java
public class B extends Thread
{
public void run()
{
System.out.println("Thread B");
System.out.println("i in Thread B ");
for(int i=1;i<=5;i++)
{
System.out.println("i = " + i);
}
System.out.println("Thread B Completed.");
}
}

//Main.java
public class Main
{
public static void main(String[] args)
{
//life cycle of Thread
// Thread's New State
A threadA = new A();
B threadB = new B();
// Both the above threads are in runnable state

//Running state of thread A & B


threadA.start();

//Move control to another thread


threadA.yield();
//Bolcked State of thread B
try {
threadA.sleep(1000);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
threadB.start();
System.out.println("Main Thread End");
}
}

Programming in Java P.SowmyaSree Page 85


Output:

D:\sowmya java>javacMain.java
D:\sowmya java>java Main
Thread A
i in Thread A
i=1
Main Thread End
Thread B
i in Thread B
i=1
i=2
i=3
i=4
i=5
Thread B Completed.
i=2
i=3
i=4
i=5
Thread A Completed.

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


class TestMultiPriority1 extends Thread
{
public void run()
{
System.out.println("running thread name is:"+ Thread.currentThread().getName());
System.out.println("running thread priority is:”+Thread.currentThread().getPriority());
}
public static void main(String args[])
{
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();

Programming in Java P.SowmyaSree Page 86


m1.setPriority(Thread.MIN_PRIORITY); Output:
m2.setPriority(Thread.MAX_PRIORITY);
m1.start(); D:\sowmya java>javacTestMultiPriority1.java
m2.start(); D:\sowmya java>java TestMultiPriority1
} running thread name is:Thread-0
} running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
Synchronization :

In multithreading, there is the asynchronous behavior of the programs. If one thread is writing some data
and another thread which is reading data at the same time, might create inconsistency in the application.
When there is a need to access the shared resources by two or more threads, then synchronization approach
is utilized.
Java has provided synchronized methods to implement synchronized behavior.
In this approach, once the thread reaches inside the synchronized block, then no other thread can call that
method on the same object. All threads have to wait till that thread finishes the synchronized block and
comes out of that.
In this way, the synchronization helps in a multithreaded application. One thread has to wait till other
thread finishes its execution only then the other threads are allowed for execution.

Syntax

Synchronized(object)
{
//Block of statements to be synchronized
}

Example Program on Synchronization


class Table
{ Output:
synchronized void printTable(int n)
D:\sowmya java>javacTestSynchronization2.java
{
D:\sowmya java>java TestSynchronization2
//synchronized method
5
for(int i=1;i<=5;i++)
10
{
15
System.out.println(n*i);
20
try
25
{
100
Thread.sleep(400);
200
}
300
catch(Exception e)
400
{
500
System.out.println(e);
}
}
}
}

Programming in Java P.SowmyaSree Page 87


class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
}

public class TestSynchronization2


{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}

Programming in Java P.SowmyaSree Page 88


Chapter-3
Input/Output

I/O devices are the pieces of hardware used by a human to communicate with a computer.Forinstance
,a keyboard or computer mouse is an input device for a computer ,while monitors and printers are output
devices.

Introduction:
Java performs Input/Output through the concept of Streams.A Stream is a sequence of data like a
stream of water that flows continuously.Java’s IO package mostly concerns itself with the reading of data
from a source and writing of data to a destination.
Source Program Destination

You can either read from stream or write to a stream.A stream is connected to datasource or a data
destination.Streams in java IO can be either byte based (reading and writing bytes) or character based
(reading and writing characters).

Java.io Package:
This package provides for system input and output through data streams, serialization and the file system.
Java defines two types of streams-
1. Byte Stream:It provides a convenient means for handling input and output of byte.
2. Character Stream: It provides a convenient menas for handling input and output of
characters.
Byte Stream Classes:
Byte stream is defined by using two abstract class at the top of hierarchy-
o InputStream
o OutputStream

Some important Byte stream classes are-


Stream class Description
BufferedInputStream Used for Buffered Input Stream.
BufferedOutputStream Used for Buffered Output Stream.
DataInputSream Contains method for reading java standard
datatype
DataOutputStream An output stream that contains method for
writing java standard type
FileInputStream Input stream that reads from a file
FileOutputStream Output stream that write to a file
InputStream Abstract class that describe stream output
OutputStream Abstract class that describe stream output
PrintStream Output stream that contains print() and
println() method

Programming in Java P.SowmyaSree Page 89


These classes define several key methods.Two most important are:

read():reads byte of data


write():Writes byte of data.

Character Stream Classes: It is also defined by using two abstract class at the top of hierarchy-
• Reader
• Writer

Some important Character stream classes are-


Stream class Description
BufferedReader Handles Buffered Input Stream.
BufferedWriter Handles Buffered Output Stream.
FileReader Input stream that reads from file
FileWriter Output stream that write to a file
InputStreamReader Input stream that translate byte to character
OutputStreamReader Output stream that translate character to byte
PtintWriter Output stream that contains print() and
println() method
Reader Abstract class that define character stream
input
Writer Abstract class that define character stream
output

File class: Files are a common source or destination of data in Java application. The file class is an
abstract representation of file and directory pathname. A pathname can be either absolute or relative. The
file class have several methods for working with directories and files,deleting and renaming directories or
files ,listing the contents of directory etc.

Using The File Class:


The java.io.package includes a class known as the file class that provides support for creating files and
directories. The class includes several constructors for instantiating the File objects. This class also contain
several methods for supporting the operations such as:
• Creating a file
• Opening a file
• Closing a file
• Deleting a file
• Getting the name of a file
• Getting the size of a file
• Checking whether the file is writable
• Checking whether the file is readable
• Renaming a file

Creation of File Object: A File object is created by passing in a String that represents the name of a file,
or a String or another File object.
For Example: File f1=new File(“testFile.txt”);

Programming in Java P.SowmyaSree Page 90


Defines an abstract file name for the testFile.txt file in current directory.This is an relative file name.

Constructors:
Constructor Description
File(File parent,String child) It creates new File instance from a parent pathname and a
child pathname string.
File(Sting pathname) It creates a new File instance by converting the given
pathname string into an pathname.
File(String parent,String child) It creates a new File instance from a parent pathname string
and a child pathname string.
File(URL url) It creates a new File instance by converting the given
file:URL into an pathname.

Methods:
Modifier and Type Method Description
static File createTempFile(String prefix,String It creates an empty file in the
suffix) default temporary file directory,
using the given prefix and suffix to
generate its name.
boolean createNewFile() It automatically creates a new,
empty file named by this abstract
pathname if and only if a file with
this name does not yet exist.
boolean canWrite() It tests whether the application can
modify the file denoted by this
abstract pathname.String[]
boolean canExecute() It tests whether the application can
execute the file denoted by this
abstract pathname.
boolean canRead() It tests whether the application can
read the file denoted by this
abstract pathname.
boolean isAbsolute() It tests whether this abstract
pathname is absolute.
boolean isDirectory() It tests whether the file denoted by
this abstract pathname is a
directory.
boolean isFile() It tests whether the file denoted by
this abstract pathname is an normal
file.
String getName() It returns the name of the file or
directory denoted by this abstract
pathname.
String getParent() It returns the pathname string of
this abstract pathname’s parent,or
null if this pathname does not
name a parent directory.

Programming in Java P.SowmyaSree Page 91


Path toPath() It returns a java.nio.file.Path object
constructed from the this abstract
path.
URL toURL() It constructs a file:URL that
represents this abstract pathname.
File[] listFiles() It returns an array of abstract
pathnames denoting the files in the
directory denoted by this abstract
pathname.
long getFreeSpace() It returns the number of
unallocated bytes in the partition
named by this abstract pathname.
String[] List(FilenameFilter filter) It returns an array of strings
naming the files and directories in
the directories in the directory
denoted by this abstract pathname
that satisfy the specified filter.
boolean mkdir() It creates the directory named by
this abstract pathname.
String getAbsolutePath() It returns the absolute path of the
file.

Example program on File class Methods:


import java.io.*;
public class FileDemo
{
public static void main(String args[])throws Exception
{
String path="",name="";
File f1=new File("testFile.txt");
if(f1.createNewFile())
{
System.out.println("New File is created!");
name=f1.getName(); Output:
System.out.println("Name of File:"+name);
path=f1.getAbsolutePath(); D:\sowmya java>javacFileDemo.java
System.out.println("Absolute File Path:"+path); D:\sowmya java>java FileDemo
} New File is created!
else Name of File:testFile.txt
{ Absolute File Path:D:\sowmya\javaprg\testFile.txt
System.out.println("File already exists.");
}
}
}

Programming in Java P.SowmyaSree Page 92


FileInputStream Class:
Java FileInputStream class obtains input bytes from a . It is used for reading byte-oriented data (streams of
raw bytes) such as image data, audio, video etc. You can also read character-stream data. But, for reading
streams of characters, it is recommended to use class.

declaration
public class FileInputStream extends InputStream

Methods:
Method Description
int available() It is used to return the estimated number of bytes that can be
read from the input stream.
int read() It is used to read the byte of data from the input stream.
int read(byte[] b) It is used to read up to b.length bytes of data from the input
stream.
int read(byte[] b, int off, intlen) It is used to read up to len bytes of data from the input
stream.
long skip(long x) It is used to skip over and discards x bytes of data from the
input stream.
FileChannelgetChannel() It is used to return the unique FileChannel object associated
with the file input stream.
FileDescriptorgetFD() It is used to return the object.
protected void finalize() It is used to ensure that the close method is call when there
is no more reference to the file input stream.
void close() It is used to closes the stream.

Example Program on FileInputStream Class:


importjava.io.FileInputStream;
public class DataStreamExample
{
public static void main(String args[])
{
try
{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=fin.read();
System.out.print((char)i);
fin.close();
} Output:
catch(Exception e)
{System.out.println(e);} D:\sowmya java>javacDataStreamExample .java
} D:\sowmya java>java DataStreamExample
} A

Programming in Java P.SowmyaSree Page 93


FileOutputStream Class
Java FileOutputStream is an output stream used for writing data to a File .
If you have to write primitive values into a file, use FileOutputStream class. You can write byte-oriented
as well as character-oriented data through FileOutputStream class. But, for character-oriented data, it is
preferred to use thanFileOutputStream.

declaration
public class FileOutputStream extends OutputStream

methods
Method Description
protected void finalize() It is used to clean up the connection with the file output
stream.
void write(byte[] ary) It is used to write ary.length bytes from the byte array
to the file output stream.
void write(byte[] ary, int off, intlen) It is used to write len bytes from the byte array starting
at offset off to the file output stream.
void write(int b) It is used to write the specified byte to the file output
stream.
FileChannelgetChannel() It is used to return the file channel object associated
with the file output stream.
FileDescriptorgetFD() It is used to return the file descriptor associated with
the stream.
void close() It is used to closes the file output stream.

FileOutputStream Example
import java.io.FileOutputStream;
public class FileOutputStreamExample
{
public static void main(String args[])
{
try
{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
}
catch(Exception e) Output:
{
System.out.println(e); D:\sowmya java>javacFileOutputStreamExample .java
} D:\sowmya java>java FileOutputStreamExample
} success...
}

Programming in Java P.SowmyaSree Page 94


Scanner Class
There are various ways to read input from keyboard; the java.util.Scanner class is one of them. The Java
Scanner class breaks the input into tokens using a delimiter, the default delimiter is whitespace.
It provides many methods to read and parse various primitive values .It is widely used to parse text for
string and primitive types using regular expression. Java Scanner class extends Object class and
implements Iterator and Closeable interfaces.

Commonly used methods of Scanner class


S.No Method Description
1 public String next() It returns the next token from the scanner.
2 public String nextLine() It moves the scanner position to the next line and returns
the value as a string.
3 public byte nextByte() It scans the next token as byte.
4 public short nextShort() It scans the next token as short value.
5. public intnextInt() It scans the next token as int value.
6. public long nextLong() It scans the next token as long value.
7. public float nextFloat () It scans the next token as float value.
8. public double next Double() It scans the next token as double value.

Example program on Scanner class:


importjava.util.*;
public class ScannerExample Output:
{
public static void main(String args[]) D:\sowmya java>javacScannerExample.java
{ D:\sowmya java>java ScannerExample
Scanner in = new Scanner(System.in); Enter your name: N.SowmyaSree
System.out.print("Enter your name: "); Hello Mr/MsN.SowmyaSree
String name = in.nextLine();
System.out.println("Hello Mr/Ms " + name);
in.close();
}
}

BufferedInputStream Class
Java BufferedInputStream is used to read information from . It internally uses buffer mechanism to make
the performance fast.
The important points about BufferedInputStream are:
o When the bytes from the stream are skipped or read, the internal buffer automatically refilled from
the contained input stream, many bytes at a time.
o When a BufferedInputStream is created, an internal buffer is created.

declaration
public class BufferedInputStream extends FilterInputStream

Programming in Java P.SowmyaSree Page 95


Constructors

constructor
Description
BufferedInputStream(InputStream IS) It creates the BufferedInputStream and saves it
argument, the input stream IS, for later use.
BufferedInputStream(InputStream IS, It creates the BufferedInputStream with a specified
int size) buffer size and saves it argument, the input stream IS,
for later use.

Methods

method
Description

int available() It returns an estimate number of bytes that can be read


from the input stream without blocking by the next
invocation method for the input stream.
int read() It read the next byte of data from the input stream.
int read(byte[] b, int off, intln) It read the bytes from the specified byte-input stream into a
specified byte array, starting with the given offset.
void close() It closes the input stream and releases any of the system
resources associated with the stream.
void reset() It repositions the stream at a position the mark method was
last called on this input stream.
void mark(intreadlimit) It sees the general contract of the mark method for the
input stream.
long skip(long x) It skips over and discards x bytes of data from the input
stream.
booleanmarkSupported() It tests for the input stream to support the mark and reset
methods.

Example of Java BufferedInputStream


import java.io.*;
public class BufferedInputStreamExample
{
public static void main(String args[])
{
try
{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=bin.read())!=-1){
System.out.print((char)i);
}
Programming in Java P.SowmyaSree Page 96
bin.close(); Output:
fin.close();
}catch(Exception e){System.out.println(e);} D:\sowmya java>javacBufferedInputStreamExample.java
} D:\sowmya java>java BufferedInputStreamExample
} Welcome to java.

BufferedOutputStream Class:
Java BufferedOutputStream is used for buffering an output stream. It internally uses buffer to store
data. It adds more efficiency than to write data directly into a stream. So, it makes the performance fast.
For adding the buffer in an OutputStream, use the BufferedOutputStream class.

Let's see the syntax for adding the buffer in an OutputStream:


OutputStreamos= new BufferedOutputStream(new FileOutputStream("D:\\IO Package\\testout.txt"));

BufferedOutputStream class declaration


public class BufferedOutputStream extends FilterOutputStream

constructors
constructor
Description

BufferedOutputStream(OutputStreamos) It creates the new buffered output stream which is used for
writing the data to the specified output stream.
BufferedOutputStream(OutputStreamos, int It creates the new buffered output stream which is used for
size) writing the data to the specified output stream with a specified
buffer size.

Methods
method
Description

void write(int b) It writes the specified byte to the buffered output stream.
void write(byte[] b, int off, intlen) It write the bytes from the specified byte-input stream into
a specified byte , starting with the given offset
void flush() It flushes the buffered output stream.

Example of BufferedOutputStream class:


import java.io.*;
public class BufferedOutputStreamExample
{
public static void main(String args[])throws Exception
{
FileOutputStreamfout=new FileOutputStream("D:\\testout.txt");
Programming in Java P.SowmyaSree Page 97
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Welcome to java.";
byte b[]=s.getBytes();
bout.write(b); Output:
bout.flush();
D:\sowmya java>javacBufferedOutputStreamExample.java
bout.close();
D:\sowmya java>java BufferedOutputStreamExample
fout.close();
success
System.out.println("success");
}
}

RandomAccessFile
This is used for reading and writing to random access file. A random access file behaves like a large of
bytes. There is a cursor implied to the array called file , by moving the cursor we do the read write
operations. If end-of-file is reached before the desired number of byte has been read than EOFExceptionis .
It is a type of IOException.

Constructor

Constructor Description
RandomAccessFile(File file,String Creates a random access file stream to read from,and
mode) optionally to write to,the file specified by the File
argument.
RandomAccessFile(String Creates a random access file stream to read from,and
name,String mode) optionally to write to, a file with the specified name.
Methods
Modifier and Type Method Description
void close() It closes this random access
file stream and releases any
system resources associated
with the stream
FileChannel getChannel() It returns the unique
FileChannel object associated
with this file.
int reading() It reads a signed 32-bit integer
from this file.
String readUTF() It reads in a string from this
file.
void seek(long pos) It sets the file-pointer offset,
measured from the beginning
of this file, at which the next
read or write occurs.
void writeDouble(double v) It converts the double
argument to along using the
doubleToLongBits method in
class Double, and then writes
that long value to the file as an

Programming in Java P.SowmyaSree Page 98


eight-byte quantity, high byte
first.
void writeFloat(float v) It converts the float argument
to an int using the
floatToIntBits method in class
Float, and then writes that int
value to the file as a four-byte
quantity, high byte first.
void write(int b) It writes the specified byte to
this file.
int read() It reads a byte of data from
this file.
long length() It returns the length of this
file.
void seek(long pos) It sets the file-pointer offset,
measured from the beginning
of this file, at which the next
read or write occurs.

program on RandomAccessFile class Output:


import java.io.*;
classRandomAccessFileExample D:\sowmya java>javac RandomAccessFileExample.java
{ D:\sowmya java>java RandomAccessFileExample
public static void main(String args[]) Length of File After writing Data:200
{ First Number is :0
try Second Number is :1
{ Current Length of File is :204

RandomAccessFile file=new RandomAccessFile("testFile.txt","rw");


file.setLength(0);
for(int i=0;i<50;i++)
{
file.writeInt(i);
}
System.out.println("Length of File After writing Data:"+file.length());
file.seek(0);
System.out.println("First Number is :"+file.readInt());
file.seek(1*4);
System.out.println("Second Number is :"+file.readInt());
file.writeInt(101);
file.seek(file.length());
file.writeInt(50);
System.out.println("Current Length of File is :"+file.length());
}
catch(Exception e)
{
e.printStackTrace();}}}
Programming in Java P.SowmyaSree Page 99
Unit-IV
Chapter -1
Applets

An applet is a Java program that runs in a web browser.

Introduction:
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. It Secured and can be executed by browsers running under
many platforms, including Linux, Windows, Mac Os etc. Plug-in is required at client browser to execute
applet
Java Plug-in is required in the browser at client side to execute applet. Java Plug-in is a software
product that serves as a bridge between a browser and an external Java Runtime Environment (JRE).

Applets Example: Every Applet application must import two packages

1. java.awt.*: Imports the Abstract Window Toolkit (AWT)classes. Applets interact with the
user(either directly or indirectly)through the AWT. The AWT contains support for a window-based,
graphical user interface.
2. The java.applet.*: Imports the applet package, which contains the class Applet. Every applet that
you create must be a subclass of Applet class.

Steps to create an Applet example:

1. Create the applet with filename as HelloWorldApplet.java

import java.applet.Applet;
import java.awt.Graphics;
//Every applet must extend from java.applet.Applet class
public class HelloWorldApplet extends Applet
{
//paint method is called every time applet redisplay its output
public void paint(Graphics g)
{
g.drawString("Hello World",50,50);
}
}

2. Compile the above HelloWorldApplet.java applet.


D:\sowmyajava>javac HelloWorldApplet.java

3. Create a html file, example “HelloWorldApplet.html” and place the applet code in html file.
<html>
<body>
<applet code="HelloWorldApplet.class" width="300" height="300">
</applet>
</body>
</html>
Programming in Java P.SowmyaSree Page 100
4. There are two ways to run an applet.
❖ Executing the Applet within Java-compatible web browser. For executing an Applet in an
web browser, create short HTML file in the same directory and Run the HTML file then the
output is as follows:

❖ Using an Applet viewer, such as the standard tool, applet viewer. An applet viewer executes
your applet in a window.
5. Execute the applet using applet viewer tool at command prompt as shown below-
D:\sowmyajava>appletviewer HelloWorldApplet.html

The class in the program must be declared ad public ,because it will be accessed by code that is outside the
program
Every Every Applet application must declare a paint() method. This method is defined by
AWT class and must be overridden by the applet. The paint( ) method is called each time when an applet
needs to redisplay its output.

Another important thing to notice about applet application is that, execution of an applet does not
begin at main( )method. In fact an applet application does not have any main( ) method.

Applet life cycle:

Programming in Java P.SowmyaSree Page 101


Whenever an applet is created, it undergoes a series of changes from initialization to
destruction.
Various stages of an applet life cycle are depicted in the figure above.

1. Initial State: When a new applet is born or created, it is activated by calling init( ) method, At
this stage, new objects to the applet are created ,initial values are set, images are loaded and the
colors of the images are set. An applet is initialized only once in its lifetime.
2. Running State:An applet achieves the running state when the system calls the start() method.
This occurs as soon as the applet is initialized. An applet may also start when it is in idle state.
3. Idle State: An applet comes in idle state when its execution has been stopped either implicitly
or explicitly. An applet is implicitly stopped when we leave the page containing the currently
running applet. An applet is explicitly stopped when we call stop() method to stop its execution.
4. Dead State:An applet is in dead state when it has been removed from the memory. This can be
done by using destroy ( ) method.
5. Paint() : Apart from the above stages, Java applet also possess paint( ) method. This method
helps in drawing, writing and creating colored backgrounds of the applet. It takes an argument
of the graphics class. To use The graphics, imports the package java.awt.Graphics.

Applet Class:Applet class provides all necessary support for applet execution, such as initializing and
destroying of applet. It also provide methods that load and display images and methods that load and play
audio clips.
Most applets override these four methods. These four methods forms Applet lifecycle.

public void init(): init() is the first method to be called. This is where variable are initialized. This
method is called only once during the runtime of applet.

public void start(): start( ) method is called after init( ).This method is called to restart an applet after it
has been stopped.
public void stop(): stop( ) method is called to suspend thread that does not need to run when applet is not
visible.

public void destroy(): destroy( ) method is called when your applet needs to be removed completely from
memory.

Programming in Java P.SowmyaSree Page 102


public void stop(): stop( ) method is called to suspend thread that does not need to run when applet is not
visible.

public void destroy(): destroy( ) method is called when your applet needs to be removed completely from
memory.

Program to show functions of Applet class:

1. Create the applet with filename as MyApplet.java

import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet
{
public void init()
{
setName("My Applet");
}
public void paint(Graphics g)
{
g.setColor(Color.red);
g.drawRoundRect(10,30,120,120,2,3);
}
}

2. Compile the above MyApplet.java applet.


D:\sowmyajava>javac MyApplet.java

3. Create the html file,example “MyApplet.html” and place the applet code in html file.

<html>
<body>
<applet code="MyApplet.class" width="300" height="300">
</applet>
</body>
</html>

4. Execute the applet using applet viewer tool at command prompt as shown below:
D:\sowmyajava>appletviewer MyApplet.html

Programming in Java P.SowmyaSree Page 103


Common Methods Used in Displaying the output:

Applets are displayed in a window and they use the AWT to perform input and output functions. Below are
the common methods used for displaying the output-

➢ To output a string to an applet, use drawstring( ),which is a member of the Graphics class.
Typically, it is called from within either update( ) or paint( ).It has the following general form:
voiddrawString(String message,intx,int y)
Here, message is the string to be output beginning at x,y. In a Java window, the upper-left corner is
location 0,0. The drawString( ) method will not recognize newline characters. If we want to start a line of
text in another line, we must do it manually, specifying the X,Y location where we want the line to begin.

➢ To set the background color of an applets window, we use setBackground( )


To set the foreground color, we use setForeground( ).These methods are defined y Component, and
have the general forms:
voidsetBackground(ColornewColor)
voidsetForeground(ColornewColor)
Here, newColor specifies the new color.The class Color defines the following values that can be used to
specify colors:
✓ Color.black
✓ Color.magenta
✓ Color.blue
✓ Color.orange
✓ Color.cyan
✓ Color.pink
✓ Color.darkGray
✓ Color.red
✓ Color.gray
✓ Color.white
✓ Color.green
✓ Color.yellow
✓ Color.lightGray
For example, this sets the background color to blue and the text color to yellow:
setBackground(Color.blue);
setBackground(Color.yellow);

Programming in Java P.SowmyaSree Page 104


we can change these colors as and when required during the execution of the applet.The default foreground
color is black.The default background color is lightgray.

➢ We can obtain the current settings for background and foreground colors by calling getBackground(
) and getForeground( ),respectively.They are also defined by Component and bear the general form:
ColorgetBackground( )
ColorgetForeground( )

Program to change color of the foreground and background:


1. Create the applet with filename as MyApplet.java

importjava.applet.*;
importjava.awt.*;
public class MyApplet1 extends Applet
{
public void init()
{
setName("My Applet");
}
public void paint(Graphics g)
{
setBackground(Color.Green);
setForeground(Color.RED);
g.drawString("Using Colors in Applet",50,100);
}
}
2. Compile the above MyApplet1.java applet.
D:\sowmyajava>javac MyApplet1.java

3. Create the html file,example “MyApplet1.html” and place the applet code in html file
<html>
<body>
<applet code="MyApplet1.class" width="250" height="250"></applet></body>
</html>

4. Execute the applet using applet viewer tool at


command prompt as shown below

D:\sowmyajava>appletviewer MyApplet1.html

Programming in Java P.SowmyaSree Page 105


Chapter-2
Event Handling

Changing the state of an object is known as an event. Event handling is the process of how events
generated in Java GUI application are processed or handled.

Introduction: Any program that uses GUI (Graphical User Interface)such as Java application written for
windows, is event driven. Event describes the change in state of any object.

For Example: Pressing a button, Entering a character in Textbox, Clicking or Dragging a mouse, etc.

Event handling has three main components:

1. Events: An event is a change in state of an object.


2. Event Source: Event source is an object that generates an event.
3. Listeners: A listener is an object that listens to the event. A listener gets notified when an event
occurs.

Event handling process:A source generates an Event and sends it to one or more listeners registered with
the source. Once event is received by the listener, they process the event and then return. Events are
supported by a number of Java packages, like java.util, java.awt and java.awt.event.

Steps to handle events:


1. Implement appropriate interface in the class.
2. Register the component with the listener.

Types of Events:

Important Event Classes and Interface:


Event Classes Description Listener Interface
ActionEvent Generated when button is pressed, ActionListener
menu-item is selected, list-item is
double clicked.
MouseEvent Generated when mouse is dragged, MouseListener
moved, clicked, pressed or released and
also when it enters or exit a component.
KeyEvent Generated when input is received from KeyListener
keyboard.
ItemEvent Generated when check-box or list item ItemListener
is clicked.
TextEvent Generated when value of textarea or TextListener
textfield is changed
MouseWheelEvent Generated when mouse wheel is moved MouseWheelListener

WindowEvent Generated when window is activated, WindowListener


deactivated, deiconified, iconified,
opened or closed.
ComponentEvent Generated when component is hidden, ComponentEventListener
Programming in Java P.SowmyaSree Page 106
moved, resized or set visible.
ContainerEvent Generated when component is added or ContainerListener
removed from container.
AdjustmentEvent Generated when scroll bar is AdjustmentListener
manipulated
FocusEvent Generated when component gains or FocusListener
loses keyboard focus

Example program on Event Handling


import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class EventApplet extends Applet implements ActionListener
{
Button b;
TextFieldtf;
public void init()
{
tf=new TextField();
tf.setBounds(30,40,150,20);
b=new Button("Click");
b.setBounds(80,150,60,50);
add(b);
add(tf);
b.addActionListener(this);
setLayout(null);
}
public void actionPerformed(ActionEvent e)
{
tf.setText("Welcome");
}
}
Save the above program with EventApplet.java

//EventApplet.html
<html>
<body>
<applet code="EventApplet.class" width="300" height="300">
</applet>
</body>
</html>

Programming in Java P.SowmyaSree Page 107


Output:
After clicking on “Click” button

Programming in Java P.SowmyaSree Page 108


Chapter-3
AWT

Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications in
java.
Java AWT components are platform-dependent i.e. components are displayed according to the view of
operating system. AWT is heavyweight i.e. its components are using the resources of OS.
The java.awt package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.

AWT Hierarchy

Component class: Component class is at the top of AWT hierarchy. Component is an abstract class that
encapsulates all the attributes of visual component. A component object is responsible for remembering the
current foreground and background colors and the currently selected text font.

Container:
The Container is a component in AWT that can contain another component like buttons, textfields,
labels etc. The classes that extends Container class are known as container such as Frame, Dialog and
Panel.

Window:
The window is the containers that have no borders and menu bars. You must use frame, dialog or
another window for creating a window.

Panel:
The panel is the container that doesn’t contain title bar, border or menu bars. It can have other
components like button, textfield etc.

Programming in Java P.SowmyaSree Page 109


Frame:
Frame is a top-level container which is used to hold components in it. Components such as a button,
checkbox, radio button, menu, list, table etc. In Java, most of the AWT applications are created using
Frame window.

Constructors of Frame:

Constructor Description
public Frame( ) Creates a Frame window with no name.
public Frame(String name) Creates a Frame window with a name.

Frame Methods:

Methods Description
Public void add(Component comp) This method adds the component, comp, to the
container Frame.
Public void setLayout(LayoutManger object) This method sets the layout of the components
in a container, Frame.
Public void remove(Component comp) This method removes a component, comp,
from the container, Frame.
Public void This method sets the size of a Frame in terms
setSize(intwidthPixel,intheightPixel) of pixels.

BorderLayout is the default layout manager of Frame:

The default layout of Frame by which it positions the components in it is BorderLayout, manager.
Hence, if we add components to a Frame without calling it’s setLayout( ) method, these components are
automatically added to the center region using BorderLayout manager.
Note: Remember, using the BorderLayout manager, only one component can be placed in a region, hence
if multiple elements are added to a region, only the last element will be visible.

Creating a Frame:

There are two ways to create a Frame.


They are:
1. By Instantiating Frame class.
2.By extending Frame class.

• Creating Frame Window by Instantiating Frame class:


import java.awt.*;
class FrameExample
{
Frame frame;
Label label;
Button button;
FrameExample()
{
Programming in Java P.SowmyaSree Page 110
frame=new Frame("Frame");
label=new Label("Welcome!");
button=new Button("Button1");

//Setting layout of components in Frame to FlowLayoutframe.setLayout(new FlowLayout( ));

frame.add(label);
frame.add(button);
frame.setSize(250,200);
frame.setVisible(true);
}
public static void main(String args[])
{
new FrameExample();
}
}

Output:

D:\sowmyajava>javac FrameExample.java

D:\sowmyajava>java FrameExample

Button

The button class is used to create a labeled button that has platform independent implementation. The
application result in some action when the button is pushed.

Button Class declaration


public class Button extends Component implements Accessible

Button Example program


import java.awt.*;
public class ButtonExample
{
public static void main(String[] args)
{
Frame f=new Frame("Button Example");
Button b=new Button("Click Here");
b.setBounds(50,100,80,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true); }}

Programming in Java P.SowmyaSree Page 111


Output:

D:\sowmyajava>javac ButtonExample.java
D:\sowmyajava>java ButtonExample

Button Example with ActionListener


import java.awt.*;
import java.awt.event.*;
public class ButtonExample1
{
public static void main(String[] args)
{
Frame f=new Frame("Button Example");
final TextFieldtf=new TextField();
tf.setBounds(50,50, 150,20);
Button b=new Button("Click Here");
b.setBounds(50,100,60,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Javatpoint.");
}
});
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

Output:

D:\sowmyajava>javac ButtonExample1.java
D:\sowmyajava>java ButtonExample1

Label

Programming in Java P.SowmyaSree Page 112


The object of Label class is a component for placing text in a container. It is used to display a single line of
read only text. The text can be changed by an application but a user cannot edit it directly.
Label Class Declaration
public class Label extends Component implements Accessible
Label Example
import java.awt.*;
class LabelExample
{
public static void main(String args[])
{
Frame f= new Frame("Label Example");
Label l1,l2;
l1=new Label("First Label.");
l1.setBounds(50,100, 100,30);
l2=new Label("Second Label.");
l2.setBounds(50,150, 100,30);
f.add(l1); f.add(l2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

Output:

D:\sowmyajava>javac LabelExample.java
D:\sowmyajava>java LabelExample

Checkbox

The Checkbox class is used to create a checkbox. It is used to turn an option on (true) or off (false).
Clicking on a Checkbox changes its state from "on" to "off" or from "off" to "on".
Checkbox ClassDeclaration
public class Checkbox extends Component implements ItemSelectable, Accessible

Programming in Java P.SowmyaSree Page 113


Checkbox Example
import java.awt.*;
public class CheckboxExample
{
CheckboxExample()
{
Frame f= new Frame("Checkbox Example");
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100,100, 50,50);

f.add(checkbox1);
f.add(checkbox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxExample();
}
}

Output:
D:\sowmyajava>javac CheckboxExample.java
D:\sowmyajava>java CheckboxExample

Radio Buttons/CheckboxGroup:

The object of CheckboxGroup class is used to group together a set of Checkbox. At a time only one
check box button is allowed to be in "on" state and remaining check box button in "off" state. It inherits
the object class.

CheckboxGroup Example
import java.awt.*;
public class CheckboxGroupExample
{
CheckboxGroupExample()
{
Frame f= new Frame("CheckboxGroup Example");
CheckboxGroupcbg = new CheckboxGroup();
Checkbox checkBox1 = new Checkbox("C++", cbg,
false);
checkBox1.setBounds(100,100, 50,50);
Checkbox checkBox2 = new Checkbox("Java", cbg,
true);
checkBox2.setBounds(100,150, 50,50);

Programming in Java P.SowmyaSree Page 114


f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxGroupExample(); }}
Output:

D:\sowmyajava>javac CheckboxGroupExample.java
D:\sowmyajava>java CheckboxGroupExample

Container Class:
Container is the super class of all Java containers.
Following is the Container class signature-

public class Container extends Component

Important methods of the Container class are:


✓ Add( ):This method is overloaded with which a component can be added to the container.
✓ Invalidate( ):Used to invalidate the present set up of components in the container.
✓ Validate( ):Used to revalidate the current set up of components after calling invalidate( ).
The important container used very often are applets, frames and panels.

Layouts:
The java.awt library provides 5 basic layouts. Each layout has its own significance and all of them
are completely different. The 5 layouts available in the java.awt library are:
1. Border Layout.
2. Grid Layout.
3. Card Layout.
4. Flow Layout

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:

Example program on border layout:


import java.awt.*;
import javax.swing.*;

public class Border {


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

Programming in Java P.SowmyaSree Page 115


JButton b1=new JButton("NORTH");;
JButton b2=new JButton("SOUTH");;
JButton b3=new JButton("EAST");;
JButton b4=new JButton("WEST");;
JButton b5=new JButton("CENTER");;

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

Output:
D:\sowmyajava>javac Border.java
D:\sowmyajava>java Border

Grid Layout:
A GridLayout is a more organized way of arranging components. It divides the frame or
panel in the form of a grid containing evenly distributed cells. Each component get added to a particular
cell. The order of placement of components is directly dependant on the order in which they are added to
the frame or panel. The below image shows a 2 column 3 row GridLayout based Frame.

Example program on Grid layout:


import java.awt.*;
import javax.swing.*;

public class MyGridLayout{


JFrame f;
MyGridLayout(){
f=new JFrame();

JButton b1=new JButton("1");


JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
JButton b8=new JButton("8");
JButton b9=new JButton("9");

Programming in Java P.SowmyaSree Page 116


f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.add(b6);f.add(b7);f.add(b8);f.add(b9);

f.setLayout(new GridLayout(3,3));
//setting grid layout of 3 rows and 3 columns

f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyGridLayout();
}
}

Output:
D:\sowmyajava>javac MyGridLayout.java
D:\sowmyajava>java MyGridLayout

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

Example program on Card Layout


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutExample extends JFrame implements ActionListener
{
CardLayout card;
JButton b1,b2,b3;
Container c;
CardLayoutExample()
{

c=getContentPane();
card=new CardLayout(40,30);
//create CardLayout object with 40 hor space and 30 ver space
c.setLayout(card);

b1=new JButton("Apple");
b2=new JButton("Boy");
b3=new JButton("Cat");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);

c.add("a",b1);c.add("b",b2);c.add("c",b3);

Programming in Java P.SowmyaSree Page 117


}
public void actionPerformed(ActionEvent e)
{ card.next(c); }

public static void main(String[] args)


{
CardLayoutExample cl=new CardLayoutExample();
cl.setSize(400,400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}

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.
Example program on FlowLayout
import java.awt.*;
import javax.swing.*;

public class MyFlowLayout{


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

JButton b1=new JButton("1");


JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("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();
}
}

Output:
D:\sowmyajava>javac MyFlowLayout.java

Programming in Java P.SowmyaSree Page 118


D:\sowmyajava>java MyFlowLayout

Unit-III
Chapter-4
Swing

Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-based applications. It
is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in java.
Unlike AWT, Java Swing provides platform-independent and lightweight components.
The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu, JColorChooser etc.

Differences between Swing and AWT:

No AWT SWING
1 AWT components are platform- Java swing components are platform-
dependent. independent.
2 AWT components are heavyweight. Swing components are lightweight.
3 AWT doesn't support pluggable look Swing supports pluggable look and feel.
and feel.
4 AWT provides less components than Swing provides more powerful components
Swing. such as tables, lists, scrollpanes,
colorchooser, tabbedpane etc.
5 AWT doesn't follows MVC(Model Swing follows MVC.
View Controller) where model
represents data, view represents
presentation and controller acts as an
interface between model and view.

Hierarchy of Java Swing classes

Programming in Java P.SowmyaSree Page 119


JFrame

The javax.swing.JFrame class is a type of container which inherits the java.awt.Frame class.
JFrame works like the main window where components like labels, buttons, textfields are added to create a
GUI.

Unlike Frame, JFrame has the option to hide or close the window with the help of
setDefaultCloseOperation(int) method.

Constructors
Constructor Description
JFrame() It constructs a new frame that is initially invisible.
JFrame(GraphicsConfigurationgc) It creates a Frame in the specified GraphicsConfiguration of
a screen device and a blank title.
JFrame(String title) It creates a new, initially invisible Frame with the specified
title.
JFrame(String title, It creates a JFrame with the specified title and the specified
GraphicsConfigurationgc) GraphicsConfiguration of a screen device.

Methods
Modifier Method Description
and type
Adds the specified child Component.
protected addImpl(Component comp,
void Object constraints, int index)

protected createRootPane() Called by the constructor methods to create


JRootPane the default rootPane.
protected
void frameInit() Called by the constructors to init the
JFrame properly.

void setContentPane(ContainecontentP
ane) It sets the contentPane property

static void setDefaultLookAndFeelDecorate Provides a hint as to whether or not newly


d(booleandefaultLookAndFeelDe created JFrames should have their Window
corated) decorations (such as borders, widgets to
close the window, title...) provided by the
current look and feel.
void It sets the image to be displayed as the icon
setIconImage(Image image) for this window.

void setJMenuBar(JMenuBarmenubar) It sets the menubar for this frame.


void setLayeredPane(JLayeredPanelay It sets the layeredPane property.

Programming in Java P.SowmyaSree Page 120


eredPane)
JRootPane getRootPane()
It returns the rootPane object for this
frame.

TransferHand getTransferHandler() It gets the transferHandler property.


ler

JFrame Example
import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame

JButton b=new JButton("click");//creating instance of


JButton
b.setBounds(130,100,100, 40);//x axis, y axis, width, height

f.add(b);//adding button in JFrame

f.setSize(400,500);//400 width and 500 height


f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
}

Output:

D:\sowmyajava>javac FirstSwingExample.java
D:\sowmyajava>java FirstSwingExample

Japplet

As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of swing. The JApplet
class extends the Applet class.

Example program on Japplet


import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
public class EventJApplet extends JApplet implements ActionListener{
JButton b;
JTextFieldtf;
public void init()
{
tf=new JTextField();
tf.setBounds(30,40,150,20);
b=new JButton("Click");

Programming in Java P.SowmyaSree Page 121


b.setBounds(80,150,70,40);
add(b);add(tf);
b.addActionListener(this);
setLayout(null);
}
public void actionPerformed(ActionEvent e)
{
tf.setText("Welcome");
}
}
In the above example, we have created all the controls in init() method because it is invoked only once.
EventJapplet.html

<html>
<body>
<applet code="EventJApplet.class" width="300"
height="300">
</applet>
</body>
</html>

Output:
D:\sowmyajava>javac EventJApplet.java
D:\sowmyajava>appletviewer EventJApplet.html

JPanel

The JPanel is a simplest container class. It provides space in which an application can attach any other
component. It inherits the JComponents class.
It doesn't have title bar.

Declaration
public class JPanel extends JComponent implements Accessible

JPanel Example
import java.awt.*;
import javax.swing.*;
public class PanelExample
{
PanelExample()
{
JFrame f= new JFrame("Panel Example");
JPanel panel=new JPanel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
JButton b1=new JButton("Button 1");
b1.setBounds(50,100,80,30);

Programming in Java P.SowmyaSree Page 122


b1.setBackground(Color.yellow);
JButton b2=new JButton("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1); panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PanelExample();
}
}
Output:
D:\sowmyajava>javac PanelExample.java
D:\sowmyajava>java PanelExample

Jtable: The JTable class is used to display data in tabular form. It is composed of rows and columns.
JTable Example
import javax.swing.*;
public class TableExample
{
JFrame f;
TableExample()
{
f=new JFrame();
String data[][]={ {"101","Amit","670000"},
{"102","Jai","780000"},
{"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"};
JTablejt=new JTable(data,column);
jt.setBounds(30,40,200,300);
JScrollPanesp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
}
public static void main(String[] args)
{
new TableExample();
}
}
Output:
D:\sowmya\javaprg>javac TableExample.java
D:\sowmya\javaprg>java TableExample

Programming in Java P.SowmyaSree Page 123


JDialog

The JDialog control represents a top level window with a border and a title used to take some form of input
from the user. It inherits the Dialog class.
Unlike JFrame, it doesn't have maximize and minimize buttons.

JDialog Example
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DialogExample
{
private static JDialog d;
DialogExample()
{
JFrame f= new JFrame();
d = new JDialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
JButton b = new JButton ("OK");
b.addActionListener ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
DialogExample.d.setVisible(false);
}
});
d.add( new JLabel ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[])
{
new DialogExample();
}
}

Output:
D:\sowmya\javaprg>javac DialogExample.java
D:\sowmya\javaprg>java DialogExample

Programming in Java P.SowmyaSree Page 124


Programming in Java P.SowmyaSree Page 125

You might also like