java honors

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

Unit - 1

OOPS Concepts and Java Programming:

Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in
programming. The main aim of OOPs is to bind together the data and the functions that operate on them so that no other part of
the code can access this data except that function.
OOPS concepts are as follows:
● Class
● Object
● Method and method passing
Pillars of OOPs:
● Abstraction
● Encapsulation
● Inheritance
● Polymorphism
○ Compile-time polymorphism
○ Runtime polymorphism
Class:
A class is a user-defined blueprint or prototype from which objects are created. It represents the set of properties or
methods that are common to all objects of one type. Using classes, you can create multiple objects with the same behavior instead
of writing their code multiple times. This includes classes for objects occurring more than once in your code. In general, class
declarations can include these components in order:

Modifiers: A class can be public or have default access (Refer to this for details).
Class name: The class name should begin with the initial letter capitalized by convention.
Superclass (if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only
extend (subclass) one parent.
Interfaces (if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A
class can implement more than one interface.
Body: The class body is surrounded by braces, { }.

An object is a basic unit of Object-Oriented Programming that represents real-life entities. A typical Java program creates
many objects, which as you know, interact by invoking methods. The objects are what perform your code, they are the part of your
code visible to the viewer/user. An object mainly consists of:
Example Program of Class:-
public class College {

static String Employee_name;


static float Employee_salary;
static void set(String n, float p) {
Employee_name = n;
Employee_salary = p;
}
static void get() {
System.out.println("Employee name is: " +Employee_name );
System.out.println("Employee CTC is: " + Employee_salary);
}
public static void main(String args[]) {
College.set("Krishna", 10000.0f);
College.get();
}
}
Abstraction:-
Data Abstraction is the property by virtue of which only the essential details are displayed to the user. The trivial or
non-essential units are not displayed to the user. Ex: A car is viewed as a car rather than its individual components.
Data Abstraction may also be defined as the process of identifying only the required characteristics of an object, ignoring
the irrelevant details. The properties and behaviors of an object differentiate it from other objects of similar type and also help in
classifying/grouping the object.
Consider a real-life example of a man driving a car. The man only knows that pressing the accelerators will increase the
car speed or applying brakes will stop the car, but he does not know how on pressing the accelerator, the speed is actually
increasing. He does not know about the inner mechanism of the car or the implementation of the accelerators, brakes etc. in the
car. This is what abstraction is.
//abstract class
abstract class College{
//abstract methods declaration
abstract void add();
abstract void mul();
abstract void div();
}
Encapsulation
It is defined as the wrapping up of data under a single unit. It is the mechanism that binds together the code and the data it
manipulates. Another way to think about encapsulation is that it is a protective shield that prevents the data from being accessed by
the code outside this shield.
Encapsulation can be achieved by declaring all the variables in a class as private and writing public methods in the class
to set and get the values of the variables.

class Employee {
private int empid;
private String ename;
}
Inheritance
Inheritance is an important pillar of OOP (Object Oriented Programming). It is the mechanism in Java by which one class is allowed
to inherit the features (fields and methods) of another class. We are achieving inheritance by using extends keyword. Inheritance is
also known as “is-a” relationship.
Superclass: The class whose features are inherited is known as superclass (also known as base or parent class).
Subclass: The class that inherits the other class is known as subclass (also known as derived or extended or child class).
The subclass can add its own fields and methods in addition to the superclass fields and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already
a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are
reusing the fields and methods of the existing class.

//base class or parent class or super class


class A{
//parent class methods
void method1(){}
void method2(){}
}
//derived class or child class or base class
class B extends A{ //Inherits parent class methods
//child class methods
void method3(){}
void method4(){}
}
Polymorphism
It refers to the ability of object-oriented programming languages to differentiate between entities with the same name
efficiently. This is done by Java with the help of the signature and declaration of these entities. The ability to appear in many forms
is called polymorphism.
Polymorphism in Java is mainly of 2 types:
● Overloading
● Overriding

// Java program to Demonstrate Polymorphism


// This class will contain
// 3 methods with same name,
// yet the program will
// compile & run successfully
public class Sum {
// Overloaded sum().
// This sum takes two int parameters
public int sum(int x, int y)
{
return (x + y);
}
// Overloaded sum().
// This sum takes three int parameters
public int sum(int x, int y, int z)
{
return (x + y + z);
}
// Overloaded sum().
// This sum takes two double parameters
public double sum(double x, double y)
{
return (x + y);
}
// Driver code
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}
—------------------------------------------------------

Procedural Programming vs Object-Oriented Programming

Below are some of the differences between procedural and object-oriented programming:

Procedural Oriented Programming Object-Oriented Programming

In procedural programming, the program is divided into small In object-oriented programming, the program is divided into
parts called functions. small parts called objects.

Procedural programming follows a top-down approach. Object-oriented programming follows a bottom-up


approach.

There is no access specifier in procedural programming. Object-oriented programming has access specifiers like
private, public, protected, etc.

Adding new data and functions is not easy. Adding new data and function is easy.

Procedural programming does not have any proper way of hiding Object-oriented programming provides data hiding so it is
data so it is less secure. more secure.

In procedural programming, overloading is not possible. Overloading is possible in object-oriented programming.

In procedural programming, there is no concept of data hiding and In object-oriented programming, the concept of data hiding
inheritance. and inheritance is used.

In procedural programming, the function is more important than In object-oriented programming, data is more important
the data. than function.

Procedural programming is based on the unreal world. Object-oriented programming is based on the real world.

Procedural programming is used for designing medium-sized Object-oriented programming is used for designing large
programs. and complex programs.

Procedural programming uses the concept of procedure Object-oriented programming uses the concept of data
abstraction. abstraction.

Code reusability absent in procedural programming, Code reusability present in object-oriented programming.

Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.

—---------------------------------------
Java Programming
A First Simple Program

Now that the basic object-oriented underpinning of Java has been discussed, let’s look at some actual Java programs. Let’s start by
compiling and running the short sample program shown here. As you will see, this involves a little more work than you might
imagine.
/* This is a simple Java program.
Call this file "Example.java".
*/
class Example {
// Your program begins with a call to main().
public static void main(String args[])
{
System.out.println("This is a simple Java program.");
}}

Entering the Program:

For most computer languages, the name of the file that holds the source code to a program is immaterial. However, this is
not the case with Java.
The first thing that you must learn about Java is that the name you give to a source file is very important.
For this example, the name of the source file should be Example.java. Let’s see why. In Java, a source file is officially
called a compilation unit.
It is a text file that contains (among other things) one or more class definitions. (For now, we will be using source files that
contain only one class.)
The Java compiler requires that a source file use the .java filename extension. As you can see by looking at the program,
the name of the class defined by the program is also Example.
This is not a coincidence. In Java, all code must reside inside a class. By convention, the name of the main class should
match the name of the file that holds the program.
You should also make sure that the capitalization of the filename matches the class name. The reason for this is that Java
is case-sensitive.
At this point, the convention that filenames correspond to class names may seem arbitrary. However, this convention
makes it easier to maintain and organize your programs.
Compiling the Program To compile the Example program, execute the compiler, javac, specifying the name of the source
file on the command line, as shown here:
C:\>javac Example.java
The javac compiler creates a file called Example.class that contains the bytecode version of the program. As discussed earlier, the
Java bytecode is the intermediate representation of your program that contains instructions the Java Virtual Machine will execute.
Thus, the output of javac is not code that can be directly executed.
To actually run the program, you must use the Java application launcher called java. To do so, pass the class name
Example as a command-line argument, as shown here:
C:\>java Example
When the program is run, the following output is displayed:
This is a simple Java program.
The Java Keywords

Datatypes:-
The Primitive Types
Java defines eight primitive types of data: byte, short, int, long, char, float, double, and boolean.
The primitive types are also commonly referred to as simple types, and both terms will be used in this book. These can be put in
four groups:
• Integers This group includes byte, short, int, and long, which are for whole-valued signed numbers.
•Floating-point numbers This group includes float and double, which represent numbers with fractional precision.
•Characters This group includes char, which represents symbols in a character set, like letters and numbers.
•Boolean This group includes boolean, which is a special type for representing true/false values.
Integers
Java defines four integer types: byte, short, int, and long. All of these are signed, positive and negative values. Java does
not support unsigned, positive-only integers.
byte
The smallest integer type is byte. This is a signed 8-bit type that has a range from –128 to 127. Variables of type byte are
especially useful when you’re working with a stream of data from a network or file. They are also useful when you’re working with
raw binary data that may not be directly compatible with Java’s other built-in types.
Byte variables are declared by use of the byte keyword. For example, the following declares two byte variables called b
and c:
byte b, c;
short
short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably the leastused Java type. Here are some
examples of short variable declarations:
short s;
short t;
int
The most commonly used integer type is int. It is a signed 32-bit type that has a range from –2,147,483,648 to
2,147,483,647. In addition to other uses, variables of type int are commonly employed to control loops and to index arrays.
long
long is a signed 64-bit type and is useful for those occasions where an int type is not large enough to hold the desired
value. The range of a long is quite large. This makes it useful when big, whole numbers are needed
int lightspeed;
long days;
long seconds;
long distance;

Floating-Point Types
Floating-point numbers, also known as real numbers, are used when evaluating expressions that require fractional
precision. For example, calculations such as square root, or transcendentals such as sine and cosine, result in a value whose
precision requires a floating point type.
float
The type float specifies a single-precision value that uses 32 bits of storage. Single precision is faster on some processors
and takes half as much space as double precision, but will become imprecise when the values are either very large or very small.
Variables of type float are useful when you need a fractional component, but don’t require a large degree of precision.
For example, float can be useful when representing dollars and cents.
Here are some example float variable declarations:
float hightemp, lowtemp;
double
Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double precision is actually faster than
single precision on some modern processors that have been optimized for high-speed mathematical calculations. All
transcendental math functions, such as sin( ), cos( ), and sqrt( ), return double values. When you need to maintain accuracy over
many iterative calculations, or are manipulating large-valued numbers, double is the best choice.
Here is a short program that uses double variables to compute the area of a circle: // Compute the area of a circle.
class Area {
public static void main(String args[]) {
double pi, r, a; r = 10.8;
// radius of circle pi = 3.1416;
// pi, approximately
a = pi * r * r;
// compute area
System.out.println("Area of circle is " + a);
}}

Characters
In Java, the data type used to store characters is char. However, C/C++ programmers beware: char in Java is not the
same as char in C or C++. In C/C++, char is 8 bits wide. This is not the case in Java.Instead, Java uses Unicode to represent
characters. Unicode defines a fully international character set that can represent all of the characters found in all human languages.
Unicode required 16 bits. Thus, in Java char is a 16-bit type. The range of a char is 0 to 65,536. There are no negative chars. The
standard set of characters known as ASCII still ranges from 0 to 127 as always, and the extended 8-bit character set, ISO-Latin-1,
ranges from 0 to 255.
Here is a program that demonstrates char variables:
// Demonstrate char data type.
class CharDemo {
public static void main(String args[]) {
char ch1, ch2; ch1 = 88;
// code for X ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}}
Booleans
Java has a primitive type, called boolean, for logical values. It can have only one of two possible values, true or false. This is the
type returned by all relational operators, as in the case of a < b. boolean is also the type required by the conditional expressions
that govern the control statements such as if and for.
Here is a program that demonstrates the boolean type :
// Demonstrate boolean values.
class BoolTest {
public static void main(String args[]) {
boolean b;
b = false;
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b);
// a boolean value can control the if statement
if(b) System.out.println("This is executed.");
b = false;
if(b) System.out.println("This is not executed.");
// outcome of a relational operator is a boolean value
System.out.println("10 > 9 is " + (10 > 9));
}}
Escape Sequence Characters:

Scope and Lifetime of Variables


A block defines a scope. Thus, each time you start a new block, you are creating a new scope. A scope determines what
objects are visible to other parts of your program. It also determines the lifetime of those objects.The scope defined by a method
begins with its opening curly brace. However, if that method has parameters, they too are included within the method’s scope.
Although this book will look more closely at parameters, they work the same as any other method variable.
Scopes can be nested. For example, each time you create a block of code, you are creating a new, nested scope. When
this occurs, the outer scope encloses the inner scope. This means that objects declared in the outer scope will be visible to code
within the inner scope. However, the reverse is not true. Objects declared within the inner scope will not be visible outside it.
// Demonstrate block scope.
class Scope {
public static void main(String args[]) {
int x;
// known to all code within main
x = 10;
if(x == 10) {
// start new scope
int y = 20;
// known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y); x = y * 2;
}
// y = 100;
// Error! y not known here // x is still known here.
System.out.println("x is " + x);
}}
As the comments indicate, the variable x is declared at the start of main( )’s scope and is accessible to all subsequent code within
main( ). Within the if block, y is declared. Since a block defines a scope, y is only visible to other code within its block. This is why
outside of its block, the line y = 100; is commented out. If you remove the leading comment symbol, a compile-time error will occur,
because y is not visible outside of its block. Within the if block, x can be used because code within a block (that is, a nested scope)
has access to variables declared by an enclosing scope.
Within a block, variables can be declared at any point, but are valid only after they are declared. Thus, if you define a
variable at the start of a method, it is available to all of the code within that method. Conversely, if you declare a variable at the end
of a block, it is effectively useless, because no code will have access to it. For example, this fragment is invalid because count
cannot be used prior to its declaration:
// This fragment is wrong! count = 100; // oops! cannot use count before it is declared! int count; Here is another important
point to remember: variables are created when their scope is entered, and destroyed when their scope is left. This means that a
variable will not hold its value once it has gone out of scope. Therefore, variables declared within a method will not hold their values
between calls to that method.. Also, a variable declared within a block will lose its value when the block is left. Thus, the lifetime of
a variable is confined to its scope.

Type Conversion and Casting


Type Casting in Java
In Java, type casting is a method or process that converts a data type into another data type in both ways manually and
automatically. The automatic conversion is done by the compiler and manual conversion performed by the programmer. In this
section, we will discuss type casting and its types with proper examples.

Type casting
Converting a value from one data type to another data type is known as type casting.

Types of Type Casting


There are two types of type casting:
->Widening Type Casting
->Narrowing Type Casting
Widening Type Casting
Converting a lower data type into a higher one is called widening type casting. It is also known as implicit conversion or
casting down. It is done automatically. It is safe because there is no chance to lose data. It takes place when:
Both data types must be compatible with each other.
The target type must be larger than the source type.
byte -> short -> char -> int -> long -> float -> double
For example, the conversion between numeric data type to char or Boolean is not done automatically. Also, the char and Boolean
data types are not compatible with each other. Let's see an example.

WideningTypeCastingExample.java
public class WideningTypeCastingExample
{
public static void main(String[] args)
{
int x = 7;
//automatically converts the integer type into long type
long y = x;
//automatically converts the long type into float type
float z = y;
System.out.println("Before conversion, int value "+x);
System.out.println("After conversion, long value "+y);
System.out.println("After conversion, float value "+z);
}
}

Output
Before conversion, the value is: 7
After conversion, the long value is: 7
After conversion, the float value is: 7.0

In the above example, we have taken a variable x and converted it into a long type. After that, the long type is converted into the
float type.

Narrowing Type Casting


Converting a higher data type into a lower one is called narrowing type casting. It is also known as explicit conversion or
casting up. It is done manually by the programmer. If we do not perform casting then the compiler reports a compile-time error.

double -> float -> long -> int -> char -> short -> byte
Let's see an example of narrowing type casting.
In the following example, we have performed the narrowing type casting two times. First, we have converted the double type into
long data type after that long data type is converted into int type.

NarrowingTypeCastingExample.java

public class NarrowingTypeCastingExample


{
public static void main(String args[])
{
double d = 166.66;
//converting double data type into long data type
long l = (long)d;
//converting long data type into int data type
int i = (int)l;
System.out.println("Before conversion: "+d);
//fractional part lost
System.out.println("After conversion into long type: "+l);
//fractional part lost
System.out.println("After conversion into int type: "+i);
}
}

Output
Before conversion: 166.66
After conversion into long type: 166
After conversion into int type: 166

Accepting Input from the Keyboard, Reading Input with Java.util.Scanner Class

Accepting keyboard input in Java is done using a Scanner object.

Consider the following statement

Scanner console = new Scanner(System.in)

This statement declares a reference variable named console. The Scanner object is associated with the standard input
device (System.in).
To get input from the keyboard, you can call methods of the Scanner class. For example in following statement nextInt()
method of Scanner takes an integer and returns to variable x :

int x = console.nextInt();
Example :

import java.util.Scanner; // Needed for Scanner class

/**
* This program demonstrates keyboard input.
*/
public class RectangleArea
{
public static void main(String[] args)
{
int length; // To hold the rectangle's length.
int width; // To hold the rectangle's width.
int area; // To hold rectangle's area

// Create a Scanner object to read input.


Scanner console = new Scanner(System.in);

// Get length from the user.


System.out.print("Enter length ");
length = console.nextInt();

// Get width from the user.


System.out.print("Enter width ");
width = console.nextInt();

// Calculate area.
area = length * width;

// Display area.
System.out.println("The area of rectangle is " + area);
}
}

Output :

Enter length 5
Enter width 8
The area of rectangle is 40

Some other useful methods of Scanner class

Method Returns

int nextInt() Returns the next token as an int.

float nextFloat() Returns the next token as a float.

double nextDouble() Returns the next token as a long.

String next() Finds and returns the next complete token as a string ended by a blank.

String nextLine() Returns the rest of the current line, excluding any line separator at the end.

Displaying Output with System.out.printf()

printf() uses format specifiers for formatting. There are certain data types are mentioned below:

● For Number Formatting


● Formatting Decimal Numbers
● For Boolean Formatting
● For String Formatting
● For Char Formatting
● For Date and Time Formatting
i). For Number Formatting

The number itself includes Integer, Long, etc. The formatting Specifier used is %d.
Below is the implementation of the above method:

// Java Program to demonstrate


// Use of printf to
// Formatting Integer
import java.io.*;

// Driver Class
class College {
// main function
public static void main (String[] args) {
int a=10000;

//System.out.printf("%.d%n",a);
System.out.printf("%,d%n",a);
}
}
Output
10,000
ii). For Decimal Number Formatting
Decimal Number Formatting can be done using print() and format specifier %f .
Below is the implementation of the above method:
// Java Programs to demonstrate
// Use of Printf() for decimal
// Number Formatting
import java.io.*;

// Driver Class
class College {
// main function
public static void main(String[] args)
{
// declaring double
double a = 3.14159265359;

// Printing Double Value with


// different Formatting
System.out.printf("%f\n", a);
System.out.printf("%5.3f\n", a);
System.out.printf("%5.2f\n", a);
}
}

Output
3.141593
3.142
3.14

iii). For Boolean Formatting


Boolean Formatting can be done using printf and ( ‘%b’ or ‘%B’ ) depending upon the result needed.
Below is the implementation of the above method:

// Java Programs to demonstrate


// Use of Printf() for decimal
// Boolean Formatting
import java.io.*;

// Driver Function
class College {
// main function
public static void main(String[] args)
{
int a = 10;
Boolean b = true, c = false;
Integer d = null;

// Formatting Done using printf


System.out.printf("%b\n", a);
System.out.printf("%B\n", b);
System.out.printf("%b\n", c);
System.out.printf("%B\n", d);
}
}
Output
true
TRUE
false
FALSE

iv). For Char Formatting


Char Formatting is easy to understand as it needs printf() and Character format specifier used are ‘%c’ and ‘%C’.
Below is the implementation of the above method:

// Java Program to Formatt


//
import java.io.*;

// Driver Class
class College {
// main function
public static void main(String[] args)
{
char c = 'g';

// Formatting Done
System.out.printf("%c\n", c);

// Converting into Uppercase


System.out.printf("%C\n", c);
}
}
Output
g
G

v). For String Formatting


String Formatting requires the knowledge of Strings and format specifier used ‘%s’ and ‘%S’.
Below is the implementation of the above method:

// Java Program to implement


// Printf() for String Formatting
import java.io.*;

// Driver Class
class College {
// main function
public static void main(String[] args)
{
String str = "College";

// Formatting from lowercase to


// Uppercase
System.out.printf("%s \n", str);
System.out.printf("%S \n", str);

str = "College";
// Vice-versa not possible
System.out.printf("%S \n", str);
System.out.printf("%s \n", str);
}
}
Output
College
College
College
College

vi). For Date and Time Formatting


Formatting of Date and Time is not as easy as the data-type used above. It uses more than simple format specifier
knowledge can be observed in the example mentioned below.
Below is the implementation of the above method:

// Java Program to demonstrate use of


// printf() for formatting Date-time
import java.io.*;
import java.util.*;

// Driver Class
class College {
// main function
public static void main(String[] args)
{
Date time = new Date();

System.out.printf("Current Time: %tT\n", time);

// Another Method with all of them Hour


// minutes and seconds seperated
System.out.printf("Hours: %tH Minutes: %tM Seconds: %tS\n",
time,time, time);

// Another Method to print the time


// Followed by am/pm , time in milliseconds
// nanoseconds and time-zone offset
System.out.printf("%1$tH:%1$tM:%1$tS %1$tp %1$tL %1$tN %1$tz %n",
time);
}
}
Output
Current Time: 11:32:36
Hours: 11 Minutes: 32 Seconds: 36
11:32:36 am 198 198000000 +0000

Displaying Formatted Output with String.format()

In Java, String format() method returns a formatted string using the given locale, specified format string, and arguments.
We can concatenate the strings using this method and at the same time, we can format the output concatenated string.

Syntax of String format()


There are two types of string format() methods mentioned below:

public static String format(Locale loc, String form, Object... args)


public static String format(String form, Object... args)
Parameters
locale: the locale value to be applied on the format() method
format: The format of the output string.
args: args specifying the number of arguments for the format string. It may be zero or more.
Return Value
Formatted string.
Exception Thrown
NullPointerException: If the format is null.
IllegalFormatException: If the format specified is illegal or there are insufficient arguments.
Example of Java String format()

// Java program to demonstrate


// working of format() method

// Main class
class College {
// Main driver method
public static void main(String args[])
{
// Custom input string to be formatted
String str = "College";

// Concatenation of two strings


String s
= String.format("My Company name is %s", str);

// Output is given upto 8 decimal places


String str2
= String.format("My answer is %.8f", 47.65734);

// Here answer is supposed to be %15.8f" and


// "47.65734000" there are 15 spaces
String str3 = String.format("My answer is %15.8f",
47.65734);

// Print and display strings


System.out.println(s);
System.out.println(str2);
System.out.println(str3);
}
}
Output
My Company name is College
My answer is 47.65734000
My answer is 47.65734000

Control Statements

A programming language uses control statements to control the flow of execution of a program based on certain conditions. These
are used to cause the flow of execution to advance and branch based on changes to the state of a program.

Java’s Selection statements:

if
if-else
nested-if
if-else-if
switch-case
jump – break, continue, return
1. if: if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of
statements will be executed or not i.e if a certain condition is true then a block of statements is executed otherwise not.

Syntax:

if(condition)
{
// Statements to execute if
// condition is true
}
Here, the condition after evaluation will be either true or false. if statement
accepts boolean values – if the value is true then it will execute the block
of statements under it.
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by
default if statement will consider the immediate one statement to be inside
its block. For example,

if(condition) //Assume condition is true


statement1; //part of if block
statement2; // separate from if block

// Here if the condition is true


// if block will consider statement1 as its part and executes in only true
condition
// statement2 will be separate from the if block so it will always executes whether the condition is true or false.

// Java program to illustrate If statement without curly block


import java.util.*;

class IfDemo {
public static void main(String args[])
{
int i = 10;

if (i < 15)
System.out.println("Inside If block"); // part of if block(immediate one statement after if condition)
System.out.println("10 is less than 15"); //always executes as it is outside of if block
// This statement will be executed
// as if considers one statement by default again below statement is outside of if block
System.out.println("I am Not in if");
}
}
Output
Inside If block
10 is less than 15
I am Not in if
Time Complexity: O(1)
Auxiliary Space : O(1)

2. if-else: The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it
won’t. But what if we want to do something else if the condition is false? Here comes the else statement. We can use the else
statement with the if statement to execute a block of code when the condition
is false.

Syntax:

if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}

// Java program to illustrate if-else statement


import java.util.*;

class IfElseDemo {
public static void main(String args[])
{
int i = 10;

if (i < 15)
System.out.println("i is smaller than 15");
else
System.out.println("i is greater than 15");
}
}
Output
i is smaller than 15
Time Complexity: O(1)
Auxiliary Space : O(1)

3. nested-if: A nested if is an if statement that is the target of another if or else. Nested if statements mean an if statement inside
an if statement. Yes, java allows us to nest if
statements within if statements. i.e, we can
place an if statement inside another if
statement.

Syntax:

if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}

// Java program to illustrate nested-if


statement
import java.util.*;

class NestedIfDemo {
public static void main(String args[])
{
int i = 10;

if (i == 10 || i<15) {
// First if statement
if (i < 15)
System.out.println("i is smaller than 15");

// Nested - if statement
// Will only be executed if statement above
// it is true
if (i < 12)
System.out.println(
"i is smaller than 12 too");
} else{
System.out.println("i is greater than 15");
}
}
}
Output
i is smaller than 15
i is smaller than 12 too
Time Complexity: O(1)
Auxiliary Space: O(1)

4. if-else-if ladder: Here, a user can decide among multiple options.The if statements are executed from the top down. As soon as
one of the conditions controlling the if is true, the statement associated with that ‘if’ is executed, and the rest of the ladder is
bypassed. If none of the conditions is true, then the final else statement will
be executed. There can be as many as ‘else if’ blocks associated with one ‘if’
block but only one ‘else’ block is allowed with one ‘if’ block.

if (condition)
statement;
else if (condition)
statement;
.
.
else
Statement;

// Java program to illustrate if-else-if ladder


import java.util.*;

class ifelseifDemo {
public static void main(String args[])
{
int i = 20;

if (i == 10)
System.out.println("i is 10");
else if (i == 15)
System.out.println("i is 15");
else if (i == 20)
System.out.println("i is 20");
else
System.out.println("i is not present");
}
}
Output
i is 20
Time Complexity: O(1)
Auxiliary Space: O(1)

5. switch-case: The switch statement is a multiway branch statement. It provides an easy way to dispatch execution to different
parts of code based on the value of the expression.

Syntax:

switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
/*package whatever //do not write package name here */

import java.io.*;

class College {
public static void main (String[] args) {
int num=20;
switch(num){
case 5 : System.out.println("It is 5");
break;
case 10 : System.out.println("It is 10");
break;
case 15 : System.out.println("It is 15");
break;
case 20 : System.out.println("It is 20");
break;
default: System.out.println("Not present");

}
}
}
Output
It is 20
Time Complexity: O(1)
Space Complexity: O(1)

The expression can be of type byte, short, int char, or an enumeration. Beginning with JDK7, the expression can also be of type
String.
Duplicate case values are not allowed.
The default statement is optional.
The break statement is used inside the switch to terminate a statement sequence.
The break statements are necessary without the break keyword, statements in switch blocks fall through.
If the break keyword is omitted, execution will continue to the next case.

6. jump: Java supports three jump statements: break, continue and return. These three statements transfer control to another part
of the program.

Break: In Java, a break is majorly used for:


Terminate a sequence in a switch statement (discussed above).
To exit a loop.
Used as a “civilized” form of goto.
Continue: Sometimes it is useful to force an early iteration of a
loop. That is, you might want to continue running the loop but stop
processing the remainder of the code in its body for this particular
iteration. This is, in effect, a goto just past the body of the loop, to
the loop’s end. The continue statement performs such an action.

// Java program to illustrate using


// continue in an if statement
import java.util.*;

class ContinueDemo {
public static void main(String args[])
{
for (int i = 0; i < 10; i++) {
// If the number is even
// skip and continue
if (i % 2 == 0)
continue;

// If number is odd, print it


System.out.print(i + " ");
}
}
}
Output
13579
Time Complexity: O(1)
Auxiliary Space: O(1)

Return: The return statement is used to explicitly return from a method. That is, it causes program control to transfer back to the
caller of the method.

// Java program to illustrate using return


import java.util.*;

public class Return {


public static void main(String args[])
{
boolean t = true;
System.out.println("Before the return.");

if (t)
return;

// Compiler will bypass every statement


// after return
System.out.println("This won't execute.");
}
}
Output
Before the return.
Time Complexity: O(1)
Auxiliary Space: O(1)
—----------------------------------------------------------------------------------------------------------------------------------------------------------

UNIT - II
Arrays

In Java, all arrays are dynamically allocated. (discussed below)


Arrays may be stored in contiguous memory [consecutive memory locations].
Since arrays are objects in Java, we can find their length using the object property length. This is different from C/C++, where we
find length using size of.
A Java array variable can also be declared like other variables with [] after the data type.
The variables in the array are ordered, and each has an index beginning with 0.
Java arrays can also be used as a static field, a local variable, or a method parameter.
An array can contain primitives (int, char, etc.) and object (or non-primitive) references of a class, depending on the definition of the
array. In the case of primitive data types, the actual values might be stored in contiguous memory locations (JVM does not
guarantee this behavior). In the case of class objects, the actual objects are stored in a heap segment. To learn more about Java
Array, go through the Java programming course here.

Creating, Initializing, and Accessing an Arrays


One-Dimensional Arrays
The general form of a one-dimensional array declaration is

-- type var-name[];
-- type[] var-name;
An array declaration has two components: the type and the name. type declares the element type of the array. The element type
determines the data type of each element that comprises the array. Like an array of integers, we can also create an array of other
primitive data types like char, float, double, etc., or user-defined data types (objects of a class). Thus, the element type for the array
determines what type of data the array will hold.

Example:
// both are valid declarations
int intArray[];
int[] intArray;
// similar to int we can declare
// byte , short, boolean, long, float
// double, char
// an array of references to objects of
// the class MyClass (a class created by user)
MyClass myClassArray[];
// array of Object
Object[] ao,
// array of Collection
// of unknown type
Collection[] ca;

Instantiating an Array in Java


When an array is declared, only a reference of an array is created. To create or give memory to the array, you create an array like
this: The general form of new as it applies to one-dimensional arrays appears as follows:

var-name = new type [size];


Here, type specifies the type of data being allocated, size determines the number of elements in the array, and var-name is the
name of the array variable that is linked to the array. To use new to allocate an array, you must specify the type and number of
elements to allocate.

Array Literal in Java


In a situation where the size of the array and variables of the array are already known, array literals can be used.

// Declaring array literal


int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
The length of this array determines the length of the created array.
There is no need to write the new int[] part in the latest versions of Java.

// Java program to illustrate creating an array// of integers, puts some values in the array,// and prints each value to standard
output.
class College {
public static void main(String[] args)
{
// declares an Array of integers.
int[] arr;

// allocating memory for 5 integers.


arr = new int[5];

// initialize the first elements of the array


arr[0] = 10;

// initialize the second elements of the array


arr[1] = 20;

// so on...
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;

// accessing the elements of the specified array


for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i
+ " : " + arr[i]);
}
}
Output
Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50
Arrays of Objects in Java
An array of objects is created like an array of primitive-type data items in the following way.

Student[] arr = new Student[5]; //Student is a user-defined


class
Syntax:

-- data type[] arrName;


-- datatype arrName[];
-- datatype [] arrName;

import java.io.*;

class College {
public static void main (String[] args) {

int [] arr=new int [4];


// 4 is the size of arr

System.out.println("Array Size:"+arr.length);
}
}
Output
Array Size:4
ArrayIndexOutOfBoundsException

JVM throws ArrayIndexOutOfBoundsException to indicate that the array has been accessed with an illegal index. The index is
either negative or greater than or equal to the size of an array.

// Code for showing error "ArrayIndexOutOfBoundsException"


public class College {
public static void main(String[] args)
{
int[] arr = new int[4];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;

System.out.println(
"Trying to access element outside the size of array");
System.out.println(arr[5]);
}
}
Output

Trying to access element outside the size of array


Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 4
at College.main(College.java:13)

Multidimensional Arrays in Java


Multidimensional arrays are arrays of arrays with each element of
the array holding the reference of other arrays. These are also
known as Jagged Arrays. A multidimensional array is created by
appending one set of square brackets ([]) per dimension.

Syntax of Java Multidimensional Array


There are 2 methods to declare Java Multidimensional Arrays as
mentioned below:

-- datatype [][] arrayrefvariable;


-- datatype arrayrefvariable[][];
// Java Program to demonstrate
// Java Multidimensional Array
import java.io.*;

// Driver class
class College {
public static void main(String[] args)
{
// Syntax
int[][] arr = new int[3][3];
// 3 row and 3 column

// Number of Rows
System.out.println("Number of Rows:"+
arr.length);

// Number of Columns
System.out.println("Number of Columns:"+
arr[0].length);
}
}
Output
Number of Rows:3
Number of Columns:3
Multidimensional Array Declaration
int[][] intArray = new int[10][20]; //a 2D array or matrix
int[][][] intArray = new int[10][20][10]; //a 3D array

Example of Muilti Dimensional Array in Java

// Java Program to Multidimensional Array

// Driver Class
public class multiDimensional {
// main function
public static void main(String args[])
{
// declaring and initializing 2D array
int arr[][]
= { { 2, 7, 9 }, { 3, 6, 1 }, { 7, 4, 2 } };

// printing 2D array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
System.out.print(arr[i][j] + " ");

System.out.println();
}
}
}
Output
279
361
742
Passing Arrays to Methods
Like variables, we can also pass arrays to methods. For example, the below program passes the array to method sum to calculate
the sum of the array’s values.

// Java program to demonstrate


// passing of array to method

public class Test {


// Driver method
public static void main(String args[])
{
int arr[] = { 3, 1, 2, 5, 4 };

// passing array to method m1


sum(arr);
}

public static void sum(int[] arr)


{
// getting sum of array values
int sum = 0;

for (int i = 0; i < arr.length; i++)


sum += arr[i];

System.out.println("sum of array values : " + sum);


}
}
Output
sum of array values : 15
Returning Arrays from Methods
As usual, a method can also return an array. For example, the below program returns an array from method m1.

// Java program to demonstrate


// return of array from method

class Test {
// Driver method
public static void main(String args[])
{
int arr[] = m1();

for (int i = 0; i < arr.length; i++)


System.out.print(arr[i] + " ");
}

public static int[] m1()


{
// returning array
return new int[] { 1, 2, 3 };
}
}
Output
123
Command Line Arguments
The java command-line argument is an argument i.e. passed at the time of running the java program.
The arguments passed from the console can be received in the java program and it can be used as an input.
So, it provides a convenient way to check the behavior of the program for the different values. You can pass N (1,2,3 and
so on) numbers of arguments from the command prompt.
Simple example of command-line argument in java
In this example, we are receiving only one argument and printing it. To run this java program, you must pass at least one
argument from the command prompt.

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

Example of command-line argument that prints all the values


In this example, we are printing all the arguments passed from the command-line. For this purpose, we have traversed the array
using for loop.
class A{
public static void main(String args[]){
for(int i=0;i<args.length;i++)
System.out.println(args[i]);

}
}
compile by > javac A.java
run by > java A sonoo jaiswal 1 3 abc
Output: sonoo
jaiswal
1
3
abc
String Class Methods

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

1. String literal
String s = “College”;
2. Using new keyword
String s = new String (“College”);
String Constructors in Java
1. String(byte[] byte_arr)
Construct a new String by decoding the byte array. It uses the platform’s default character set for decoding.
Example:
byte[] b_arr = {71, 101, 101, 107, 115};
String s_byte =new String(b_arr); //Geeks
2. String(byte[] byte_arr, Charset char_set)
Construct a new String by decoding the byte array. It uses the char_set for decoding.

Example:
byte[] b_arr = {71, 101, 101, 107, 115};
Charset cs = Charset.defaultCharset();
String s_byte_char = new String(b_arr, cs); //Geeks
3. String(byte[] byte_arr, String char_set_name)
Construct a new String by decoding the byte array. It uses the char_set_name for decoding. It looks similar to the above
constructs and they appear before similar functions but it takes the String(which contains char_set_name) as parameter while the
above constructor takes CharSet.
Example:
byte[] b_arr = {71, 101, 101, 107, 115};
String s = new String(b_arr, "US-ASCII"); //Geeks
4. String(byte[] byte_arr, int start_index, int length)
Construct a new string from the bytes array depending on the start_index(Starting location) and length(number of
characters from starting location).
Example:
byte[] b_arr = {71, 101, 101, 107, 115};
String s = new String(b_arr, 1, 3); // eek
5. String(byte[] byte_arr, int start_index, int length, Charset char_set)
Construct a new string from the bytes array depending on the start_index(Starting location) and length(number of
characters from starting location).Uses char_set for decoding.
Example:
byte[] b_arr = {71, 101, 101, 107, 115};
Charset cs = Charset.defaultCharset();
String s = new String(b_arr, 1, 3, cs); // eek
6. String(byte[] byte_arr, int start_index, int length, String char_set_name)
Construct a new string from the bytes array depending on the start_index(Starting location) and length(number of
characters from starting location).Uses char_set_name for decoding.
Example:
byte[] b_arr = {71, 101, 101, 107, 115};
String s = new String(b_arr, 1, 4, "US-ASCII"); // eeks
7. String(char[] char_arr)
Allocates a new String from the given Character array
Example:
char char_arr[] = {'G', 'e', 'e', 'k', 's'};
String s = new String(char_arr); //Geeks
8. String(char[] char_array, int start_index, int count)
Allocates a String from a given character array but choose count characters from the start_index.
Example:
char char_arr[] = {'G', 'e', 'e', 'k', 's'};
String s = new String(char_arr , 1, 3); //eek
9. String(int[] uni_code_points, int offset, int count)
Allocates a String from a uni_code_array but choose count characters from the start_index.
Example:
int[] uni_code = {71, 101, 101, 107, 115};
String s = new String(uni_code, 1, 3); //eek
10. String(StringBuffer s_buffer)
Allocates a new string from the string in s_buffer
Example:
StringBuffer s_buffer = new StringBuffer("Geeks");
String s = new String(s_buffer); //Geeks
11. String(StringBuilder s_builder)
Allocates a new string from the string in s_builder
Example:
StringBuilder s_builder = new StringBuilder("Geeks");
String s = new String(s_builder); //Geeks

String Methods in Java


1. int length()
Returns the number of characters in the String.
"College".length(); // returns 13
2. Char charAt(int i)
Returns the character at ith index.
"College".charAt(3); // returns ‘k’
3. String substring (int i)
Return the substring from the ith index character to end.
"College".substring(3); // returns “ksforGeeks”
4. String substring (int i, int j)
Returns the substring from i to j-1 index.
"College".substring(2, 5); // returns “eks”
5. String concat( String str)
Concatenates specified string to the end of this string.
String s1 = ”Geeks”;
String s2 = ”forGeeks”;
String output = s1.concat(s2); // returns “College”
6. int indexOf (String s)
Returns the index within the string of the first occurrence of the specified string.
If String s is not present in input string then -1 is returned as the default value.
1. String s = ”Learn Share Learn”;
int output = s.indexOf(“Share”); // returns 6
2. String s = "Learn Share Learn"
int output = s.indexOf(“Play”); // return -1
7. int indexOf (String s, int i)
Returns the index within the string of the first occurrence of the specified string, starting at the specified index.
String s = ”Learn Share Learn”;
int output = s.indexOf("ea",3);// returns 13
8. Int lastIndexOf( String s)
Returns the index within the string of the last occurrence of the specified string.
If String s is not present in input string then -1 is returned as the default value.
1. String s = ”Learn Share Learn”;
int output = s.lastIndexOf("a"); // returns 14
2. String s = "Learn Share Learn"
int output = s.indexOf(“Play”); // return -1
9. boolean equals( Object otherObj)
Compares this string to the specified object.
Boolean out = “Geeks”.equals(“Geeks”); // returns true
Boolean out = “Geeks”.equals(“geeks”); // returns false
10. boolean equalsIgnoreCase (String anotherString)
Compares string to another string, ignoring case considerations.
Boolean out= “Geeks”.equalsIgnoreCase(“Geeks”); // returns true
Boolean out = “Geeks”.equalsIgnoreCase(“geeks”); // returns true
11. int compareTo( String anotherString)
Compares two string lexicographically.
int out = s1.compareTo(s2);
// where s1 and s2 are
// strings to be compared
This returns difference s1-s2. If :
out < 0 // s1 comes before s2
out = 0 // s1 and s2 are equal.
out > 0 // s1 comes after s2.
12. int compareToIgnoreCase( String anotherString)
Compares two string lexicographically, ignoring case considerations.
int out = s1.compareToIgnoreCase(s2);
// where s1 and s2 are
// strings to be compared
This returns difference s1-s2. If :
out < 0 // s1 comes before s2
out = 0 // s1 and s2 are equal.
out > 0 // s1 comes after s2.
Note: In this case, it will not consider case of a letter (it will ignore whether it is uppercase or lowercase).
13. String toLowerCase()
Converts all the characters in the String to lower case.
String word1 = “HeLLo”;
String word3 = word1.toLowerCase(); // returns “hello"
14. String toUpperCase()
Converts all the characters in the String to upper case.
String word1 = “HeLLo”;
String word2 = word1.toUpperCase(); // returns “HELLO”
15. String trim()
Returns the copy of the String, by removing whitespaces at both ends. It does not affect whitespaces in the middle.
String word1 = “ Learn Share Learn “;
String word2 = word1.trim(); // returns “Learn Share Learn”
16. String replace (char oldChar, char newChar)
Returns new string by replacing all occurrences of oldChar with newChar.
String s1 = “feeksforfeeks“;
String s2 = “feeksforfeeks”.replace(‘f’ ,’g’); // return “College”
Note: s1 is still feeksforfeeks and s2 is geeksgorgeeks
17. boolean contains(string) :
Returns true if string contains contains the given string
String s1="College";
String s2="geeks";
s1.contains(s2) // return true
18. Char[] toCharArray():
Converts this String to a new character array.
String s1="College";
char []ch=s1.toCharArray(); // returns [ 'g', 'e' , 'e' , 'k' , 's' , 'f', 'o', 'r' , 'g' , 'e' , 'e' , 'k' ,'s' ]
19. boolean starsWith(string):
Return true if string starts with this prefix.
String s1="College";
String s2="geeks";
s1.startsWith(s2) // return true

import java.io.*;
import java.util.*;
class Test
{
// main function
public static void main (String[] args)
{
String s= "College";
System.out.println("String length = " + s.length());
System.out.println("Character at 3rd position = " + s.charAt(3));
System.out.println("Substring" + s.substring(3));
System.out.println("Substring= " + s.substring(2,5));
String s1 = "Geeks";
String s2 = "forGeeks";
System.out.println("Concatenated string= " +s1.concat(s2));
String s4 = "Learn Share Learn";
System.out.println("Index of Share " +s4.indexOf("Share"));
System.out.println("Index of a= " +s4.indexOf('a',3));
Boolean out = "Geeks".equals("geeks");
System.out.println("Checking Equality" + out);
out = "Geeks".equals("Geeks");
System.out.println("Checking Equality" + out);
out = "Geeks".equalsIgnoreCase("gEeks ");
System.out.println("Checking Equality " + out);
int out1 = s1.compareTo(s2);
System.out.println("the difference between ASCII value is="+out1);
String word1 = "GeeKyMe";
System.out.println("Changing to lower Case " +word1.toLowerCase());
String word2 = "GeekyME";
System.out.println("Changing to UPPER Case " +word2.toUpperCase());
String word4 = " Learn Share Learn ";
System.out.println("Trim the word " + word4.trim());
String str1 = "feeksforfeeks";
System.out.println("Original String " + str1);
String str2 = "feeksforfeeks".replace('f' ,'g') ;
System.out.println("Replaced f with g -> " + str2);
}
}
Output
String length = 13
Character at 3rd position = k
SubstringksforGeeks
Substring= eks
Concatenated string= College
Index of Share 6
Index of a= 8
Checking Equalityfalse
Checking Equalitytrue
Checking Equality false
the difference between ASCII value is=-31
Changing to lower Case geekyme
Changing to UPPER Case GEEKYME
Trim the word Learn Share Learn
Original String feeksforfeeks
Replaced f with g -> geeksgorgeeks

Java Classes
A class in Java is a set of objects which shares common characteristics/ behavior and common properties/ attributes. It is
a user-defined blueprint or prototype from which objects are created. For example, Student is a class while a particular student
named Ravi is an object.

Properties of Java Classes


Class is not a real-world entity. It is just a template or blueprint or prototype from which objects are created.
Class does not occupy memory.
Class is a group of variables of different data types and a group of methods.
A Class in Java can contain:
Data member
Method
Constructor
Nested Class
Interface
If you’re looking to gain a deeper understanding of Java and its object-oriented principles, exploring a comprehensive Java
Programming Online course can be a valuable step. It will help you master the core concepts of classes and objects, and how to
effectively use them in building robust Java applications.
Class Declaration in Java
access_modifier class <class_name>
{
data member;
method;
constructor;
nested class;
interface;
}

Example of Java Class

// Java Program for class example

class Student {
// data member (also instance variable)
int id;
// data member (also instance variable)
String name;

public static void main(String args[])


{
// creating an object of
// Student
Student s1 = new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Output
0
Null

Java Objects
An object in Java is a basic unit of Object-Oriented Programming and represents real-life entities. Objects are the
instances of a class that are created to use the attributes and methods of a class. A typical Java program creates many objects,
which as you know, interact by invoking methods. An object consists of :

State : It is represented by attributes of an object. It also reflects


the properties of an object.
Behavior : It is represented by the methods of an object. It also
reflects the response of an object with other objects.
Identity : It gives a unique name to an object and enables one
object to interact with other objects.
Example of an object: dog

Declaring Objects (Also called instantiating a class)


When an object of a class is created, the class is said to be instantiated . All the instances share the attributes and the behavior of
the class. But the values of those attributes, i.e. the state are unique for each object. A single class may have any number of
instances.

Example:
As we declare variables like (type name;). This notifies the
compiler that we will use the name to refer to data whose type is
type. With a primitive variable, this declaration also reserves the
proper amount of memory for the variable. So for reference
variables , the type must be strictly a concrete class name. In
general, we can’t create objects of an abstract class or an
interface.

Dog tuffy;
If we declare a reference variable(tuffy) like this, its value will be undetermined(null) until an object is actually created and assigned
to it. Simply declaring a reference variable does not create an object.
Initializing a Java object
The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new
operator also invokes the class constructor.

public class Dog {


String name;
String breed;
int age;
String color;
public Dog(String name, String breed, int age,
String color)
{
this.name = name;
this.breed = breed;
this.age = age;
this.color = color;
}

public String getName() { return name; }


public String getBreed() { return breed; }
public int getAge() { return age; }
public String getColor() { return color; }
@Override public String toString()
{
return ("Hi my name is " + this.getName()
+ ".\nMy breed,age and color are "
+ this.getBreed() + "," + this.getAge()
+ "," + this.getColor());
}
public static void main(String[] args)
{
Dog tuffy
= new Dog("tuffy", "papillon", 5, "white");
System.out.println(tuffy.toString());
}
}
Output
Hi my name is tuffy.
My breed,age and color are papillon,5,white
Create an Object:
Using new keyword
It is the most common and general way to create an object in Java.
Example:
// creating object of class Test
Test t = new Test();

Class Object

Class is the blueprint of an object. It is used to


An object is an instance of the class.
create objects.

No memory is allocated when a class is declared. Memory is allocated as soon as an object is created.

An object is a real-world entity such as a book, car,


A class is a group of similar objects.
etc.

Class is a logical entity. An object is a physical entity.

Objects can be created many times as per


A class can only be declared once.
requirement.

Objects of the class car can be BMW, Mercedes,


An example of class can be a car.
Ferrari, etc.
—--------
Passing Parameters:
There are different ways in which parameter data can be passed into and out of methods and functions. Let us assume
that a function B() is called from another function A(). In this case A is called the “caller function” and B is called the “called function
or callee function”. Also, the arguments which A sends to B are called actual arguments and the parameters of B are called formal
arguments.

Types of parameters:
Formal Parameter: A variable and its type as they appear in the prototype of the function or method.
Syntax:
function_name(datatype variable_name)
Actual Parameter: The variable or expression corresponding to a formal parameter that appears in the function or method call in
the calling environment.
Syntax:
func_name(variable name(s));

Important methods of Parameter Passing


1. Pass By Value: Changes made to formal parameter do not get transmitted back to the caller. Any modifications to the
formal parameter variable inside the called function or method affect only the separate storage location and will not be reflected in
the actual parameter in the calling environment. This method is also called as call by value.

// Java program to illustrate


// Call by Value

// Callee
class CallByValue {

// Function to change the value


// of the parameters
public static void example(int x, int y)
{
x++;
y++;
}
}

// Caller
public class Main {
public static void main(String[] args)
{

int a = 10;
int b = 20;

// Instance of class is created


CallByValue object = new CallByValue();

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

// Passing variables in the class function


object.example(a, b);

// Displaying values after


// calling the function
System.out.println("Value of a: "
+ a + " & b: " + b);
}
}

Output
Value of a: 10 & b: 20
Value of a: 10 & b: 20

2. Call by reference(aliasing):
Changes made to formal parameter do get transmitted back to the caller through parameter passing. Any changes to the
formal parameter are reflected in the actual parameter in the calling environment as formal parameter receives a reference (or
pointer) to the actual data. This method is also called as call by reference. This method is efficient in both time and space.
// Java program to illustrate
// Call by Reference

// Callee
class CallByReference {

int a, b;

// Function to assign the value


// to the class variables
CallByReference(int x, int y)
{
a = x;
b = y;
}

// Changing the values of class variables


void ChangeValue(CallByReference obj)
{
obj.a += 10;
obj.b += 20;
}
}

// Caller
public class Main {

public static void main(String[] args)


{

// Instance of class is created


// and value is assigned using constructor
CallByReference object
= new CallByReference(10, 20);

System.out.println("Value of a: " + object.a


+ " & b: " + object.b);

// Changing values in class function


object.ChangeValue(object);

// Displaying values
// after calling the function
System.out.println("Value of a: " + object.a
+ " & b: " + object.b);
}
}

Output
Value of a: 10 & b: 20
Value of a: 20 & b: 40

—---------
Methods,
The method in Java or Methods of Java is a collection of statements that perform some specific tasks and return the result
to the caller. A Java method can perform some specific tasks without returning anything. Java Methods allows us to reuse the code
without retyping the code. In Java, every method must be part of some class that is different from languages like C, C++, and
Python.
A method is like a function i.e. used to expose the behavior of an object.
It is a set of codes that perform a particular task.
Syntax of Method:
<access_modifier> <return_type> <method_name>( list_of_parameters)
{
//body
}
Advantage of Method:
Code Reusability
Code Optimization
Method Declaration
In general, method declarations have 6 components:
1. Modifier: It defines the access type of the method i.e. from where it can be accessed in your application. In Java, there 4 types of
access specifiers.

public: It is accessible in all classes in your application.


protected: It is accessible within the class in which it is defined and in its subclasses.
private: It is accessible only within the class in which it is defined.
default: It is declared/defined without using any
modifier. It is accessible within the same class and
package within which its class is defined.
Note: It is Optional in syntax.

2. The return type: The data type of the value


returned by the method or void if does not return a
value. It is Mandatory in syntax.

3. Method Name: the rules for field names apply to


method names as well, but the convention is a little
different. It is Mandatory in syntax.

4. Parameter list: Comma-separated list of the input


parameters is defined, preceded by their data type,
within the enclosed parenthesis. If there are no parameters, you must use empty parentheses (). It is Optional in syntax.

5. Exception list: The exceptions you expect by the method can throw; you can specify these exception(s). It is Optional in syntax.

6. Method body: it is enclosed between braces. The code you need to be executed to perform your intended operations. It is
Optional in syntax.

Types of Methods in Java


There are two types of methods in Java:
1. Predefined Method
In Java, predefined methods are the method that is already defined in the Java class libraries is known as predefined
methods. It is also known as the standard library method or built-in method. We can directly use these methods just by calling them
in the program at any point.
2. User-defined Method
The method written by the user or programmer is known as a user-defined method. These methods are modified
according to the requirement.
—-------------
Static field and Method, this keyword:
1. Instance Method: Access the instance data using the object name. Declared inside a class.
Syntax:
// Instance Method
void method_name(){
body // instance area
}
2. Static Method: Access the static data using class name. Declared inside class with static keyword.

Syntax:

//Static Method
static void method_name(){
body // static area
}

this keyword:
In Java, ‘this’ is a reference variable that refers to the current object, or can be said “this” in Java is a keyword that refers
to the current object instance. It can be used to call current class methods and fields, to pass an instance of the current class as a
parameter, and to differentiate between the local and instance variables. Using “this” reference can improve code readability and
reduce naming conflicts.

Java this reference Example


In Java, this is a reference variable that refers to the current object on which the method or constructor is being invoked. It can be
used to access instance variables and methods of the current object.

import java.io.*;
class Test {
public static int i = 0;
Test()
{
i++;
}
public static int get()
{
return i;
}
public int m1()
{

System.out.println( "Inside the method m1 by object of College class");


this.m2();
return 1;
}
public void m2()
{

System.out.println( "In method m2 came from method m1");


}
}

class College {
public static void main(String[] args)
{
Test obj = new Test();
int i = obj.m1();
System.out.println( "Control returned after method m1 :" + i);

int no_of_objects = Test.get();


System.out.print( "No of instances created till now : ");
System.out.println(no_of_objects);
}
}

Output
Inside the method m1 by object of College class
In method m2 came from method m1
Control returned after method m1 :1
No of instances created till now : 1

—---------------
Java Constructors
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 the constructor, memory for the object is allocated in the memory. It is a special type of method that is used to
initialize the object. Every time an object is created using the new() keyword, at least one constructor is called.

// Java Program to demonstrate


// Constructor
import java.io.*;

// Driver Class
class Geeks {

// Constructor
Geeks()
{
super();
System.out.println("Constructor Called");
}

// main function
public static void main(String[] args)
{
Geeks geek = new Geeks();
}
}

Output
Constructor Called

How Java Constructors are Different From Java Methods?


Constructors must have the same name as the class within which it is defined it is not necessary for the method in Java.
Constructors do not return any type while method(s) have the return type or void if does not return any value.
Constructors are called only once at the time of Object creation while method(s) can be called any number of times.
Now let us come up with the syntax for the constructor being invoked at the time of object or instance creation.

class Geek
{
.......
// A Constructor
Geek() {
}
.......
}
// We can create an object of the above class
// using the below statement. This statement
// calls above constructor.
Geek obj = new Geek();

The first line of a constructor is a call to super() or this(), (a call to a constructor of a super-class or an overloaded
constructor), if you don’t type in the call to super in your constructor the compiler will provide you with a non-argument call to super
at the first line of your code, the super constructor must be called to create an object:

If you think your class is not a subclass it actually is, every class in Java is the subclass of a class object even if you don’t
say extends object in your class definition.

Types of Constructors in Java


Now is the correct time to discuss the types of the constructor, so primarily there are three types of constructors in Java are
mentioned below:

Default Constructor
Parameterized Constructor
Copy Constructor
1. Default Constructor in Java
A constructor that has no parameters is known as default the constructor. A default constructor is invisible. And if we write
a constructor with no arguments, the compiler does not create a default constructor. It is taken out. It is being overloaded and called
a parameterized constructor. The default constructor changed into the parameterized constructor. But Parameterized constructor
can’t change the default constructor. The default constructor can be implicit or explicit. If we don’t define explicitly, we get an implicit
default constructor. If we manually write a constructor, the implicit one is overridded.

// Java Program to demonstrate


// Default Constructor
import java.io.*;

// Driver class
class College {

// Default Constructor
College() { System.out.println("Default constructor"); }

// Driver function
public static void main(String[] args)
{
College hello = new College();
}
}
Output
Default constructor
2. Parameterized Constructor in Java
A constructor that has parameters is known as parameterized constructor. If we want to initialize fields of the class with our
own values, then use a parameterized constructor.

// Java Program for Parameterized Constructor


import java.io.*;
class Geek {
// data members of the class.
String name;
int id;
Geek(String name, int id)
{
this.name = name;
this.id = id;
}
}
class College {
public static void main(String[] args)
{
// This would invoke the parameterized constructor.
Geek geek1 = new Geek("Avinash", 68);
System.out.println("GeekName :" + geek1.name
+ " and GeekId :" + geek1.id);
}
}

Output
GeekName :Avinash and GeekId :68

3. Copy Constructor in Java


Unlike other constructors copy constructor is passed with another object which copies the data available from the passed
object to the newly created object.

// Java Program for Copy Constructor


import java.io.*;

class Geek {
// data members of the class.
String name;
int id;

// Parameterized Constructor
Geek(String name, int id)
{
this.name = name;
this.id = id;
}

// Copy Constructor
Geek(Geek obj2)
{
this.name = obj2.name;
this.id = obj2.id;
}
}
class College {
public static void main(String[] args)
{
// This would invoke the parameterized constructor.
System.out.println("First Object");
Geek geek1 = new Geek("Avinash", 68);
System.out.println("GeekName :" + geek1.name
+ " and GeekId :" + geek1.id);

System.out.println();

// This would invoke the copy constructor.


Geek geek2 = new Geek(geek1);
System.out.println(
"Copy Constructor used Second Object");
System.out.println("GeekName :" + geek2.name
+ " and GeekId :" + geek2.id);
}
}

Output
First Object
GeekName :Avinash and GeekId :68

Copy Constructor used Second Object


GeekName :Avinash and GeekId :68

—---------
Method Overloading
In Java, Method Overloading allows different methods to have the same name, but different signatures where the
signature can differ by the number of input parameters or type of input parameters, or a mixture of both.

Method overloading in Java is also known as Compile-time Polymorphism, Static Polymorphism, or Early binding. In
Method overloading compared to the parent argument, the child argument will get the highest priority.

public class Sum {


// Overloaded sum(). This sum takes two int parameters
public int sum(int x, int y) { return (x + y); }

// Overloaded sum(). This sum takes three int parameters


public int sum(int x, int y, int z)
{
return (x + y + z);
}

// Overloaded sum(). This sum takes two double


// parameters
public double sum(double x, double y)
{
return (x + y);
}

// Driver code
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}

Output
30
60
31.0

—-------
Inheritance
Java, Inheritance is an important pillar of OOP(Object-Oriented Programming). It is the mechanism in Java by which one
class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes
based on existing ones. A class that inherits from another class can reuse the methods and fields of that class. In addition, you can
add new fields and methods to your current class as well.

Why Do We Need Java Inheritance?


Code Reusability: The code written in the Superclass is common to all subclasses. Child classes can directly use the
parent class code.
Method Overriding: Method Overriding is achievable only through Inheritance. It is one of the ways by which Java
achieves Run Time Polymorphism.
Abstraction: The concept of abstract where we do not have to provide all details, is achieved through inheritance.
Abstraction only shows the functionality to the user.
Important Terminologies Used in Java Inheritance
Class: Class is a set of objects which shares common characteristics/ behavior and common properties/ attributes. Class
is not a real-world entity. It is just a template or blueprint or prototype from which objects are created.
Super Class/Parent Class: The class whose features are inherited is known as a superclass(or a base class or a parent
class).
Sub Class/Child Class: The class that inherits the other class is known as a subclass(or a derived class, extended class,
or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already
a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are
reusing the fields and methods of the existing class.
How to Use Inheritance in Java?
The extends keyword is used for inheritance in Java. Using the extends keyword indicates you are derived from an existing class.
In other words, “extends” refers to increased functionality.
Syntax :
class DerivedClass extends BaseClass
{
//methods and fields
}
Inheritance in Java Example
Example:In the below example of inheritance, class Employee is a base class, class Engineer is a derived class that
extends the Employee class and class Test is a driver class to run the program.

// Java Program to illustrate Inheritance (concise)

import java.io.*;

// Base or Super Class


class Employee {
int salary = 60000;
}

// Inherited or Sub Class


class Engineer extends Employee {
int benefits = 10000;
}

// Driver Class
class College {
public static void main(String args[])
{
Engineer E1 = new Engineer();
System.out.println("Salary : " + E1.salary
+ "\nBenefits : " + E1.benefits);
}
}

Output
Salary : 60000
Benefits : 10000

Java Inheritance Types


Below are the different types of inheritance which are supported by Java.

Single Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Multiple Inheritance
Hybrid Inheritance
1. Single Inheritance
In single inheritance, a sub-class is derived from only one super class. It inherits the properties and behavior of a
single-parent class. Sometimes, it is also known as simple inheritance. In the below figure, ‘A’ is a parent class and ‘B’ is a child
class. The class ‘B’ inherits all the properties of the class ‘A’.
// Java program to illustrate the
// concept of single inheritance
import java.io.*;
import java.lang.*;
import java.util.*;

// Parent class
class One {
public void print_geek()
{
System.out.println("Geeks");
}
}

class Two extends One {


public void print_for() { System.out.println("for"); }
}

// Driver class
public class Main {
// Main function
public static void main(String[] args)
{
Two g = new Two();
g.print_geek();
g.print_for();
g.print_geek();
}
}

Output
Geeks
for
Geeks

2. Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class, and as well as the derived class also acts as the
base class for other classes. In the below image, class A serves as a base class for the derived class B, which in turn serves as a
base class for the derived class C. In Java, a class cannot directly access the grandparent’s members.

// Importing required libraries


import java.io.*;
import java.lang.*;
import java.util.*;

// Parent class One


class One {
// Method to print "Geeks"
public void print_geek() {
System.out.println("Geeks");
}
}

// Child class Two inherits from class One


class Two extends One {
// Method to print "for"
public void print_for() {
System.out.println("for");
}
}

// Child class Three inherits from class Two


class Three extends Two {
// Method to print "Geeks"
public void print_lastgeek() {
System.out.println("Geeks");
}
}

// Driver class
public class Main {
public static void main(String[] args) {
// Creating an object of class Three
Three g = new Three();

// Calling method from class One


g.print_geek();

// Calling method from class Two


g.print_for();

// Calling method from class Three


g.print_lastgeek();
}
}

Output
Geeks
for
Geeks

3. Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass. In the below image,
class A serves as a base class for the derived classes B, C, and D.

// Java program to illustrate the


// concept of Hierarchical inheritance

class A {
public void print_A() { System.out.println("Class A"); }
}

class B extends A {
public void print_B() { System.out.println("Class B"); }
}

class C extends A {
public void print_C() { System.out.println("Class C"); }
}

class D extends A {
public void print_D() { System.out.println("Class D"); }
}

// Driver Class
public class Test {
public static void main(String[] args)
{
B obj_B = new B();
obj_B.print_A();
obj_B.print_B();

C obj_C = new C();


obj_C.print_A();
obj_C.print_C();

D obj_D = new D();


obj_D.print_A();
obj_D.print_D();
}
}

Output
Class A
Class B
Class A
Class C
Class A
Class D
4. Multiple Inheritance (Through Interfaces)
In Multiple inheritances, one class can have more than one superclass and inherit features from all parent classes. Please
note that Java does not support multiple inheritances with classes. In Java, we can achieve multiple inheritances only through
Interfaces. In the image below, Class C is derived from interfaces A and B.

// Java program to illustrate the


// concept of Multiple inheritance
import java.io.*;
import java.lang.*;
import java.util.*;

interface One {
public void print_geek();
}

interface Two {
public void print_for();
}

interface Three extends One, Two {


public void print_geek();
}
class Child implements Three {
@Override public void print_geek()
{
System.out.println("Geeks");
}

public void print_for() { System.out.println("for"); }


}

// Drived class
public class Main {
public static void main(String[] args)
{
Child c = new Child();
c.print_geek();
c.print_for();
c.print_geek();
}
}

Output
Geeks
for
Geeks

5. Hybrid Inheritance
It is a mix of two or more of the above types of inheritance. Since Java doesn’t
support multiple inheritances with classes, hybrid inheritance involving multiple inheritance
is also not possible with classes. In Java, we can achieve hybrid inheritance only through
Interfaces if we want to involve multiple inheritance to implement Hybrid inheritance.
However, it is important to note that Hybrid inheritance does not necessarily require the use
of Multiple Inheritance exclusively. It can be achieved through a combination of Multilevel
Inheritance and Hierarchical Inheritance with classes, Hierarchical and Single Inheritance
with classes. Therefore, it is indeed possible to implement Hybrid inheritance using classes
alone, without relying on multiple inheritance type.

Advantages Of Inheritance in Java:


Code Reusability: Inheritance allows for code reuse and reduces the amount of
code that needs to be written. The subclass can reuse the properties and methods
of the superclass, reducing duplication of code.
Abstraction: Inheritance allows for the creation of abstract classes that define a common interface for a group of related
classes. This promotes abstraction and encapsulation, making the code easier to maintain and extend.
Class Hierarchy: Inheritance allows for the creation of a class hierarchy, which can be used to model real-world objects
and their relationships.
Polymorphism: Inheritance allows for polymorphism, which is the ability of an object to take on multiple forms. Subclasses
can override the methods of the superclass, which allows them to change their behavior in different ways.
Disadvantages of Inheritance in Java:
Complexity: Inheritance can make the code more complex and harder to understand. This is especially true if the
inheritance hierarchy is deep or if multiple inheritances is used.
Tight Coupling: Inheritance creates a tight coupling between the superclass and subclass, making it difficult to make
changes to the superclass without affecting the subclass.

Super Keyword
The super keyword in Java is a reference variable that is used to refer to parent class when we’re working with objects.
You need to know the basics of Inheritanceand Polymorphism to understand the Java super keyword.
The Keyword “super” came into the picture with the concept of Inheritance. In this article, we gonna covers all about super
in Java including definitions, examples, Uses, Syntax, and more.

Characteristics of Super Keyword in Java


In Java, super keyword is used to refer to the parent class of a subclass. Here are some of its key characteristics:

super is used to call a superclass constructor: When a subclass is created, its constructor must call the constructor of its
parent class. This is done using the super() keyword, which calls the constructor of the parent class.
super is used to call a superclass method: A subclass can call a method defined in its parent class using the super
keyword. This is useful when the subclass wants to invoke the parent class’s implementation of the method in addition to its own.
super is used to access a superclass field: A subclass can access a field defined in its parent class using the super
keyword. This is useful when the subclass wants to reference the parent class’s version of a field.
super must be the first statement in a constructor: When calling a superclass constructor, the super() statement must be
the first statement in the constructor of the subclass.
super cannot be used in a static context: The super keyword cannot be used in a static context, such as in a static method
or a static variable initializer.
super is not required to call a superclass method: While it is possible to use the super keyword to call a method in the
parent class, it is not required. If a method is not overridden in the subclass, then calling it without the super keyword will invoke the
parent class’s implementation.

// super keyword in java example

// Base class vehicle


class Vehicle {
int maxSpeed = 120;
}

// sub class Car extending vehicle


class Car extends Vehicle {
int maxSpeed = 180;

void display()
{
// print maxSpeed of base class (vehicle)
System.out.println("Maximum Speed: "+ super.maxSpeed);
}
}

// Driver Program
class Test {
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}

Output
Maximum Speed: 120

Java Final classes


When a class is declared with the final keyword in Java, it is called a final class. A final class cannot be extended(inherited).

There are two uses of a final class:


Usage 1: One is definitely to prevent inheritance, as final classes cannot be extended. For example, all Wrapper Classes
like Integer, Float, etc. are final classes. We can not extend them.

final class A
{
// methods and fields
}
// The following class is illegal
class B extends A
{
// COMPILE-ERROR! Can't subclass A
}
Usage 2: The other use of final with classes is to create an immutable class like the predefined String class. One can not make a
class immutable without making it final.

Java Final Method


When a method is declared with final keyword, it is called a final method in Java. A final method cannot be overridden.
The Object class does this—a number of its methods are final. We must declare methods with the final keyword for which
we are required to follow the same implementation throughout all the derived classes.
Illustration: Final keyword with a method

class A
{
final void m1()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void m1()
{
// Compile-error! We can not override
System.out.println("Illegal!");
}
}

Advantages of final Keyword in Java:


The final keyword in Java provides several advantages, including:

Ensuring immutability: When a variable or reference is marked as final, its value cannot be changed once it is assigned.
This helps ensure that data is immutable and cannot be accidentally or maliciously modified.
Improving performance: The use of the final can sometimes help improve performance, as the Java Virtual Machine (JVM)
can optimize code more effectively when it knows that certain values or references cannot be changed.
Making code easier to understand: By declaring variables, methods, or classes as final, developers can make their code
easier to understand and reason about. When a value or reference is marked as final, it is clear that it will not change, which can
simplify code analysis and debugging.
Promoting code reuse: By declaring methods as final, developers can prevent subclasses from overriding them. This can
help promote code reuse and reduce duplication, as subclasses must use the parent class’s implementation of the method.
Enhancing security: The use of final can help enhance security by preventing malicious code from modifying sensitive data
or behavior.
—--------
Object class and its methods:
Object class is present in java.lang package. Every class in Java is directly or indirectly derived from the Object class. If a
class does not extend any other class then it is a direct child class of Object and if extends another class then it is indirectly
derived. Therefore the Object class methods are available to all Java classes. Hence Object class acts as a root of the inheritance
hierarchy in any Java Program.
Using Object Class Methods
The Object class provides multiple methods which are as follows:

toString() method
hashCode() method
equals(Object obj) method
finalize() method
getClass() method
clone() method
wait(), notify() notifyAll() methods
1. toString() method
The toString() provides a String representation of an object and is used to convert an object to a String. The default
toString() method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign
character `@’, and the unsigned hexadecimal representation of the hash code of the object. In other words, it is defined as:
2. hashCode() method
It returns a hash value that is used to search objects in a collection. JVM(Java Virtual Machine) uses the hashcode
method while saving objects into hashing-related data structures like HashSet, HashMap, Hashtable, etc. The main advantage of
saving objects based on hash code is that searching becomes easy.

// Java program to demonstrate working of


// hashCode() and toString()

public class Student {


static int last_roll = 100;
int roll_no;

// Constructor
Student()
{
roll_no = last_roll;
last_roll++;
}

// Overriding hashCode()
@Override public int hashCode() { return roll_no; }

// Driver code
public static void main(String args[])
{
Student s = new Student();

// Below two statements are equivalent


System.out.println(s);
System.out.println(s.toString());
}
}

Output :

Student@64
Student@64

3. equals(Object obj) method


It compares the given object to “this” object (the object on which the method is called). It gives a generic way to compare
objects for equality. It is recommended to override the equals(Object obj) method to get our own equality condition on Objects. For
more on the override of equals(Object obj) method refer – Overriding equals method in Java
4. getClass() method
It returns the class object of “this” object and is used to get the actual runtime class of the object. It can also be used to get
metadata of this class. The returned Class object is the object that is locked by static synchronized methods of the represented
class. As it is final so we don’t override it.

// Java program to demonstrate working of getClass()

public class Test {


public static void main(String[] args)
{
Object obj = new String("College");
Class c = obj.getClass();
System.out.println("Class of Object obj is : "
+ c.getName());
}
}

Output:

Class of Object obj is : java.lang.String

5. finalize() method
This method is called just before an object is garbage collected. It is called the Garbage Collector on an object when the
garbage collector determines that there are no more references to the object. We should override finalize() method to dispose of
system resources, perform clean-up activities and minimize memory leaks. For example, before destroying the Servlet objects web
container, always called finalize method to perform clean-up activities of the session.

// Java program to demonstrate working of finalize()

public class Test {


public static void main(String[] args)
{
Test t = new Test();
System.out.println(t.hashCode());

t = null;

// calling garbage collector


System.gc();

System.out.println("end");
}

@Override protected void finalize()


{
System.out.println("finalize method called");
}
}

Output:

1510467688
finalize method called
end

6. clone() method
It returns a new object that is exactly the same as this object. For clone() method refer Clone().
The remaining three methods wait(), notify() notifyAll() are related to Concurrency. Refer to Inter-thread Communication in Java for
details.
—------------
Polymorphism:
The word ‘polymorphism’ means ‘having many forms’. In simple words, we can define Java Polymorphism as the ability of
a message to be displayed in more than one form. In this article, we will learn what is polymorphism and its type.

Real-life Illustration of Polymorphism in Java: A person can have different characteristics at the same time. Like a man at
the same time is a father, a husband, and an employee. So the same person possesses different behaviors in different situations.
This is called polymorphism.

What is Polymorphism in Java?


Polymorphism is considered one of the important features of Object-Oriented Programming. Polymorphism allows us to
perform a single action in different ways. In other words, polymorphism allows you to define one interface and have multiple
implementations. The word “poly” means many and “morphs” means forms, So it means many forms.

Types of Java Polymorphism


In Java Polymorphism is mainly divided into two types:

Compile-time Polymorphism
Runtime Polymorphism
Compile-Time Polymorphism in Java
It is also known as static polymorphism. This type of polymorphism is achieved by function overloading or operator overloading.

Method Overloading
When there are multiple functions with the same name but different parameters then these functions are said to be overloaded.
Functions can be overloaded by changes in the number of arguments or/and a change in the type of arguments.

// Java Program for Method overloading


// By using Different Types of Arguments

// Class 1
// Helper class
class Helper {

// Method with 2 integer parameters


static int Multiply(int a, int b)
{
// Returns product of integer numbers
return a * b;
}

// Method 2
// With same name but with 2 double parameters
static double Multiply(double a, double b)
{
// Returns product of double numbers
return a * b;
}
}

// Class 2
// Main class
class College {
// Main driver method
public static void main(String[] args)
{
// Calling method by passing
// input as in arguments
System.out.println(Helper.Multiply(2, 4));
System.out.println(Helper.Multiply(5.5, 6.3));
}
}

Output
8
34.65

Subtypes of Compile-time Polymorphism


1. Function Overloading
It is a feature in C++ where multiple functions can have the same name but with different parameter lists. The compiler will
decide which function to call based on the number and types of arguments passed to the function.

2. Operator Overloading
It is a feature in C++ where the operators such as +, -, *, etc. can be given additional meanings when applied to
user-defined data types.

3. Template
it is a powerful feature in C++ that allows us to write generic functions and classes. A template is a blueprint for creating a
family of functions or classes.
Runtime Polymorphism in Java
It is also known as Dynamic Method Dispatch. It is a process in which a function call to the overridden method is resolved
at Runtime. This type of polymorphism is achieved by Method Overriding. Method overriding, on the other hand, occurs when a
derived class has a definition for one of the member functions of the base class. That base function is said to be overridden.

// Java Program for Method Overriding

// Class 1
// Helper class
class Parent {

// Method of parent class


void Print()
{

// Print statement
System.out.println("parent class");
}
}

// Class 2
// Helper class
class subclass1 extends Parent {

// Method
void Print() { System.out.println("subclass1"); }
}

// Class 3
// Helper class
class subclass2 extends Parent {

// Method
void Print()
{

// Print statement
System.out.println("subclass2");
}
}

// Class 4
// Main class
class College {

// Main driver method


public static void main(String[] args)
{

// Creating object of class 1


Parent a;

// Now we will be calling print methods


// inside main() method

a = new subclass1();
a.Print();

a = new subclass2();
a.Print();
}
}

Output
subclass1
subclass2

Subtype of Run-time Polymorphism


i. Virtual functions
It allows an object of a derived class to behave as if it were an object of the base class. The derived class can override the
virtual function of the base class to provide its own implementation. The function call is resolved at runtime, depending on the
actual type of the object.
Abstract Class and Its Methods:
In Java, abstract class is declared with the abstract keyword. It may have both abstract and non-abstract
methods(methods with bodies). An abstract is a Java modifier applicable for classes and methods in Java but not for Variables.

Java abstract class is a class that can not be initiated by itself, it needs to be subclassed by another class to use its properties. An
abstract class is declared using the “abstract” keyword in its class definition.

Illustration of Abstract class

abstract class Shape


{
int color;
// An abstract function
abstract void draw();
}

In Java, the following some important observations about abstract classes are as follows:

An instance of an abstract class can not be created.


Constructors are allowed.
We can have an abstract class without any abstract method.
There can be a final method in abstract class but any abstract method in class(abstract class) can not be declared as final
or in simpler terms final method can not be abstract itself as it will yield an error: “Illegal combination of modifiers: abstract and final”
We can define static methods in an abstract class
We can use the abstract keyword for declaring top-level classes (Outer class) as well as inner classes as abstract
If a class contains at least one abstract method then compulsory should declare a class as abstract
If the Child class is unable to provide implementation to all abstract methods of the Parent class then we should declare
that Child class as abstract so that the next level Child class should provide implementation to the remaining abstract method.
Abstract Class having constructor, data member, and methods
Elements abstract class can have

data member
abstract method
method body (non-abstract method)
constructor
main() method.
Below is the implementation of the above topic:

// Java Program to implement Abstract Class


// having constructor, data member, and methods
import java.io.*;

abstract class Subject {


Subject() {
System.out.println("Learning Subject");
}

abstract void syllabus();

void Learn(){
System.out.println("Preparing Right Now!");
}
}

class IT extends Subject {


void syllabus(){
System.out.println("C , Java , C++");
}
}

class College {
public static void main(String[] args) {
Subject x=new IT();

x.syllabus();
x.Learn();
}
}

Output
Learning Subject
C , Java , C++
Preparing Right Now!

Abstract Method
The abstract Method is used for creating blueprints for classes or interfaces. Here methods are defined but these methods
don’t provide the implementation. Abstract Methods can only be implemented using subclasses or classes that implement the
interfaces.

These methods are sometimes referred to as subclass responsibility because they have no implementation specified in
the super-class. Thus, a subclass must override them to provide a method definition.

Declare Abstract Method in Java


To declare an abstract method, use this general form:
abstract type method-name(parameter-list);

// Java Program to implement To display the


// method print the addition and subtraction
// by using abstraction

// Abstract Class
abstract class arithmetic_operation {
abstract void printInfo();
}
// Class add
class add extends arithmetic_operation {
// class add must override printInfo() method
// otherwise, compile-time
// exception will be thrown
void printInfo()
{
int a = 3;
int b = 4;
System.out.println(a + b);
}
}

// Class sub
class sub extends arithmetic_operation {
// class sub must override printInfo() method
// otherwise, compile-time
// exception will be thrown
void printInfo()
{
int c = 4;
int d = 5;
System.out.println(c - d);
}
}

// Driver Class
class abstraction {
// Main Function
public static void main(String args[])
{
arithmetic_operation n = new add();
n.printInfo();
arithmetic_operation y = new sub();
y.printInfo();
}
}

Output
7
-1

Unit - III
Interface Vs Abstract class:

Abstract Class Interface

Definition Cannot be instantiated; contains both Specifies a set of methods a class must
abstract (without implementation) and implement; methods are abstract by
concrete methods (with implementation) default.

Implementation Method Can have both implemented and Methods are abstract by default; Java 8,
abstract methods. can have default and static methods.

Inheritance class can inherit from only one abstract A class can implement multiple
class. interfaces.

Access Modifiers Methods and properties can have any Methods and properties are implicitly
access modifier (public, protected, public.
private).

Variables Can have member variables (final, Variables are implicitly public, static, and
non-final, static, non-static). final (constants).

Type of Methods Can have both abstract and concrete Can have only abstract methods (until
methods Java 7), and from Java 8, can have
default and static methods, and from
Java 9, can have private methods.

Constructors Can have constructors Cannot have constructors

Implementing Interface:
The interface in Java is a mechanism to achieve abstraction. Traditionally, an interface could only have abstract methods
(methods without a body) and public, static, and final variables by default. It is used to achieve abstraction and multiple inheritance
in Java. In other words, interfaces primarily define methods that other classes must implement. Java Interface also represents the
IS-A relationship.

In Java, the abstract keyword applies only to classes and methods, indicating that they cannot be instantiated directly and must be
implemented.

When we decide on a type of entity by its behavior and not via attribute we should define it as an interface.
Syntax for Java Interfaces

interface {
// declare constant fields
// declare methods that abstract
// by default.
}
To declare an interface, use the interface keyword. It is used to provide total abstraction. That means all the methods in an interface
are declared with an empty body and are public and all fields are public, static, and final by default. A class that implements an
interface must implement all the methods declared in the interface. To implement the interface, use the implements keyword.

Uses of Interfaces in Java


Uses of Interfaces in Java are mentioned below:

It is used to achieve total abstraction.


Since java does not support multiple inheritances in the case of class, by using an interface it can achieve multiple
inheritances.
Any class can extend only 1 class, but can any class implement an infinite number of interfaces.
It is also used to achieve loose coupling.
Interfaces are used to implement abstraction.
So, the question arises why use interfaces when we have abstract classes?

The reason is, abstract classes may contain non-final variables, whereas variables in the interface are final, public, and static.

// A simple interface
interface Player
{
final int id = 10;
int move();
}

Relationship Between Class and Interface


A class can extend another class similar to this an interface can extend another interface. But only a class can extend to
another interface, and vice-versa is not allowed.
Class Interface

In class, you can instantiate variables and create an object. In an interface, you must initialize variables as they are final
but you can’t create an object.

A class can contain concrete (with implementation) methods The interface cannot contain concrete (with implementation)
methods.

The access specifiers used with classes are private, protected, In Interface only one specifier is used- Public.
and public.

// Java program to demonstrate working of


// interface

import java.io.*;

// A simple interface
interface In1 {

// public, static and final


final int a = 10;

// public and abstract


void display();
}

// A class that implements the interface.


class TestClass implements In1 {

// Implementing the capabilities of


// interface.
public void display(){
System.out.println("Geek");
}

// Driver Code
public static void main(String[] args)
{
TestClass t = new TestClass();
t.display();
System.out.println(t.a);
}
}

Output
Geek
10

Multiple Inheritance in Java Using Interface


Multiple Inheritance is an OOPs concept that can’t be implemented in Java using classes. But we can use multiple
inheritances in Java using Interface. let us check this with an example.

// Java program to demonstrate How Diamond Problem


// Is Handled in case of Default Methods

// Interface 1
interface API {
// Default method
default void show()
{

// Print statement
System.out.println("Default API");
}
}

// Interface 2
// Extending the above interface
interface Interface1 extends API {
// Abstract method
void display();
}

// Interface 3
// Extending the above interface
interface Interface2 extends API {
// Abstract method
void print();
}

// Main class
// Implementation class code
class TestClass implements Interface1, Interface2 {
// Overriding the abstract method from Interface1
public void display()
{
System.out.println("Display from Interface1");
}
// Overriding the abstract method from Interface2
public void print()
{
System.out.println("Print from Interface2");
}
// Main driver method
public static void main(String args[])
{
// Creating object of this class
// in main() method
TestClass d = new TestClass();

// Now calling the methods from both the interfaces


d.show(); // Default method from API
d.display(); // Overridden method from Interface1
d.print(); // Overridden method from Interface2
}
}

Output
Default API
Display from Interface1
Print from Interface2

Extending Interfaces
One interface can inherit another by the use of keyword extends. When a class implements an interface that inherits
another interface, it must provide an implementation for all methods required by the interface inheritance chain.

interface Student
{
public void data();

}
class avi implements Student
{
public void data ()
{
String name="avinash";
int rollno=68;
System.out.println(name);
System.out.println(rollno);
}
}
public class inter_face
{
public static void main (String args [])
{
avi h= new avi();
h.data();
}
}

Output
avinash
68
—--------
Packages in java
Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces. Packages are used for:

Preventing naming conflicts. For example there can be two classes with name Employee in two packages,
college.staff.cse.Employee and college.staff.ee.Employee
Making searching/locating and usage of classes, interfaces, enumerations and annotations easier
Providing controlled access: protected and default have package level access control. A protected member is accessible by classes
in the same package and its subclasses. A default member (without any access specifier) is accessible by classes in the same
package only.
Packages can be considered as data encapsulation (or data-hiding).
All we need to do is put related classes into packages. After that, we can simply write an import class from existing packages and
use it in our program. A package is a container of a group of related classes where some of the classes are accessible are exposed
and others are kept for internal purpose. We can reuse existing classes from the packages as many time as we need it in our
program.

Package names and directory structure are closely related. For example if a package name is college.staff.cse, then there
are three directories, college, staffand cse such that cse is present in staff and staff is present inside college. Also, the directory
college is accessible through CLASSPATH variable, i.e., path of parent directory of college is present in CLASSPATH. The idea is
to make sure that classes are easy to locate.

Package naming conventions : Packages are named in reverse order of domain names, i.e., org.College.practice. For
example, in a college, the recommended convention is college.tech.cse, college.tech.ee, college.art.history, etc.

Adding a class to a Package : We can add more classes to a created package by using package name at the top of the
program and saving it in the package directory. We need a new java file to define a public class, otherwise we can add the new
class to an existing .java file and recompile it.

Subpackages: Packages that are inside another package are the subpackages. These are not imported by default, they
have to imported explicitly. Also, members of a subpackage have no access privileges, i.e., they are considered as different
package for protected and default access specifiers.

Example :
import java.util.*;
util is a subpackage created inside java package.

Accessing classes inside a package

Consider following two statements :

// import the Vector class from util package.


import java.util.vector;

// import all the classes from util package


import java.util.*;

First Statement is used to import Vector class from util package which is contained inside java.
Second statement imports all the classes from util package.

// All the classes and interfaces of this package


// will be accessible but not subpackages.
import package.*;

// Only mentioned class of this package will be accessible.


import package.classname;

// Class name is generally used when two packages have the same
// class name. For example in below code both packages have
// date class so using a fully qualified name to avoid conflict
import java.util.Date;
import my.package.Date;

// Java program to demonstrate accessing of members when


// corresponding classes are imported and not imported.
import java.util.Vector;

public class ImportDemo


{
public ImportDemo()
{
// java.util.Vector is imported, hence we are
// able to access directly in our code.
Vector newVector = new Vector();

// java.util.ArrayList is not imported, hence


// we were referring to it using the complete
// package.
java.util.ArrayList newList = new java.util.ArrayList();
}

public static void main(String arg[])


{
new ImportDemo();
}
}

Types of Packages:
Built-in Packages
These packages consist of a large number of classes which are a part of
Java API.Some of the commonly used built-in packages are:

java.lang: Contains language support classes(e.g classes which defines


primitive data types, math operations). This package is automatically
imported.
java.io: Contains classes for supporting input / output operations.
java.util: Contains utility classes which implement data structures like
Linked List, Dictionary and support ; for Date / Time operations.
java.applet: Contains classes for creating Applets.
java.awt: Contain classes for implementing the components for
graphical user interfaces (like button , ;menus etc). 6)
java.net: Contain classes for supporting networking operations.
User-defined packages: These are the packages that are defined by the user. First we create a directory myPackage (name should
be same as the name of the package). Then create the MyClass inside the directory with the first statement being the package
names.

// Name of the package must be same as the directory


// under which this file is saved
package myPackage;

public class MyClass


{
public void getNames(String s)
{
System.out.println(s);
}
}
Now we can use the MyClass class in our program.

/* import 'MyClass' class from 'names' myPackage */


import myPackage.MyClass;

public class PrintName


{
public static void main(String args[])
{
// Initializing the String variable
// with a value
String name = "College";

// Creating an instance of class MyClass in


// the package.
MyClass obj = new MyClass();

obj.getNames(name);
}
}
Note : MyClass.java must be saved inside the myPackage directory since it is a part of the package.
Setting CLASSPATH: CLASSPATH can be set by any of the following ways:
CLASSPATH can be set permanently in the environment: In Windows, choose control panel ? System ? Advanced ? Environment
Variables ? choose “System Variables” (for all the users) or “User Variables” (only the currently login user) ? choose “Edit” (if
CLASSPATH already exists) or “New” ? Enter “CLASSPATH” as the variable name ? Enter the required directories and JAR files
(separated by semicolons) as the value (e.g., “.;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar”). Take note that you need to
include the current working directory (denoted by ‘.’) in the CLASSPATH. To check the current setting of the CLASSPATH, issue the
following command:
> SET CLASSPATH
CLASSPATH can be set temporarily for that particular CMD shell session by issuing the following command:
> SET CLASSPATH=.;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar
Instead of using the CLASSPATH environment variable, you can also use the command-line option -classpath or -cp of the javac
and java commands, for example,
> java –classpath c:\javaproject\classes com.abc.project1.subproject2.MyClass3
Illustration of user-defined packages: Creating our first package: File name – ClassOne.java, ClassTwo.java

package package_name; package package_one;

public class ClassOne { public class ClassTwo {


public void methodClassOne() public void methodClassTwo()
{ {
System.out.println("Hello there its ClassOne"); System.out.println("Hello there i am ClassTwo");
} }
} }
Making use of both the created packages: File name – Testing.java

import package_name.ClassOne;
import package_one.ClassTwo;

public class Testing {


public static void main(String[] args)
{
ClassTwo a = new ClassTwo();
ClassOne b = new ClassOne();
a.methodClassTwo();
b.methodClassOne();
}
}

Output:

Hello there i am ClassTwo


Hello there its ClassOne

Important points:

Every class is part of some package.


If no package is specified, the classes in the file goes into a special unnamed package (the same unnamed package for all
files).
All classes/interfaces in a file are part of the same package. Multiple files can specify the same package name.
If package name is specified, the file must be in a subdirectory called name (i.e., the directory name must match the
package name).
We can access public classes in another (named) package using: package-name.class-name
—------------
Exceptions:
In Java, Exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at run time, that
disrupts the normal flow of the program’s instructions. Exceptions can be caught and handled by the program. When an exception
occurs within a method, it creates an object. This object is called the exception object. It contains information about the exception,
such as the name and description of the exception and the state of the program when the exception occurred.

Major reasons why an exception Occurs


Invalid user input
Device failure
Loss of network connection
Physical limitations (out-of-disk memory)
Code errors
Out of bound
Null reference
Type mismatch
Opening an unavailable file
Database errors
Arithmetic errors
Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of memory, memory leaks, stack overflow
errors, library incompatibility, infinite recursion, etc. Errors are usually beyond the control of the programmer, and we should not try
to handle errors.
Benefits of Exception:
Following are the benefits of exception handling -

1. Using exception the main application logic can be separated out from the code which may cause some unusual
conditions.

2. When calling method encounters some error then the exception can be thrown. This avoids crashing of the entire
application abruptly.

3. The working code and the error handling code can be separated out due to exception handling mechanism. Using
exception handling, various types of errors in the source code can be grouped together.

4. Due to exception handling mechanism, the errors can be propagated up the method call stack i.e. problems occurring at
the lower level can be handled by the higher up methods.
Exception Hierarchy
All exception and error types are subclasses of the class Throwable, which is the base class of the hierarchy. One branch
is headed by Exception. This class is used for exceptional conditions that user programs should catch. NullPointerException is an
example of such an exception. Another branch, Error is used by the Java run-time system(JVM) to indicate errors having to do with
the run-time environment itself(JRE). StackOverflowError is an example of such an error.
Types of exceptions:
Java defines several types of exceptions that relate to its various class libraries. Java also allows users to define their own
exceptions.

Built-in Exceptions:
Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are suitable to explain certain error
situations. Below is the list of important built-in exceptions in Java.

ArithmeticException: It is thrown when an exceptional condition has occurred in an arithmetic operation.


ArrayIndexOutOfBoundsException: It is thrown to indicate that an array has been accessed with an illegal index. The
index is either negative or greater than or equal to the size of the array.
ClassNotFoundException: This Exception is raised when we try to access a class whose definition is not found
FileNotFoundException: This Exception is raised when a file is not accessible or does not open.
IOException: It is thrown when an input-output operation failed or interrupted
InterruptedException: It is thrown when a thread is waiting, sleeping, or doing some processing, and it is interrupted.
NoSuchFieldException: It is thrown when a class does not contain the field (or variable) specified
NoSuchMethodException: It is thrown when accessing a method that is not found.
NullPointerException: This exception is raised when referring to the members of a null object. Null represents nothing
NumberFormatException: This exception is raised when a method could not convert a string into a numeric format.
RuntimeException: This represents an exception that occurs during runtime.
StringIndexOutOfBoundsException: It is thrown by String class methods to indicate that an index is either negative or
greater than the size of the string
IllegalArgumentException : This exception will throw the error or error statement when the method receives an argument
which is not accurately fit to the given relation or condition. It comes under the unchecked exception.
IllegalStateException : This exception will throw an error or error message when the method is not accessed for the
particular operation in the application. It comes under the unchecked exception.
Examples of Built-in Exception
A. Arithmetic exception
// Java program to demonstrate ArithmeticException
class ArithmeticException_Demo
{
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a/b; // cannot divide by zero
System.out.println ("Result = " + c);
}
catch(ArithmeticException e) {
System.out.println ("Can't divide a number by 0");
}
}
}

Output
Can't divide a number by 0

B. NullPointer Exception
//Java program to demonstrate NullPointerException
class NullPointer_Demo
{
public static void main(String args[])
{
try {
String a = null; //null value
System.out.println(a.charAt(0));
} catch(NullPointerException e) {
System.out.println("NullPointerException..");
}
}
}

Output
NullPointerException..

C. StringIndexOutOfBound Exception

// Java program to demonstrate StringIndexOutOfBoundsException


class StringIndexOutOfBound_Demo
{
public static void main(String args[])
{
try {
String a = "This is like chipping "; // length is 22
char c = a.charAt(24); // accessing 25th element
System.out.println(c);
}
catch(StringIndexOutOfBoundsException e) {
System.out.println("StringIndexOutOfBoundsException");
}
}
}

Output
StringIndexOutOfBoundsException

D. FileNotFound Exception

//Java program to demonstrate FileNotFoundException


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo {

public static void main(String args[]) {


try {

// Following file does not exist


File file = new File("E://file.txt");

FileReader fr = new FileReader(file);


} catch (FileNotFoundException e) {
System.out.println("File does not exist");
}
}
}

Output:

File does not exist

E. NumberFormat Exception

// Java program to demonstrate NumberFormatException


class NumberFormat_Demo
{
public static void main(String args[])
{
try {
// "akki" is not a number
int num = Integer.parseInt ("akki") ;

System.out.println(num);
} catch(NumberFormatException e) {
System.out.println("Number format exception");
}
}
}

Output
Number format exception

F. ArrayIndexOutOfBounds Exception

// Java program to demonstrate ArrayIndexOutOfBoundException


class ArrayIndexOutOfBound_Demo
{
public static void main(String args[])
{
try{
int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of
// size 5
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println ("Array Index is Out Of Bounds");
}
}
}

Output
Array Index is Out Of Bounds
G. IO Exception

// Java program to demonstrate IOException


class IOException_Demo {

public static void main(String[] args)


{

// Create a new scanner with the specified String


// Object
Scanner scan = new Scanner("Hello Geek!");

// Print the line


System.out.println("" + scan.nextLine());

// Check if there is an IO exception


System.out.println("Exception Output: "
+ scan.ioException());

scan.close();
}
}

Output:

Hello Geek!
Exception Output: null

H. NoSuchMethod Exception

// Java program to demonstrate NoSuchElementException


public class NoSuchElementException_Demo {

public static void main(String[] args)


{

Set exampleleSet = new HashSet();

Hashtable exampleTable = new Hashtable();

exampleleSet.iterator().next();
//accessing Set

exampleTable.elements().nextElement();
//accessing Hashtable

// This throws a NoSuchElementException as there are


// no elements in Set and HashTable and we are
// trying to access elements
}
}

I. IllegalArgumentException: This program, checks whether the person is eligible for voting or not. If the age is greater
than or equal to 18 then it will not throw any error. If the age is less than 18 then it will throw an error with the error statement.

Also, we can specify “throw new IllegalArgumentException()” without the error message. We can also specify
Integer.toString(variable_name) inside the IllegalArgumentException() and It will print the argument name which is not satisfied the
given condition.

/*package whatever //do not write package name here */

import java.io.*;
class College {
public static void print(int a)
{
if(a>=18){
System.out.println("Eligible for Voting");
}
else{

throw new IllegalArgumentException("Not Eligible for Voting");

}
public static void main(String[] args) {
College.print(14);
}
}

Output :

Exception in thread "main" java.lang.IllegalArgumentException: Not Eligible for Voting


at College.print(File.java:13)
at College.main(File.java:19)

J. IllegalStateException: This program, displays the addition of numbers only for Positive integers. If both the numbers
are positive then only it will call the print method to print the result otherwise it will throw the IllegalStateException with an error
statement. Here, the method is not accessible for non-positive integers.

Also, we can specify the “throw new IllegalStateException()” without the error statement.

/*package whatever //do not write package name here */

import java.io.*;

class College {
public static void print(int a,int b)
{
System.out.println("Addition of Positive Integers :"+(a+b));
}

public static void main(String[] args) {


int n1=7;
int n2=-3;
if(n1>=0 && n2>=0)
{
College.print(n1,n2);
}
else
{
throw new IllegalStateException("Either one or two numbers are not Positive Integer");
}
}
}

Output :

Exception in thread "main" java.lang.IllegalStateException: Either one or two numbers are not Positive Integer
at College.main(File.java:20)

k. ClassNotFound Exception :

// Java program to demonstrate ClassNotFoundException


public class ClassNotFoundException_Demo
{
public static void main(String[] args) {
try{
Class.forName("Class1"); // Class1 is not defined
}
catch(ClassNotFoundException e){
System.out.println(e);
System.out.println("Class Not Found...");
}
}
}

Output
java.lang.ClassNotFoundException: Class1
Class Not Found...

User-Defined Exceptions
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases, the user can also
create exceptions which are called ‘user-defined Exceptions’.

The following steps are followed for the creation of a user-defined Exception.

The user should create an exception class as a subclass of the Exception class. Since all the exceptions are subclasses of the
Exception class, the user should also make his class a subclass of it. This is done as:
class MyException extends Exception
We can write a default constructor in his own exception class.
MyException(){}
We can also create a parameterized constructor with a string as a parameter.
We can use this to store exception details. We can call the superclass(Exception) constructor from this and send the string there.
MyException(String str)
{
super(str);
}
To raise an exception of a user-defined type, we need to create an object to his exception class and throw it using the throw clause,
as:
MyException me = new MyException(“Exception details”);
throw me;
The following program illustrates how to create your own exception class MyException.
Details of account numbers, customer names, and balance amounts are taken in the form of three arrays.
In main() method, the details are displayed using a for-loop. At this time, a check is done if in any account the balance
amount is less than the minimum balance amount to be apt in the account.
If it is so, then MyException is raised and a message is displayed “Balance amount is less”.

// Java program to demonstrate user defined exception

// This program throws an exception whenever balance


// amount is below Rs 1000
class MyException extends Exception
{
//store account information
private static int accno[] = {1001, 1002, 1003, 1004};

private static String name[] =


{"Nish", "Shubh", "Sush", "Abhi", "Akash"};

private static double bal[] =


{10000.00, 12000.00, 5600.0, 999.00, 1100.55};

// default constructor
MyException() { }

// parameterized constructor
MyException(String str) { super(str); }

// write main()
public static void main(String[] args)
{
try {
// display the heading for the table
System.out.println("ACCNO" + "\t" + "CUSTOMER" +
"\t" + "BALANCE");

// display the actual account information


for (int i = 0; i < 5 ; i++)
{
System.out.println(accno[i] + "\t" + name[i] +
"\t" + bal[i]);

// display own exception if balance < 1000


if (bal[i] < 1000)
{
MyException me =
new MyException("Balance is less than 1000");
throw me;
}
}
} //end of try

catch (MyException e) {
e.printStackTrace();
}
}
}

Runtime Error

MyException: Balance is less than 1000


at MyException.main(fileProperty.java:36)

Output:

ACCNO CUSTOMER BALANCE


1001 Nish 10000.0
1002 Shubh 12000.0
1003 Sush 5600.0
1004 Abhi 999.0

In Java, there are two types of exceptions:

Checked exceptions
Unchecked exceptions
Checked Exceptions in Java
These are the exceptions that are checked at compile time. If some code within a method throws a checked exception, then the
method must either handle the exception or it must specify the exception using the throws keyword. Checked exceptions can be
fully checked or partially checked.

Fully Checked Exception: A checked exception where all its child classes are also checked (e.g., IOException,
InterruptedException).
Partially Checked Exception: A checked exception where some of its child classes are unchecked (e.g.,
Exception).
Checked exceptions represent invalid conditions in areas outside the immediate control of the program (like memory, network, file
system, etc.). Any checked exception is a subclass of Exception. Unlike unchecked exceptions, checked exceptions must be either
caught by the caller or listed as part of the method signature using the throws keyword.

// Java Program to Illustrate Checked Exceptions


// Where FileNotFoundException occurred

// Importing I/O classes


import java.io.*;

// Main class
class College {

// Main driver method


public static void main(String[] args)
{

// Reading file from path in local directory


FileReader file = new FileReader("C:\\test\\a.txt");

// Creating object as one of ways of taking input


BufferedReader fileInput = new BufferedReader(file);

// Printing first 3 lines of file "C:\test\a.txt"


for (int counter = 0; counter < 3; counter++)
System.out.println(fileInput.readLine());

// Closing file connections


// using close() method
fileInput.close();
}
}

Output

Unchecked Exceptions in Java


These are the exceptions that are not checked at compile time. In C++, all exceptions are unchecked, so it is not forced by the
compiler’s to either handle or specify the exception. It is up to the programmers to be civilized and specify or catch the exceptions.
In Java, exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under throwable is
checked.

Consider the following Java program. It compiles fine, but it throws ArithmeticException when run. The compiler allows it to compile
because ArithmeticException is an unchecked exception.

// Java Program to Illustrate Un-checked Exceptions

// Main class
class College {

// Main driver method


public static void main(String args[])
{
// Here we are dividing by 0
// which will not be caught at compile time
// as there is no mistake but caught at runtime
// because it is mathematically incorrect
int x = 0;
int y = 10;
int z = y / x;
}
}

Output

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


at Main.main(Main.java:5)
Java Result: 1

usage of try, catch, throw, throws and finally:


In Java exception is an “unwanted or unexpected event”, that occurs during the execution of the program. When an exception
occurs, the execution of the program gets terminated. To avoid these termination conditions we can use try catch block in Java.
An exception can occur due to several reasons like a Network connection problem, Bad input provided by a user, Opening a
non-existing file in your program, etc

Blocks and Keywords Used For Exception Handling


1. try in Java
The try block contains a set of statements where an exception can occur.
try
{
// statement(s) that might cause exception
}
2. catch in Java
The catch block is used to handle the uncertain condition of a try block. A try block is always followed by a catch block, which
handles the exception that occurs in the associated try block.

catch
{
// statement(s) that handle an exception
// examples, closing a connection, closing
// file, exiting the process after writing
// details to a log file.
}
3. throw in Java
The throw keyword is used to transfer control from the try block to the catch block.

Below is the implementation of the above approach:

// Java program that demonstrates the use of throw


class ThrowExcep {
static void help()
{
try {
throw new NullPointerException("error_unknown");
}
catch (NullPointerException e) {
System.out.println("Caught inside help().");
// rethrowing the exception
throw e;
}
}

public static void main(String args[])


{
try {
help();
}
catch (NullPointerException e) {
System.out.println(
"Caught in main error name given below:");
System.out.println(e);
}
}
}

Output
Caught inside help().
Caught in main error name given below:
java.lang.NullPointerException: error_unknown

4. throws in Java
The throws keyword is used for exception handling without try & catch block. It specifies the exceptions that a method can
throw to the caller and does not handle itself.

Below is the implementation of the above approach:

// Java program to demonstrate working of throws


class ThrowsExecp {

// This method throws an exception


// to be handled
// by caller or caller
// of caller and so on.
static void fun() throws IllegalAccessException
{
System.out.println("Inside fun(). ");
throw new IllegalAccessException("demo");
}

// This is a caller function


public static void main(String args[])
{
try {
fun();
}
catch (IllegalAccessException e) {
System.out.println("caught in main.");
}
}
}

Output
Inside fun().
caught in main.

5. finally in Java
It is executed after the catch block. We use it to put some common code (to be executed irrespective of whether an
exception has occurred or not ) when there are multiple catch blocks.
An example of an exception generated by the system is given below:

Exception in thread "main"


java.lang.ArithmeticException: divide
by zero at ExceptionDemo.main(ExceptionDemo.java:5)
ExceptionDemo: The class name
main:The method name
ExceptionDemo.java:The file name
java:5:line number
Below is the implementation of the above approach:

// Java program to demonstrate working of try,


// catch and finally

class Division {
public static void main(String[] args)
{
int a = 10, b = 5, c = 5, result;
try {
result = a / (b - c);
System.out.println("result" + result);
}

catch (ArithmeticException e) {
System.out.println("Exception caught:Division by zero");
}

finally {
System.out.println("I am in final block");
}
}
}

Output
Exception caught:Division by zero
I am in final block

Rethrowing Exceptions:
When an exception is cached in a catch block, you can re-throw it using the throw keyword (which is used to throw the exception
objects).

While re-throwing exceptions you can throw the same exception as it is without adjusting it as −

try {
int result = (arr[a])/(arr[b]);
System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
}
catch(ArithmeticException e) {
throw e;
}
Or, wrap it within a new exception and throw it. When you wrap a cached exception within another exception and throw it, it is
known as exception chaining or, exception wrapping, by doing this you can adjust your exception, throwing a higher level of
exception maintaining the abstraction.

try {
int result = (arr[a])/(arr[b]);
System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
}
catch(ArrayIndexOutOfBoundsException e) {
throw new IndexOutOfBoundsException();
}
Example
In the following Java example our code in demoMethod() might throw ArrayIndexOutOfBoundsException an
ArithmeticException. We are catching these two exceptions in two different catch blocks.

In the catch blocks, we are re-throwing both exceptions one by wrapping within the higher exceptions and the other one directly.

import java.util.Arrays;
import java.util.Scanner;
public class RethrowExample {
public void demoMethod() {
Scanner sc = new Scanner(System.in);
int[] arr = {10, 20, 30, 2, 0, 8};
System.out.println("Array: "+Arrays.toString(arr));
System.out.println("Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)");
int a = sc.nextInt();
int b = sc.nextInt();
try {
int result = (arr[a])/(arr[b]);
System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
}
catch(ArrayIndexOutOfBoundsException e) {
throw new IndexOutOfBoundsException();
}
catch(ArithmeticException e) {
throw e;
}
}
public static void main(String [] args) {
new RethrowExample().demoMethod();
}
}

Output1
Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
0
4
Exception in thread "main" java.lang.ArithmeticException: / by zero
at myPackage.RethrowExample.demoMethod(RethrowExample.java:16)
at myPackage.RethrowExample.main(RethrowExample.java:25)

Output2
Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
124
5
Exception in thread "main" java.lang.IndexOutOfBoundsException
at myPackage.RethrowExample.demoMethod(RethrowExample.java:17)
at myPackage.RethrowExample.main(RethrowExample.java:23)

—-----------------

Unit - IV
Multithreading

Differences between multiple processes and multiple threads:

Multiprocessing uses multiple CPUs to run many processes at a time while multithreading creates multiple threads within a
single process to get faster and more efficient task execution. Both Multiprocessing and Multithreading are used to increase the
computing power of a system in different ways. In this article, we are going to
discuss the difference between multiprocessing and multithreading in detail.

What is Multiprocessing?
Multiprocessing is a system that has more than one or two processors. In
Multiprocessing, CPUs are added to increase the computing speed of the
system. Because of Multiprocessing, There are many processes are executed
simultaneously. Explore more about similar topics. Multiprocessing is classified into two categories:

1. Symmetric Multiprocessing
2. Asymmetric Multiprocessing

Advantages
Increases computing power by utilizing multiple processors.
Suitable for tasks that require heavy computational power.
Disadvantages
Process creation is time-consuming.
Each process has its own address space, which can lead to higher memory usage.

What is Multithreading?
Multithreading is a system in which multiple threads are created of a process for increasing the computing speed of the
system. In multithreading, many threads of a process are executed simultaneously and process creation in multithreading
is done according to economical.
Advantages
More efficient than multiprocessing for tasks within a single process.
Threads share a common address space, which is memory-efficient.
Disadvantages
Not classified into categories like multiprocessing.
Thread creation is economical but can lead to synchronization
issues.

Difference Between Multiprocessing and


Multithreading
Multiprocessing Multithreading

While In Multithreading, many threads are created of a single process for


In Multiprocessing, CPUs are added for increasing computing power.
increasing computing power.

While in multithreading, many threads of a process are executed


In Multiprocessing, Many processes are executed simultaneously.
simultaneously.

Multiprocessing are classified into Symmetric and Asymmetric. While Multithreading is not classified in any categories.

In Multiprocessing, Process creation is a time-consuming process. While in Multithreading, process creation is according to economical.

In Multiprocessing, every process owned a separate address space. While in Multithreading, a common address space is shared by all the threads.

Lifecycle and States of a Thread in Java

A thread in Java at any point of time exists in any one of the following states. A thread lies only in one of the shown states at any
instant:

New State
Runnable State
Blocked State
Waiting State
Timed Waiting State
Terminated State

The diagram shown below represents


various states of a thread at any
instant in time.
Life Cycle of a Thread
There are multiple states of the thread in a lifecycle as mentioned below:

New Thread: When a new thread is created, it is in the new state. The thread has not yet started to run when the
thread is in this state. When a thread lies in the new state, its code is yet to be run and hasn’t started to execute.
Runnable State: A thread that is ready to run is moved to a runnable state. In this state, a thread might actually be
running or it might be ready to run at any instant of time. It is the responsibility of the thread scheduler to give the thread, time to
run.
A multi-threaded program allocates a fixed amount of time to each individual thread. Each and every thread runs for a short while
and then pauses and relinquishes the CPU to another thread so that other threads can get a chance to run. When this happens, all
such threads that are ready to run, waiting for the CPU and the currently running thread lie in a runnable state.
Blocked: The thread will be in blocked state when it is trying to acquire a lock but currently the lock is acquired by the
other thread. The thread will move from the blocked state to runnable state when it acquires the lock.
Waiting state: The thread will be in waiting state when it calls wait() method or join() method. It will move to the
runnable state when other thread will notify or that thread will be terminated.
Timed Waiting: A thread lies in a timed waiting state when it calls a method with a time-out parameter. A thread lies in
this state until the timeout is completed or until a notification is received. For example, when a thread calls sleep or a conditional
wait, it is moved to a timed waiting state.
Terminated State: A thread terminates because of either of the following reasons:
Because it exits normally. This happens when the code of the thread has been entirely executed by the program.
Because there occurred some unusual erroneous event, like a segmentation fault or an unhandled exception.
Implementing the Thread States in Java
In Java, to get the current state of the thread, use Thread.getState() method to get the current state of the thread. Java provides
java.lang.Thread.State class that defines the ENUM constants for the state of a thread, as a summary of which is given below:

1. New
Thread state for a thread that has not yet started.

public static final Thread.State NEW


2. Runnable
Thread state for a runnable thread. A thread in the runnable state is executing in the Java virtual machine but it may be
waiting for other resources from the operating system such as a processor.

public static final Thread.State RUNNABLE


3. Blocked
Thread state for a thread blocked waiting for a monitor lock. A thread in the blocked state is waiting for a monitor lock to
enter a synchronized block/method or reenter a synchronized block/method after calling Object.wait().

public static final Thread.State BLOCKED


4. Waiting
Thread state for a waiting thread. A thread is in the waiting state due to calling one of the following methods:

Object.wait with no timeout


Thread.join with no timeout
LockSupport.park
public static final Thread.State WAITING
5. Timed Waiting
Thread state for a waiting thread with a specified waiting time. A thread is in the timed waiting state due to calling one of
the following methods with a specified positive waiting time:

Thread.sleep
Object.wait with timeout
Thread.join with timeout
LockSupport.parkNanos
LockSupport.parkUntil
public static final Thread.State TIMED_WAITING
6. Terminated
Thread state for a terminated thread. The thread has completed execution.

Declaration: public static final Thread.State TERMINATED


Example
Below is the implementation of the thread states mentioned above:

// Java program to demonstrate thread states


class thread implements Runnable {
public void run()
{
// moving thread2 to timed waiting state
try {
Thread.sleep(1500);
}
catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println(
"State of thread1 while it called join() method on thread2 -"
+ Test.thread1.getState());
try {
Thread.sleep(200);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public class Test implements Runnable {


public static Thread thread1;
public static Test obj;

public static void main(String[] args)


{
obj = new Test();
thread1 = new Thread(obj);

// thread1 created and is currently in the NEW


// state.
System.out.println(
"State of thread1 after creating it - "
+ thread1.getState());
thread1.start();

// thread1 moved to Runnable state


System.out.println(
"State of thread1 after calling .start() method on it - "
+ thread1.getState());
}

public void run()


{
thread myThread = new thread();
Thread thread2 = new Thread(myThread);

// thread2 created and is currently in the NEW


// state.
System.out.println(
"State of thread2 after creating it - "
+ thread2.getState());
thread2.start();

// thread2 moved to Runnable state


System.out.println(
"State of thread2 after calling .start() method on it - "
+ thread2.getState());
// moving thread2 to timed waiting state
try {
// moving thread2 to timed waiting state
Thread.sleep(200);
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(
"State of thread2 after calling .sleep() method on it - "
+ thread2.getState());

try {
// waiting for thread2 to die
thread2.join();
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(
"State of thread2 when it has finished it's execution - "
+ thread2.getState());
}
}

Output :
State of thread1 after creating it - NEW
State of thread1 after calling .start() method on it - RUNNABLE
State of thread2 after creating it - NEW
State of thread2 after calling .start() method on it - RUNNABLE
State of thread2 after calling .sleep() method on it - TIMED_WAITING
State of thread1 while it called join() method on thread2 -WAITING
State of thread2 when it has finished it's execution - TERMINATED

Create a Thread

Thread can be referred to as a lightweight process. Thread uses fewer resources to create and exist in the process; thread
shares process resources. The main thread of Java is the thread that is started when the program starts. The slave thread is
created as a result of the main thread. This is the last thread to complete execution.

A thread can programmatically be created by:

Implementing the java.lang.Runnable interface.


Extending the java.lang.Thread class.
You can create threads by implementing the runnable interface and overriding the run() method. Then, you can create a
thread object and call the start() method.

Thread Class:

The Thread class provides constructors and methods for creating and operating on threads. The thread extends the
Object and implements the Runnable interface.

// start a newly created thread.


// Thread moves from new state to runnable state
// When it gets a chance, executes the target run() method
public void start()
Runnable interface:

Any class with instances that are intended to be executed by a thread should implement the Runnable interface. The Runnable
interface has only one method, which is called run().

// Thread action is performed


public void run()
Benefits of creating threads :
When compared to processes, Java Threads are more lightweight; it takes less time and resources to create a thread.
Threads share the data and code of their parent process.
Thread communication is simpler than process communication.
Context switching between threads is usually cheaper than switching between processes.
Calling run() instead of start()

The common mistake is starting a thread using run() instead of start() method.

Thread myThread = new Thread(MyRunnable());


myThread.run(); //should be start();
The run() method is not called by the thread you created. Instead, it is called by the thread that created the myThread.

Example 1: By using Thread Class

import java.io.*;
class College extends Thread {
public void run()
{
System.out.print("Welcome to College.");
}
public static void main(String[] args)
{
College g = new Colege(); // creating thread
g.start(); // starting thread
}
}
Output :
Welcome to College

Example 2: By implementing Runnable interface

import java.io.*;
class College implements Runnable {
public static void main(String args[])
{
// create an object of Runnable target
College College = new College();

// pass the runnable reference to Thread


Thread t = new Thread(College, "College");

// start the thread


t.start();

// get the name of the thread


System.out.println(t.getName());
}
@Override public void run()
{
System.out.println("Inside run method");
}
}
Output :
Gfg
Inside run method

In Java Threads, if any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the interrupt() method
on the thread, breaks out the sleeping or waiting state throwing InterruptedException. If the thread is not in the sleeping or waiting
state, calling the interrupt() method performs normal behavior and doesn’t interrupt the thread but sets the interrupt flag to true.

interrupt() method: If any thread is in sleeping or waiting for a state then using the interrupt() method, we can interrupt the
execution of that thread by showing InterruptedException. A thread that is in the sleeping or waiting state can be interrupted with
the help of the interrupt() method of Thread class.

Example: Suppose there are two threads and If one of the threads is blocked in an invocation of the wait(), wait(long), or wait(long,
int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then
its interrupt status will be cleared and it will receive an InterruptedException, which gives the chance to another thread to execute
the corresponding run() method of another thread which results into high performance and reduces the waiting time of the threads.

Different scenarios where we can interrupt a thread


Case 1: Interrupting a thread that doesn’t stop working: In the program, we handle the InterruptedException using try and catch
block, so whenever any thread interrupts the currently executing thread it will come out from the sleeping state but it will not stop
working.

// Java Program to illustrate the


// concept of interrupt() method
// while a thread does not stops working

class MyClass extends Thread {


public void run()
{
try {
for (int i = 0; i < 5; i++) {
System.out.println("Child Thread executing");

// Here current threads goes to sleeping state


// Another thread gets the chance to execute
Thread.sleep(1000);
}
}
catch (InterruptedException e) {
System.out.println("InterruptedException occur");
}
}
}

class Test {
public static void main(String[] args)
throws InterruptedException
{
MyClass thread = new MyClass();
thread.start();

// main thread calls interrupt() method on


// child thread
thread.interrupt();

System.out.println("Main thread execution completes");


}
}
Output :
Main thread execution completes
Child Thread executing
InterruptedException occur
Case 2: Interrupting a thread that stops working: In the program, after interrupting the currently executing thread, we are throwing a
new exception in the catch block so it will stop working.

// Java Program to illustrate the


// concept of interrupt() method
// while a thread stops working

class Geeks extends Thread {


public void run()
{
try {
Thread.sleep(2000);
System.out.println("Geeksforgeeks");
}
catch (InterruptedException e) {
throw new RuntimeException("Thread " +
"interrupted");
}
}
public static void main(String args[])
{
Geeks t1 = new Geeks();
t1.start();
try {
t1.interrupt();
}
catch (Exception e) {
System.out.println("Exception handled");
}
}
}
Output :
Exception in thread "Thread-0" java.lang.RuntimeException: Thread interrupted at Geeks.run(File.java:13)

Case 3: Interrupting a thread that works normally: In the program, there is no exception occurred during the execution of the thread.
Here, interrupt only sets the interrupted flag to true, which can be used by Java programmers later.

// Java Program to illustrate the concept of


// interrupt() method

class Geeks extends Thread {


public void run()
{
for (int i = 0; i < 5; i++)
System.out.println(i);
}
public static void main(String args[])
{
Geeks t1 = new Geeks();
t1.start();
t1.interrupt();
}
}
Output :
0
1
2
3
4

Thread Priorities

As we already know java being completely object-oriented works within a multithreading environment in which thread
scheduler assigns the processor to a thread based on the priority of thread. Whenever we create a thread in Java, it always has
some priority assigned to it. Priority can either be given by JVM while creating the thread or it can be given by the programmer
explicitly.

Priorities in threads is a concept where each thread is having a priority which in layman’s language one can say every
object is having priority here which is represented by numbers ranging from 1 to 10.

The default priority is set to 5 as excepted.


Minimum priority is set to 1.
Maximum priority is set to 10.
Here 3 constants are defined in it namely as follows:

public static int NORM_PRIORITY


public static int MIN_PRIORITY
public static int MAX_PRIORITY
Let us discuss it with an example to get how internally the work is getting executed. Here we will be using the knowledge gathered
above as follows:

We will use currentThread() method to get the name of the current thread. User can also use setName() method if he/she
wants to make names of thread as per choice for understanding purposes.
getName() method will be used to get the name of the thread.
The accepted value of priority for a thread is in the range of 1 to 10.
Let us do discuss how to get and set priority of a thread in java.

public final int getPriority(): java.lang.Thread.getPriority() method returns priority of given thread.
public final void setPriority(int newPriority): java.lang.Thread.setPriority() method changes the priority of thread to
the value newPriority. This method throws IllegalArgumentException if value of parameter newPriority goes
beyond minimum(1) and maximum(10) limit.
Example

// Java Program to Illustrate Priorities in Multithreading


// via help of getPriority() and setPriority() method

// Importing required classes


import java.lang.*;

// Main class
class ThreadDemo extends Thread {

// Method 1
// run() method for the thread that is called
// as soon as start() is invoked for thread in main()
public void run()
{
// Print statement
System.out.println("Inside run method");
}

// Main driver method


public static void main(String[] args)
{
// Creating random threads
// with the help of above class
ThreadDemo t1 = new ThreadDemo();
ThreadDemo t2 = new ThreadDemo();
ThreadDemo t3 = new ThreadDemo();

// Thread 1
// Display the priority of above thread
// using getPriority() method
System.out.println("t1 thread priority : "+ t1.getPriority());

// Thread 1
// Display the priority of above thread
System.out.println("t2 thread priority : "+ t2.getPriority());

// Thread 3
System.out.println("t3 thread priority : "+ t3.getPriority());

// Setting priorities of above threads by


// passing integer arguments
t1.setPriority(2);
t2.setPriority(5);
t3.setPriority(8);

// t3.setPriority(21); will throw


// IllegalArgumentException

// 2
System.out.println("t1 thread priority : "+ t1.getPriority());

// 5
System.out.println("t2 thread priority : "+ t2.getPriority());

// 8
System.out.println("t3 thread priority : "+ t3.getPriority());

// Main thread

// Displays the name of


// currently executing Thread
System.out.println("Currently Executing Thread : "+ Thread.currentThread().getName());

System.out.println("Main thread priority : "+ Thread.currentThread().getPriority());

// Main thread priority is set to 10


Thread.currentThread().setPriority(10);

System.out.println("Main thread priority : "+ Thread.currentThread().getPriority());


}
}

Output :
t1 thread priority : 5
t2 thread priority : 5
t3 thread priority : 5
t1 thread priority : 2
t2 thread priority : 5
t3 thread priority : 8
Currently Executing Thread : main
Main thread priority : 5
Main thread priority : 10
Output explanation:

Thread with the highest priority will get an execution chance prior to other threads. Suppose there are 3 threads t1, t2, and
t3 with priorities 4, 6, and 1. So, thread t2 will execute first based on maximum priority 6 after that t1 will execute and then t3.
The default priority for the main thread is always 5, it can be changed later. The default priority for all other threads depends on the
priority of the parent thread.
Synchronizing Threads

Java provides a way of creating threads and synchronizing their tasks using synchronized blocks.

A synchronized block in Java is synchronized on some object. All synchronized blocks synchronize on the same object
and can only have one thread executed inside them at a time. All other threads attempting to enter the synchronized block are
blocked until the thread inside the synchronized block exits the block. If you want to master concurrency and understand how to
avoid common pitfalls, the Java Programming Course offers in-depth coverage of synchronization with practical coding exercises.

Note: Synchronized blocks in Java are marked with the synchronized keyword.

General Form of Synchronized Block


// Only one thread can execute at a time.
// sync_object is a reference to an object
// whose lock associates with the monitor.
// The code is said to be synchronized on
// the monitor object
synchronized(sync_object)
{
// Access shared variables and other
// shared resources
}
This synchronization is implemented in Java with a concept called monitors or locks. Only one thread can own a monitor
at a given time. When a thread acquires a lock, it is said to have entered the monitor. All other threads attempting to enter the
locked monitor will be suspended until the first thread exits the monitor.

Types of Synchronization
There are two synchronizations in Java mentioned below:

Process Synchronization
Thread Synchronization
1. Process Synchronization in Java
Process Synchronization is a technique used to coordinate the execution of multiple processes. It ensures that the shared
resources are safe and in order.

2. Thread Synchronization in Java


Thread Synchronization is used to coordinate and ordering of the execution of the threads in a multi-threaded program.
There are two types of thread synchronization are mentioned below:

Mutual Exclusive
Cooperation (Inter-thread communication in Java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data. There are three types of Mutual
Exclusive mentioned below:

Synchronized method.
Synchronized block.
Static synchronization.
Example of Synchronization
Below is the implementation of the Java Synchronization:

// A Java program to demonstrate working of


// synchronized.

import java.io.*;
import java.util.*;

// A Class used to send a message


class Sender {
public void send(String msg)
{
System.out.println("Sending\t" + msg);
try {
Thread.sleep(1000);
}
catch (Exception e) {
System.out.println("Thread interrupted.");
}
System.out.println("\n" + msg + "Sent");
}
}

// Class for send a message using Threads


class ThreadedSend extends Thread {
private String msg;
Sender sender;

// Receives a message object and a string


// message to be sent
ThreadedSend(String m, Sender obj)
{
msg = m;
sender = obj;
}

public void run()


{
// Only one thread can send a message
// at a time.
synchronized (sender)
{
// synchronizing the send object
sender.send(msg);
}
}
}

// Driver class
class SyncDemo {
public static void main(String args[])
{
Sender send = new Sender();
ThreadedSend S1 = new ThreadedSend(" Hi ", send);
ThreadedSend S2 = new ThreadedSend(" Bye ", send);
// Start two threads of ThreadedSend type
S1.start();
S2.start();

// wait for threads to end


try {
S1.join();
S2.join();
}
catch (Exception e) {
System.out.println("Interrupted");
}
}
}
Output :
Sending Hi
Hi Sent
Sending Bye
Bye Sent

The output is the same every time we run the program.

Explanation
In the above example, we choose to synchronize the Sender object inside the run() method of the ThreadedSend class.
Alternatively, we could define the whole send() block as synchronized, producing the same result.
Example of the synchronized method by using an anonymous class

// Java Pogram to synchronized method by


// using an anonymous class
import java.io.*;

class Test {
synchronized void test_function(int n)
{
// synchronized method
for (int i = 1; i <= 3; i++) {
System.out.println(n + i);
try {
Thread.sleep(500);
}
catch (Exception e) {
System.out.println(e);
}
}
}
}

// Driver Class
public class GFG {
// Main function
public static void main(String args[])
{
// only one object
final Test obj = new Test();

Thread a = new Thread() {


public void run() { obj.test_function(15); }
};

Thread b = new Thread() {


public void run() { obj.test_function(30); }
};

a.start();
b.start();
}
}
Output :
16
17
18
31
32
33

Inter-thread Communication

Inter-thread communication in Java is a mechanism in which a thread is paused running in its critical section and another
thread is allowed to enter (or lock) in the same critical section to be executed.

Note: Inter-thread communication is also known as Cooperation in Java.

Java uses three methods, namely, wait(), notify(), and notifyAll(). All these methods belong to object class as final so that
all classes have them. They must be used within a synchronized block only.

wait():
It tells the calling thread to give up the lock and go to sleep until some other thread enters the same monitor and calls
notify():
It wakes up one single thread called wait() on the same object. It should be noted that calling notify() does not give up a
lock on a resource.
notifyAll():
It wakes up all the threads called wait() on the same object.

Example:

A simple Java program to demonstrate the three methods. Please note that this program might only run in offline IDEs as it
contains taking input at several points.

import java.util.LinkedList;
import java.util.Queue;

public class ProducerConsumer {


// Shared queue used by both producer and consumer
private static final Queue<Integer> queue = new LinkedList<>();
// Maximum capacity of the queue
private static final int CAPACITY = 10;

// Producer task
private static final Runnable producer = new Runnable() {
public void run() {
while (true) {
synchronized (queue) {
// Wait if the queue is full
while (queue.size() == CAPACITY) {
try {
System.out.println("Queue is at max capacity");
queue.wait(); // Release the lock and wait
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Add item to the queue
queue.add(10);
System.out.println("Added 10 to the queue");
queue.notifyAll(); // Notify all waiting consumers
try {
Thread.sleep(2000); // Simulate some delay in production
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};

// Consumer task
private static final Runnable consumer = new Runnable() {
public void run() {
while (true) {
synchronized (queue) {
// Wait if the queue is empty
while (queue.isEmpty()) {
try {
System.out.println("Queue is empty, waiting");
queue.wait(); // Release the lock and wait
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Remove item from the queue
System.out.println("Removed " + queue.remove() + " from the queue");
queue.notifyAll(); // Notify all waiting producers
try {
Thread.sleep(2000); // Simulate some delay in consumption
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};

public static void main(String[] args) {


System.out.println("Main thread started");
// Create and start the producer thread
Thread producerThread = new Thread(producer, "Producer");
// Create and start the consumer thread
Thread consumerThread = new Thread(consumer, "Consumer");
producerThread.start();
consumerThread.start();
System.out.println("Main thread exiting");
}
}
Output :
Main thread started
Main thread exiting
Queue is empty, waiting
Added 10 to the queue
Removed 10 from the queue
Queue is empty, waiting
Added 10 to the queue
Removed 10 from the queue

This output shows the interaction between the producer and consumer, where the producer adds items to the queue, and
the consumer removes them. When the queue is full, the producer waits, and when the queue is empty, the consumer waits,
demonstrating inter-thread communication using wait() and notifyAll() methods.

This example effectively demonstrates inter-thread communication in Java using a typical producer-consumer problem,
showcasing the practical use of wait(), notifyAll(), and synchronization.

A stream is a sequence of data. I/O Stream refers to a stream that is unlikely a method to sequentially access a file. I/O
Stream means an input source or output destination representing different types of sources e.g. disk files. The java.io package
provides classes that allow you to convert between Unicode character streams and byte streams of non-Unicode text.
Input Stream: reads data from the source.
Output Stream: writes data to a destination.

When to use Character Stream over Byte Stream?


In Java, characters are stored using Unicode conventions. Character stream is useful when we want to process text files.
These text files can be processed character by character. Character size is typically 16 bits.

When to use Byte Stream over Character Stream?


Byte oriented reads byte by byte. A byte stream is suitable for processing raw data like binary files.
Key points while using and dealing with any of the above streams are as follows:

Names of character streams typically end with Reader/Writer and names of byte streams end with
InputStream/OutputStream
The streams used in example codes are unbuffered streams and less efficient. We typically use them with buffered
readers/writers for efficiency. We will soon be discussing use BufferedReader/BufferedWriter (for character stream) and
BufferedInputStream/BufferedOutputStream (for byte stream) classes.
It is always recommended to close the stream if it is no longer in use. This ensures that the streams won’t be affected if
any error occurs.
The above codes may not run in online compilers as files may not exist.

Character Stream

In Java, characters are stored using Unicode conventions. Character stream automatically allows us to read/write data
character by character. For example, FileReader and FileWriter are character streams used to read from the source and write to the
destination.

// Java Program illustrate Reading


// a File in Human Readable
// Format Using FileReader Class

// Importing required classes


import java.io.*;

// Main class
public class GFG {

// Main driver method


public static void main(String[] args)
throws IOException
{

// Initially assigning null as we have not read


// anything
FileReader sourceStream = null;

// Try block to check for exceptions


try {

// Reading from file


sourceStream = new FileReader(
"/Users/mayanksolanki/Desktop/demo.rtf");

// Reading sourcefile and writing content to


// target file character by character.

int temp;

// If there is content inside file


// than read
while ((temp = sourceStream.read()) != -1)
System.out.println((char)temp);

// Display message for successful execution of program


System.out.print("Program successfully executed");
}

// finally block that executes for sure


// where we are closing file connections
// to avoid memory leakage
finally {

// Closing stream as no longer in use


if (sourceStream != null)
sourceStream.close();
}
}
}
Output :
Output: Writes content to the target file character by character
Program successfully executed
Byte Stream
Byte streams process data byte by byte (8 bits). For example, FileInputStream is used to read from the source and
FileOutputStream to write to the destination.

// Java Program Illustrate ByteStream Class to


// Copy Contents of One File to Another File

// Importing required classes


import java.io.*;

// Main class
public class GFG {

// Main driver method


public static void main(String[] args)
throws IOException
{

// Initially assigning null ot objects for


// reading and writing to file
FileInputStream sourceStream = null;
FileOutputStream targetStream = null;

// Try block to check for exceptions


try {

// Passing the files via local directory


sourceStream = new FileInputStream(
"/Users/mayanksolanki/Desktop/demo.rtf");
targetStream = new FileOutputStream(
"/Users/mayanksolanki/Desktop/democopy.rtf");

// Reading source file and writing content to


// target file byte by byte
int temp;

// If there is content inside file


// than read
while ((temp = sourceStream.read()) != -1)
targetStream.write((byte)temp);

// Display message for successful execution of program


System.out.print("Program successfully executed");
}

// finally block that executes for sure


// where we are closing file connections
// to avoid memory leakage
finally {
if (sourceStream != null)
sourceStream.close();

if (targetStream != null)
targetStream.close();
}
}
}
Output:

Program successfully executed

Ways to read input from console in Java

In Java, there are four different ways to read input from the user in the command line environment(console).

1. Using Buffered Reader Class


This is the Java classical method to take input, Introduced in JDK 1.0. This method is used by wrapping the System.in
(standard input stream) in an InputStreamReader which is wrapped in a BufferedReader, we can read input from the user in the
command line.

The input is buffered for efficient reading.


The wrapping code is hard to remember.
Implementation:

// Java program to demonstrate BufferedReader


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args)
throws IOException
{
// Enter data using BufferReader
BufferedReader reader = new BufferedReader(
new InputStreamReader(System.in));

// Reading data using readLine


String name = reader.readLine();

// Printing the read line


System.out.println(name);
}
}
Output :
Input:
Geek
Output:
Geek
Auxiliary Space: O(1)

Note: To read other types, we use functions like Integer.parseInt(), Double.parseDouble(). To read multiple values, we use split().

Reading input from the console is a common task in Java applications. If you want to explore more ways to handle user
input and optimize your code for various scenarios, the Java Programming Course provides hands-on lessons with practical
examples.

2. Using Scanner Class


This is probably the most preferred method to take input, Introduced in JDK 1.5. The main purpose of the Scanner class is
to parse primitive types and strings using regular expressions; however, it is also can be used to read input from the user in the
command line.

Convenient methods for parsing primitives (nextInt(), nextFloat(), …) from the tokenized input.
Regular expressions can be used to find tokens.
The reading methods are not synchronized.

// Java program to demonstrate working of Scanner in Java


import java.util.Scanner;

class GetInputFromUser {
public static void main(String args[])
{
// Using Scanner for Getting Input from User
Scanner in = new Scanner(System.in);

String s = in.nextLine();
System.out.println("You entered string " + s);

int a = in.nextInt();
System.out.println("You entered integer " + a);

float b = in.nextFloat();
System.out.println("You entered float " + b);
}
}
Input:
GeeksforGeeks
12
3.4

Output:
You entered string GeeksforGeeks
You entered integer 12
You entered float 3.4

3. Using Console Class


It has been becoming a preferred way for reading user’s input from the command line, Introduced in JDK 1.6. In addition, it
can be used for reading password-like input without echoing the characters entered by the user; the format string syntax can also
be used (like System.out.printf()).

Advantages:

Reading password without echoing the entered characters.


Reading methods are synchronized.
Format string syntax can be used.
Does not work in non-interactive environment (such as in an IDE).

// Java program to demonstrate working of System.console()


// Note that this program does not work on IDEs as
// System.console() may require console
public class Sample {
public static void main(String[] args)
{
// Using Console to input data from user
String name = System.console().readLine();

System.out.println("You entered string " + name);


}
}
Input:
GeeksforGeeks

Output:
You entered string GeeksforGeeks

4. Using Command line argument


Most used user input for competitive coding available right from the initial release of Java (JDK 1.0). The command-line
arguments are stored in the String format. The parseInt method of the Integer class converts string argument into Integer. Similarly,
for float and others during execution. The usage of args[] comes into existence in this input form. The passing of information takes
place during the program run. The command line is given to args[]. These programs have to be run on cmd.
Code Implementation:

// Program to check for command line arguments


class Hello {
public static void main(String[] args)
{
// check if length of args array is
// greater than 0
if (args.length > 0) {
System.out.println(
"The command line arguments are:");

// iterating the args array and printing


// the command line arguments
for (String val : args)
System.out.println(val);
}
else
System.out.println("No command line "
+ "arguments found.");
}
}
Command Line Arguments:

javac GFG1.java
java Main Hello World

Output:
The command line arguments are:
Hello
World

5. Using DataInputStream class


A DataInputStream in Java is a class that provides a convenient way to read primitive Java data types from an input
stream in a machine-independent manner, introduced in JDK 1.0. It wraps an existing InputStream and allows applications to read
Java primitive data types (int, short, long, byte, float, double, char, boolean) and strings from the underlying input stream,
preserving their binary format. DataInputStream is part of the java.io package and is particularly useful when you need to read data
that was written using a DataOutputStream or any other source that wrote data in a compatible format.

Definition:

DataInputStream is a Java class that implements data input operations. It allows applications to read primitive data types
and strings from an input stream in a machine-independent way. It achieves this by wrapping an existing input stream and providing
methods to read various primitive data types and strings from the underlying input source.

Remember that DataInputStream reads data in a binary format, so it’s important to ensure that the data being read was
written using the correct methods in DataOutputStream or a compatible source to avoid data corruption or misinterpretation.

Code Implementation:

//Java program to read input using DataInputStream class


import java.io.*;

public class Main {


public static void main(String[] args) throws IOException {
DataInputStream reader = new DataInputStream(System.in);

// Reading integers
System.out.print("Enter an integer: ");
int inputInt = Integer.parseInt(reader.readLine());

// Reading strings
System.out.print("Enter a string: ");
String inputString = reader.readLine();
System.out.println("You entered integer: " + inputInt);
System.out.println("You entered string: " + inputString);
}
}
Input:
Enter an integer: 10
Enter a string: GeeksForGeeks
Output:
You entered integer: 10
You entered string :GeeksForGeeks

Bufferreader class writes text to character-output stream, buffering characters.Thus, providing efficient writing of single array,
character and strings. A buffer size needs to be specified, if not it takes Default value.
An output is immediately set to the underlying character or byte stream by the Writer.
Class Declaration

public class BufferedWriter


extends Writer

Constructors

BufferedWriter(Writer out):
Creates a buffered character-output stream that uses a default-sized output buffer.
BufferedWriter(Writer out, int size):
Creates a new buffered character-output stream that uses an output buffer of the given size.
Methods:

write() : java.io.BufferedWriter.write(int arg) writes a single character that is specified by an integer argument.
newLine() : java.io.BufferedWriter.newLine() breaks/separates line.
flush() : java.io.BufferedWriter.flush() flushes character from write buffer.
close() : java.io.BufferedWriter.close() flushes character from write buffer and then close it.

Implementation :

//Java program illustrating use of flush(), close() method

import java.io.*; //BufferedWriter, FileWriter, IOException


public class NewClass
{
public static void main(String[] args)
{
FileWriter geek_file; //initializing FileWriter
try
{
geek_file = new FileWriter("ABC.txt");
// Initializing BufferedWriter
BufferedWriter geekwrite = new BufferedWriter(geek_file);
System.out.println("Buffered Writer start writing :)");
// Use of write() method to write the value in 'ABC' file

geekwrite.write(69); // Printing E
geekwrite.newLine(); // For next line
geekwrite.write(49); // Printing 1

// flush() method : flushing the stream


geekwrite.flush();
// close() method : closing BufferWriter to end operation
geekwrite.close();
System.out.println("Written successfully");
}
catch (IOException except)
{
except.printStackTrace();
}

}
}
Output :
Buffered Writer start writing :)
Written successfully

In Java, OutputStreamWriter class connects character streams to byte streams. It encodes Characters into bytes using a specified
charset.

Declaration of Java OutputStreamWriter Class


public class OutputStreamWriter
extends Writer
Constructors of OutputStreamWriter Class in Java
Constructors in OutputStreamWriter are mentioned below:

OutputStreamWriter(OutputStream geek_out) : Creates a “geek_out” OutputStreamWriter that uses


default charset for encoding.
OutputStreamWriter(OutputStream geek_out, Charset geek_set): Creates a “geek_out” OutputStreamWriterthat uses a “geek_ set”
charset for encoding.
OutputStreamWriter(OutputStream geek_out, CharsetEncoder encode): Creates a “geek_out” OutputStreamWriter that uses a
given encoder.
OutputStreamWriter(OutputStream geek_out, String setName): Creates a “geek_out” OutputStreamWriter that uses a named
character set.

flush() : java.io.OutputStreamWriter.flush() flushes the stream.


close() : java.io.OutputStreamWriter.close() closes the flushed stream.
write(int char) :java.io.OutputStreamWriter.write(int char) writes a single character.
write(String geek, int offset, int strlen) :java.io.OutputStreamWriter.write(String geek, int offset, int strlen) writes a portion of the
“geek” string starting from “offset position” upto “strlen” length.
write(char[] geek, int offset, int strlen) :java.io.OutputStreamWriter.write(char[] geek, int offset, int strlen) writes a portion of the
“geek” character array starting from “offset position” upto “strlen” length.
getEncoding() :java.io.OutputStreamWriter.getEncoding() tells the name of the character encoding being used in the mentioned
Stream. If there is predefined name exists, then it is returned otherwise the canonical name of the encoding is returned.
Returns Null, if the stream has been already closed.

// Java code explaining write(char[] geek, int offset, int


// strlen) and getEncoding() method
import java.io.*;

// Driver Class
public class NewClass {
// Main Function
public static void main(String[] args)
{
char[] geek = { 'G', 'E', 'E', 'K', 'S' };
try {
// Creation of new OutputStreamWriter
OutputStream g
= new FileOutputStream("test.txt");
OutputStreamWriter geeks_out1
= new OutputStreamWriter(g);

// Creating an Input Stream


FileInputStream in
= new FileInputStream("test.txt");

// Use of write(char[] geek, int offset, int


// strlen)) : Writing character values to the
// "test.txt"
geeks_out1.write(geek, 0, 3);

// flush the stream


geeks_out1.flush();

// read what we write


for (int i = 0; i < 3; i++) {
// Reading the content of "test.txt" file
System.out.println(
"char[] geek, int offset, int strlen) : "
+ (char)in.read());
}

// get and print the encoding for this stream


System.out.println("\nName of the charset : "
+ geeks_out1.getEncoding());

// Closing the OutputStreamWriter


geeks_out1.close();
}

catch (Exception ex) {


System.out.println("Error");
ex.printStackTrace();
}
}
}
Output :

char[] geek, int offset, int strlen) : G


char[] geek, int offset, int strlen) : E
char[] geek, int offset, int strlen) : E
Name of the charset : UTF8

File Class :
Java File class is Java’s representation of a file or directory pathname. Because file and directory names have different
formats on different platforms, a simple string is not adequate to name them. Java File class contains several methods for working
with the pathname, deleting and renaming files, creating new directories, listing the contents of a directory, and determining several
common attributes of files and directories.

It is an abstract representation of files and directory pathnames.


A pathname, whether abstract or in string form can be either absolute or relative. The parent of an abstract pathname may be
obtained by invoking the getParent() method of this class.
First of all, we should create the File class object by passing the filename or directory name to it. A file system may implement
restrictions to certain operations on the actual file-system object, such as reading, writing, and executing. These restrictions are
collectively known as access permissions.
Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never
change.
How to Create a File Object?
A File object is created by passing in a string that represents the name of a file, a String, or another File object. For
example,

File a = new File("/usr/local/bin/geeks");


This defines an abstract file name for the geeks file in the directory /usr/local/bin. This is an absolute abstract file name.

Fields in File Class in Java

Field Type Description

pathSeperator String the character or string used to separate individual paths in a list of file system paths.

pathSeperatorChar Char the character used to separate individual paths in a list of file system paths.

separator String default name separator character represented as a string.

separatorChar Char default name separator character.

Constructors of Java File Class


File(File parent, String child): Creates a new File instance from a parent abstract pathname and a child pathname string.
File(String pathname): Creates a new File instance by converting the given pathname string into an abstract pathname.
File(String parent, String child): Creates a new File instance from a parent pathname string and a child pathname string.
File(URI uri): Creates a new File instance by converting the given file: URI into an abstract pathname.
Methods of File Class in Java

S. No. Method Description Return Type

Tests whether the application can execute the file denoted by this abstract
1. canExecute() boolean
pathname.

Tests whether the application can read the file denoted by this abstract
2. canRead() boolean
pathname.

Tests whether the application can modify the file denoted by this abstract
3. canWrite() boolean
pathname.

compareTo(File
4. Compares two abstract pathnames lexicographically. int
pathname)

5. createNewFile() Atomically creates a new, empty file named by this abstract pathname. boolean

createTempFile(String
6. Creates an empty file in the default temporary-file directory. File
prefix, String suffix)

7. delete() Deletes the file or directory denoted by this abstract pathname. boolean

8. equals(Object obj) Tests this abstract pathname for equality with the given object. boolean

9. exists() Tests whether the file or directory denoted by this abstract pathname exists. boolean

10. getAbsolutePath() Returns the absolute pathname string of this abstract pathname. String

11. list() Returns an array of strings naming the files and directories in the directory. String[]

12. getFreeSpace() Returns the number of unallocated bytes in the partition. long

13. getName() Returns the name of the file or directory denoted by this abstract pathname. String

14. getParent() Returns the pathname string of this abstract pathname’s parent. String

15. getParentFile() Returns the abstract pathname of this abstract pathname’s parent. File

16. getPath() Converts this abstract pathname into a pathname string. String

17. setReadOnly() Marks the file or directory named so that only read operations are allowed. boolean

18. isDirectory() Tests whether the file denoted by this pathname is a directory. boolean
19. isFile() Tests whether the file denoted by this abstract pathname is a normal file. boolean

20. isHidden() Tests whether the file named by this abstract pathname is a hidden file. boolean

21. length() Returns the length of the file denoted by this abstract pathname. long

22. listFiles() Returns an array of abstract pathnames denoting the files in the directory. File[]

23. mkdir() Creates the directory named by this abstract pathname. boolean

24. renameTo(File dest) Renames the file denoted by this abstract pathname. boolean

setExecutable(boolean
25. A convenience method to set the owner’s execute permission. boolean
executable)

setReadable(boolean
26. A convenience method to set the owner’s read permission. boolean
readable)

setReadable(boolean
27. readable, boolean Sets the owner’s or everybody’s read permission. boolean
ownerOnly)

setWritable(boolean
28. A convenience method to set the owner’s write permission. boolean
writable)

29. toString() Returns the pathname string of this abstract pathname. String

30. toURI() Constructs a file URI that represents this abstract pathname. URI

Java File Class Examples


Example 1: Program to check if a file or directory physically exists or not.

// In this Java program, we accepts a file or directory name


// from command line arguments. Then the program will check
// if that file or directory physically exist or not and it
// displays the property of that file or directory.

import java.io.File;

// Displaying file property


class fileProperty {
public static void main(String[] args)
{

// accept file name or directory name through


// command line args
String fname = args[0];

// pass the filename or directory name to File


// object
File f = new File(fname);

// apply File class methods on File object


System.out.println("File name :" + f.getName());
System.out.println("Path: " + f.getPath());
System.out.println("Absolute path:"
+ f.getAbsolutePath());
System.out.println("Parent:" + f.getParent());
System.out.println("Exists :" + f.exists());

if (f.exists()) {
System.out.println("Is writable:"
+ f.canWrite());
System.out.println("Is readable" + f.canRead());
System.out.println("Is a directory:"
+ f.isDirectory());
System.out.println("File Size in bytes "
+ f.length());
}
}
}

Output

File name :file.txt


Path: file.txt
Absolute path:C:\Users\akki\IdeaProjects\codewriting\src\file.txt
Parent:null
Exists :true
Is writable:true
Is readabletrue
Is a directory:false
File Size in bytes 20
Example 2: Program to display all the contents of a directory

Here we will accept a directory name from the keyboard and then display all the contents of the directory. For this purpose, list()
method can be used as:
String arr[]=f.list();
In the preceding statement, the list() method causes all the directory entries copied into the array arr[]. Then pass these array
elements arr[i] to the File object and test them to know if they represent a file or directory.

// Java Program to display all


// the contents of a directory
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

// Displaying the contents of a directory


class Contents {
public static void main(String[] args)
throws IOException
{
// enter the path and dirname from keyboard
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));

System.out.println("Enter dirpath:");
String dirpath = br.readLine();
System.out.println("Enter the dirname");
String dname = br.readLine();

// create File object with dirpath and dname


File f = new File(dirpath, dname);

// if directory exists,then
if (f.exists()) {
// get the contents into arr[]
// now arr[i] represent either a File or
// Directory
String arr[] = f.list();

// find no. of entries in the directory


int n = arr.length;
// displaying the entries
for (int i = 0; i < n; i++) {
System.out.println(arr[i]);
// create File object with the entry and
// test if it is a file or directory
File f1 = new File(arr[i]);
if (f1.isFile())
System.out.println(": is a file");
if (f1.isDirectory())
System.out.println(": is a directory");
}
System.out.println(
"No of entries in this directory " + n);
}
else
System.out.println("Directory not found");
}
}
Output

Enter dirpath:
C:\Users\akki\IdeaProjects\
Enter the dirname
codewriting
.idea
: is a directory
an1.txt
: is a file
codewriting.iml
: is a file
file.txt
: is a file
out
: is a directory
src
: is a directory
text
: is a file
No of entries in this directory 7
Java FileWriter and FileReader classes are used to write and read data from text files (they are Character Stream classes). It is
recommended not to use the FileInputStream and FileOutputStream classes if you have to read and write any textual information
as these are Byte stream classes.

Reading and Writing Files

FileWriter
FileWriter is useful to create a file writing characters into it.

This class inherits from the OutputStream class.


The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To
specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.

FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using a FileOutputStream.
FileWriter creates the output file if it is not present already.
Constructors:

FileWriter(File file) – Constructs a FileWriter object given a File object.


FileWriter (File file, boolean append) – constructs a FileWriter object given a File object.
FileWriter (FileDescriptor fd) – constructs a FileWriter object associated with a file descriptor.
FileWriter (String fileName) – constructs a FileWriter object given a file name.
FileWriter (String fileName, Boolean append) – Constructs a FileWriter object given a file name with a Boolean indicating
whether or not to append the data written.
Methods:

public void write (int c) throws IOException – Writes a single character.


public void write (char [] stir) throws IOException – Writes an array of characters.
public void write(String str)throws IOException – Writes a string.
public void write(String str, int off, int len)throws IOException – Writes a portion of a string. Here off is offset from
which to start writing characters and len is the number of characters to write.
public void flush() throws IOException flushes the stream
public void close() throws IOException flushes the stream first and then closes the writer.

Reading and writing take place character by character, which increases the number of I/O operations and affects the
performance of the system.BufferedWriter can be used along with FileWriter to improve the speed of execution.
The following program depicts how to create a text file using FileWriter

// Creating a text File using FileWriter


import java.io.FileWriter;
import java.io.IOException;
class CreateFile
{
public static void main(String[] args) throws IOException
{
// Accept a string
String str = "File Handling in Java using "+
" FileWriter and FileReader";

// attach a file to FileWriter


FileWriter fw=new FileWriter("output.txt");

// read character wise from string and write


// into FileWriter
for (int i = 0; i < str.length(); i++)
fw.write(str.charAt(i));

System.out.println("Writing successful");
//close the file
fw.close();
}
}

FileReader
FileReader is useful to read data in the form of characters from a ‘text’ file.

This class inherited from the InputStreamReader Class.


The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate.
To specify these values yourself, construct an InputStreamReader on a FileInputStream.

FileReader is meant for reading streams of characters. For reading streams of raw bytes, consider using a FileInputStream.
Constructors:

FileReader(File file) – Creates a FileReader , given the File to read from


FileReader(FileDescripter fd) – Creates a new FileReader , given the FileDescripter to read from
FileReader(String fileName) – Creates a new FileReader , given the name of the file to read from
Methods:

public int read () throws IOException – Reads a single character. This method will block until a character is available, an I/O error
occurs, or the end of the stream is reached.
public int read(char[] cbuff) throws IOException – Reads characters into an array. This method will block until some input is
available, an I/O error occurs, or the end of the stream is reached.
public abstract int read(char[] buff, int off, int len) throws IOException –Reads characters into a portion of an array. This method will
block until some input is available, an I/O error occurs, or the end of the stream is reached.
Parameters:
cbuf – Destination buffer
off – Offset at which to start storing characters
len – Maximum number of characters to read

public void close() throws IOException closes the reader.


public long skip(long n) throws IOException –Skips characters. This method will block until some characters are
available, an I/O error occurs, or the end of the stream is reached.
Parameters:
n – The number of characters to skip
The following program depicts how to read from the ‘text’ file using FileReader

// Reading data from a file using FileReader


import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
class ReadFile
{
public static void main(String[] args) throws IOException
{
// variable declaration
int ch;

// check if File exists or not


FileReader fr=null;
try
{
fr = new FileReader("text");
}
catch (FileNotFoundException fe)
{
System.out.println("File not found");
}

// read from FileReader till the end of file


while ((ch=fr.read())!=-1)
System.out.print((char)ch);

// close the file


fr.close();
}
}

The Console Class :


The Java.io.Console class provides methods to access the character-based console device, if any, associated with the
current Java virtual machine. The Console class was added to java.io by JDK 6.

Important Points:

It is used to read from and write to the console, if one exists.


Console is primarily a convenience class because most of its functionality is available through System.in and System.out.
However, its use can simplify some types of console interactions, especially when reading strings from the console.
Console supplies no constructors. Instead, a Console object is obtained by calling System.console( ), which is shown
here:
static Console console( )
If a console is available, then a reference to it is returned. Otherwise, null is returned. A console will not be available in all
cases. Thus, if null is returned, no console I/O is possible.

It provides methods to read text and password. If you read password using Console class, it will not be displayed to the
user.The java.io.Console class is attached with system console internally.
Important Methods:

writer : Retrieves the unique PrintWriter object associated with this console.

reader : Retrieves the unique Reader object associated with this console.
format : Writes a formatted string to this console’s output stream using the specified format string and arguments.
printf : A convenience method to write a formatted string to this console’s output stream using the specified format string
and arguments.
readLine : Provides a formatted prompt, then reads a single line of text from the console.
readLine : Reads a single line of text from the console.
readPassword: Provides a formatted prompt, then reads a password or passphrase from the console with echoing
disabled.
readPassword : Reads a password or passphrase from the console with echoing disabled.
flush : Flushes the console and forces any buffered output to be written immediately .
// Java Program to demonstrate Console Methods

import java.io.*;
class ConsoleDemo
{
public static void main(String args[])
{
String str;

//Obtaining a reference to the console.


Console con = System.console();

// Checking If there is no console available, then exit.


if(con == null)
{
System.out.print("No console available");
return;
}

// Read a string and then display it.


str = con.readLine("Enter your name: ");
con.printf("Here is your name: %s\n", str);

//to read password and then display it


System.out.println("Enter the password: ");
char[] ch=con.readPassword();

//converting char array into string


String pass = String.valueOf(ch);
System.out.println("Password is: " + pass);
}
}
Output:

Enter your name: Nishant Sharma


Here is your name: Nishant Sharma
Enter the password:
Password is: dada

Serialization:

Serialization is a mechanism of converting the state of an object into a byte stream. Deserialization is the reverse process
where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persist the object.

Serialization and deserialization are crucial for saving and restoring the state of objects in Java. To explore more advanced
use cases and learn best practices, the Java Programming Course provides detailed lessons on object serialization with practical
examples.

The byte stream created is platform independent. So, the object serialized on one platform can be deserialized on a
different platform. To make a Java object serializable we implement the java.io.Serializable interface. The ObjectOutputStream
class contains writeObject() method for serializing an Object.

public final void writeObject(Object obj)


throws IOException
The ObjectInputStream class contains readObject() method for deserializing an object.

public final Object readObject()


throws IOException,
ClassNotFoundException

// Java code for serialization and deserialization


// of a Java object
import java.io.*;

class Demo implements java.io.Serializable


{
public int a;
public String b;

// Default constructor
public Demo(int a, String b)
{
this.a = a;
this.b = b;
}

class Test
{
public static void main(String[] args)
{
Demo object = new Demo(1, &quot;geeksforgeeks&quot;);
String filename = &quot;file.ser&quot;;

// Serialization
try
{
//Saving of object in a file
FileOutputStream file = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(file);

// Method for serialization of object


out.writeObject(object);

out.close();
file.close();

System.out.println(&quot;Object has been serialized&quot;);

catch(IOException ex)
{
System.out.println(&quot;IOException is caught&quot;);
}

Demo object1 = null;

// Deserialization
try
{
// Reading the object from a file
FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);

// Method for deserialization of object


object1 = (Demo)in.readObject();

in.close();
file.close();

System.out.println(&quot;Object has been deserialized &quot;);


System.out.println(&quot;a = &quot; + object1.a);
System.out.println(&quot;b = &quot; + object1.b);
}

catch(IOException ex)
{
System.out.println(&quot;IOException is caught&quot;);
}

catch(ClassNotFoundException ex)
{
System.out.println(&quot;ClassNotFoundException is caught&quot;);
}

}
}
Output :

Object has been serialized


Object has been deserialized
a=1
b = geeksforgeeks
—-------------------------------------
Unit - V
Swing is a Java Foundation Classes [JFC] library and an extension of the Abstract Window Toolkit [AWT]. Java Swing
offers much-improved functionality over AWT, new components, expanded components features, and excellent event handling with
drag-and-drop support.

Introduction of Java Swing


Swing has about four times the number of User Interface [UI] components as AWT and is part of the standard Java
distribution. By today’s application GUI requirements, AWT is a limited implementation, not quite capable of providing the
components required for developing complex GUIs required in modern commercial applications. The AWT component set has quite
a few bugs and does take up a lot of system resources when compared to equivalent Swing resources. Netscape introduced its
Internet Foundation Classes [IFC] library for use with Java. Its Classes became very popular with programmers creating GUI’s for
commercial applications.

Swing is a Set of API (API- Set of Classes and Interfaces)


Swing is Provided to Design Graphical User Interfaces
Swing is an Extension library to the AWT (Abstract Window Toolkit)

Java AWT Java Swing

Swing is a part of Java Foundation Classes and is used to create


Java AWT is an API to develop GUI applications in Java.
various applications.

Components of AWT are heavy weighted. The components of Java Swing are lightweight.

Components are platform dependent. Components are platform independent.

Execution Time is more than Swing. Execution Time is less than AWT.

AWT components require java.awt package. Swing components requires javax.swing package.

Pluggable look and feel.


Uses MVC architecture.
Lightweight Components
Platform Independent
Advanced features such as JTable, JTabbedPane, JScollPane, etc.
Java is a platform-independent language and runs on any client machine, the GUI look and feel, owned and delivered by a
platform-specific O/S, simply does not affect an application’s GUI constructed using Swing components.
Lightweight Components: Starting with the JDK 1.1, its AWT-supported lightweight component development. For a
component to qualify as lightweight, it must not depend on any non-Java [O/s based) system classes. Swing components
have their own view supported by Java’s look and feel classes.
Pluggable Look and Feel: This feature enable the user to switch the look and feel of Swing components without restarting
an application. The Swing library supports components’ look and feels that remain the same across all platforms wherever
the program runs. The Swing library provides an API that gives real flexibility in determining the look and feel of the GUI of
an application
Highly customizable – Swing controls can be customized in a very easy way as visual appearance is independent of
internal representation.
Rich controls– Swing provides a rich set of advanced controls like Tree TabbedPane, slider, colorpicker, and table
controls.
Swing Classes Hierarchy

// Java program using label (swing)


// to display the message “GFG WEB Site Click”
import java.io.*;
import javax.swing.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Creating instance of JFrame
JFrame frame = new JFrame();

// Creating instance of JButton


JButton button = new JButton(" GFG WebSite Click");

// x axis, y axis, width, height


button.setBounds(150, 200, 220, 50);

// adding button in JFrame


frame.add(button);

// 400 width and 500 height


frame.setSize(500, 600);

// using no layout managers


frame.setLayout(null);

// making the frame visible


frame.setVisible(true);
}
}

// Java program to create three buttons


// with caption OK, SUBMIT, CANCEL
import java.awt.*;

class button {
button()
{
Frame f = new Frame();
// Button 1 created
// OK button
Button b1 = new Button("OK");
b1.setBounds(100, 50, 50, 50);
f.add(b1);

// Button 2 created
// Submit button
Button b2 = new Button("SUBMIT");
b2.setBounds(100, 101, 50, 50);
f.add(b2);

// Button 3 created
// Cancel button
Button b3 = new Button("CANCEL");
b3.setBounds(100, 150, 80, 50);
f.add(b3);

f.setSize(500, 500);
f.setLayout(null);
f.setVisible(true);
}

public static void main(String a[]) { new button(); }


}

// Java Swing Program to Add Checkbox


// in the Frame
import java.awt.*;

// Driver Class
class Lan {
// Main Function
Lan()
{
// Frame Created
Frame f = new Frame();

Label l1 = new Label("Select known Languages");

l1.setBounds(100, 50, 120, 80);


f.add(l1);

// CheckBox created
Checkbox c2 = new Checkbox("Hindi");
c2.setBounds(100, 150, 50, 50);
f.add(c2);

// CheckBox created
Checkbox c3 = new Checkbox("English");
c3.setBounds(100, 200, 80, 50);
f.add(c3);

// CheckBox created
Checkbox c4 = new Checkbox("marathi");
c4.setBounds(100, 250, 80, 50);
f.add(c4);

f.setSize(500, 500);
f.setLayout(null);
f.setVisible(true);
}

public static void main(String ar[]) { new Lan(); }


}

Class Description
A Component is the Abstract base class for about the non-menu user-interface controls of Java SWING. Components are
Component
representing an object with a graphical representation.

Container A Container is a component that can container Java SWING Components

A JComponent is a base class for all swing UI Components In order to use a swing component that inherits from
JComponent
JComponent, the component must be in a containment hierarchy whose root is a top-level Java Swing container.

JLabel A JLabel is an object component for placing text in a container.

JButton This class creates a labeled button.

JColorChoose
A JColorChooser provides a pane of controls designed to allow the user to manipulate and select a color.
r

JCheckBox A JCheckBox is a graphical (GUI) component that can be in either an on-(true) or off-(false) state.

JRadioButton The JRadioButton class is a graphical (GUI) component that can be in either an on-(true) or off-(false) state. in the group

JList A JList component represents the user with the scrolling list of text items.

JComboBox A JComboBox component is Presents the User with a show up Menu of choices.

JTextField A JTextField object is a text component that will allow for the editing of a single line of text.

JPasswordFie
A JPasswordField object it is a text component specialized for password entry.
ld

JTextArea A JTextArea object is a text component that allows for the editing of multiple lines of text.

Imagelcon A ImageIcon control is an implementation of the Icon interface that paints Icons from Images

JScrollbar A JScrollbar control represents a scroll bar component in order to enable users to Select from range values.

JOptionPane JOptionPane provides set of standard dialog boxes that prompt users for a value or Something.

JFileChooser A JFileChooser it Controls represents a dialog window from which the user can select a file.

JProgressBar As the task progresses towards completion, the progress bar displays the tasks percentage on its completion.

JSlider A JSlider this class is letting the user graphically (GUI) select by using a value by sliding a knob within a bounded interval.

A JSpinner this class is a single line input where the field that lets the user select by using a number or an object value from
JSpinner
an ordered sequence.

MVC Architecture:
The Model View Controller (MVC) design pattern specifies that an application consists of a data model, presentation
information, and control information. The pattern requires that each of these be separated into different objects.
The MVC pattern separates the concerns of an application into three distinct components, each responsible for a specific
aspect of the application’s functionality.
This separation of concerns makes the application easier to maintain and extend, as changes to one component do not
require changes to the other components.
To explore MVC further and learn how to implement it in various frameworks, the System Design Course provides a
thorough overview of the MVC pattern and its applications.
Components of the MVC Design Pattern :

1. Model
The Model component in the MVC (Model-View-Controller) design pattern demonstrates the data and business logic of an
application. It is responsible for managing the application’s data, processing business rules, and responding to requests for
information from other components, such as the View and the Controller.

2. View
Displays the data from the Model to the user and sends user inputs to the Controller. It is passive and does not directly interact with
the Model. Instead, it receives data from the Model and sends user inputs to the Controller for processing.

3. Controller
Controller acts as an intermediary between the Model and the View. It handles user input and updates the Model accordingly and
updates the View to reflect changes in the Model. It contains application logic, such as input validation and data transformation.

Communication between the Components


This below communication flow ensures that each component is responsible for a specific aspect of the application’s
functionality, leading to a more maintainable and scalable architecture

User Interaction with View: The user interacts with the View, such as clicking a button or entering text into a form.
View Receives User Input: The View receives the user input and forwards it to the Controller.
Controller Processes User Input: The Controller receives the user input from the View. It interprets the input, performs any
necessary operations (such as updating the Model), and decides how to respond.
Controller Updates Model: The Controller updates the Model based on the user input or application logic.
Model Notifies View of Changes: If the Model changes, it notifies the View.
View Requests Data from Model: The View requests data from the Model to update its display.
Controller Updates View: The Controller updates the View based on the changes in the Model or in response to user input.
View Renders Updated UI: The View renders the updated UI based on the changes made by the Controller.
Example of the MVC Design Pattern
Below is the code of above problem statement using MVC Design Pattern:
Let’s break down into the component wise code:
class Student {
private String rollNo;
private String name;

public String getRollNo() {


return rollNo;
}

public void setRollNo(String rollNo) {


this.rollNo = rollNo;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}
}

class StudentView {
public void printStudentDetails(String studentName, String studentRollNo) {
System.out.println("Student:");
System.out.println("Name: " + studentName);
System.out.println("Roll No: " + studentRollNo);
}
}

class StudentController {
private Student model;
private StudentView view;

public StudentController(Student model, StudentView view) {


this.model = model;
this.view = view;
}

public void setStudentName(String name) {


model.setName(name);
}

public String getStudentName() {


return model.getName();
}

public void setStudentRollNo(String rollNo) {


model.setRollNo(rollNo);
}

public String getStudentRollNo() {


return model.getRollNo();
}

public void updateView() {


view.printStudentDetails(model.getName(), model.getRollNo());
}
}

public class MVCPattern {


public static void main(String[] args) {
Student model = retriveStudentFromDatabase();

StudentView view = new StudentView();

StudentController controller = new StudentController(model, view);

controller.updateView();

controller.setStudentName("Science");

controller.updateView();
}
private static Student retriveStudentFromDatabase() {
Student student = new Student();
student.setName("Computer");
student.setRollNo("15UCS157");
return student;
}
}

Output :
Student:
Name:Computer
Roll No: 000001
Student:
Name: Science
Roll No: 000001

Containers: AWT provides containers like panels, frames, and dialogues to organize and group components in the Application.
Types of Containers in Java AWT
There are four types of containers in Java AWT:

Window: Window is a top-level container that represents a graphical window or dialog box. The Window class extends the
Container class, which means it can contain other components, such as buttons, labels, and text fields.
Panel: Panel is a container class in Java. It is a lightweight container that can be used for grouping other components
together within a window or a frame.
Frame: The Frame is the container that contains the title bar and border and can have menu bars.
Dialog: A dialog box is a temporary window an application creates to retrieve user input.

FlowLayout
FlowLayout is used to arrange components in a sequence one after the other. The default layout of applet and panel is FlowLayout.

Constructors :

FlowLayout(): It will Construct a new FlowLayout with centered alignment.The horizontal and vertical gap will be 5 pixels.
FlowLayout(int align) : It will Construct a new FlowLayout with given alignment.The horizontal and vertical gap will be 5
pixels.
FlowLayout(int align, int HorizontalGap, int VerticalGap ): It will Construct a new FlowLayout with given alignment, the
given horizontal and vertical gap between the components.
JLabel(String text): It will create a JLabel instance with the specified text.

Commonly used methods:

setTitle(String Text): This Method is used to set Title of JFrame. The title you want to set is passed as a string.
getAlignment(): Returns the alignment for this layout.
setAlignment(int align): used to set the alignment for this layout.
removeLayoutComponent(Component comp): Used to remove the component passed as argument from the layout.
Below programs will illustrate the Example of FlowLayout in java.

Program 1: The following program illustrates the use of FlowLayout by arranging several JLabel components in a JFrame, whose
instance class is named as “Example”. We create 5 JLabel components named “l1”, “l2″… “l5” and then add them to the JFrame by
the method this.add(). We set the title and bounds of the frame by method setTitle and setBounds.
The layout is set by the method setLayout();

// Java program to show Example of FlowLayout.


// in java. Importing different Package.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class Example extends JFrame {


// Declaration of objects of JLabel class.
JLabel l1, l2, l3, l4, l5;
// Constructor of Example class.
public Example()
{
// Creating Object of "FlowLayout" class
FlowLayout layout = new FlowLayout();

// this Keyword refers to current object.


// Function to set Layout of JFrame.
this.setLayout(layout);

// Initialization of object "l1" of JLabel class.


l1 = new JLabel("Label 1 ");

// Initialization of object "l2" of JLabel class.


l2 = new JLabel("Label 2 ");

// Initialization of object "l3" of JLabel class.


l3 = new JLabel("Label 3 ");

// Initialization of object "l4" of JLabel class.


l4 = new JLabel("Label 4 ");

// Initialization of object "l5" of JLabel class.


l5 = new JLabel("Label 5 ");

// this Keyword refers to current object.


// Adding Jlabel "l1" on JFrame.
this.add(l1);

// Adding Jlabel "l2" on JFrame.


this.add(l2);

// Adding Jlabel "l3" on JFrame.


this.add(l3);

// Adding Jlabel "l4" on JFrame.


this.add(l4);

// Adding Jlabel "l5" on JFrame.


this.add(l5);
}
}

class MainFrame {
// Driver code
public static void main(String[] args)
{
// Creating Object of Example class.
Example f = new Example();

// Function to set title of JFrame.


f.setTitle("Example of FlowLayout");

// Function to set Bounds of JFrame.


f.setBounds(200, 100, 600, 400);

// Function to set visible status of JFrame.


f.setVisible(true);
}
}

Border Layout :
BorderLayout is the default layout for the window objects such as JFrame, JWindow, JDialog, JInternalFrame etc.
BorderLayout arranges the components in the five regions. Four sides are referred to as north, south, east, and west. The middle
part is called the center. Each region can contain only one component and is identified by a corresponding constant as NORTH,
SOUTH, EAST, WEST, and CENTER.

Constructors:

BorderLayout(): It will construct a new borderlayout with no gaps between the components.
BorderLayout(int, int): It will constructs a border layout with the specified gaps between the components.
Commonly Used Methods:

toString(): Returns a string which is the representation of the state of border layout.
getLayoutAlignmentX(Container parent): Returns the layout alignment along the X-axis.
getLayoutAlignmentY(Container parent): It will return the layout alignment along the Y-axis.
removeLayoutComponent(Component comp): This method is used to remove the specified component from the
borderlayout.
getVgap(): Return the vertical gap between the components.
getHgap(): Returns the Horizontal gap between the components.
setHgap(int hgap): It is used to set the horizontal gap between the components.
setVgap(int vgap): It is used to set the vertical gap between the components.
Below Programs will illustrate the BorderLayout class:

// Java program to illustrate the BorderLayout


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

// class extends JFrame


class BoderLayoutDemo extends JFrame {

BoderLayoutDemo()
{

// Creating Object of Jpanel class


JPanel pa = new JPanel();

// set the layout


pa.setLayout(new BorderLayout());

// add a new JButton with name "wel" and it is


// lie top of the container
pa.add(new JButton("WelCome"), BorderLayout.NORTH);

// add a new JButton with name "come" and it is


// lie button of the container
pa.add(new JButton("Geeks"), BorderLayout.SOUTH);

// add a new JButton with name "Layout" and it is


// lie left of the container
pa.add(new JButton("Layout"), BorderLayout.EAST);

// add a new JButton with name "Border" and it is


// lie right of the container
pa.add(new JButton("Border"), BorderLayout.WEST);

// add a new JButton with name "hello everybody" and it is


// lie center of the container
pa.add(new JButton("GeeksforGeeks"), BorderLayout.CENTER);

// add the pa object which refer to the Jpanel


add(pa);

// Function to close the operation of JFrame.


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Function to set size of JFrame.


setSize(300, 300);

// Function to set visible status of JFrame.


setVisible(true);
}
}

class MainFrame {

// Driver code
public static void main(String[] args)
{

// calling the constructor


new BoderLayoutDemo();
}
}

Grid Layout :
GridLayout class represents a layout manager with a specified number of rows and columns in a rectangular grid. The
GridLayout container is divided into an equal-sized of rectangles, and one of the components is placed in each rectangle. Every
rectangle cell has the same size therefore, they contain a component, which fills the entire cell. When the user changes or adjusts
the size of the container, the size of each rectangles changes accordingly.

Constructors of the class:

GridLayout(): It Creates a grid layout with a default of one column per component, in a single row.
GridLayout(int rw, int cl): It creates a grid layout with the specified number of rows and columns.
GridLayout(int rw, int cl, int hgap, int vgap): It creates a grid layout with the specified number of rows and columns with
horizontal and vertical gap.
Commonly Used Methods:

addLayoutComponent(String str, Component cmp): Adds the specified component with the specified name to the layout.
setColumns(int cl): Sets the number of columns in this layout to the specified value.
setHgap(int hgap): Sets the horizontal gap between components to the specified value.
setRows(int rw): Sets the number of rows in this layout to the specified value.
setVgap(int vgap): Sets the vertical gap between components to the specified value.
layoutContainer(Container pr): Lays out the specified container using this layout.
toString(): Returns the string representation of this grid layout’s values.
Below programs illustrate the GridLayout class:

// Java program to illustrate the GridLayout


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

// class GridLayout extends JFrame


public class GridLayoutDemo extends JFrame {

GridLayoutDemo() {

// Creating Object P1 of JPanel class


JPanel p1 = new JPanel();

// set the layout


p1.setLayout(new GridLayout(4, 2));

// Creating Object of "FlowLayout" class


FlowLayout layout = new FlowLayout();

// Creating Object P2 of JPanel class


JPanel p2 = new JPanel();

// set the layout


p2.setLayout(layout);

// Declaration of objects of JLabel class.


JLabel one, two, three, four;

// Declaration of objects of JTextField class.


JTextField tname, tsalary, tcode, tdesig;

// Declaration of objects of JButton class.


JButton buttonSave, buttonExit;

// Initialization of object
// "one" of JLabel class.
one = new JLabel("NAME");

// Initialization of object
// "tname" of JTextField class.
tname = new JTextField(20);
// Initialization of object
// "two" of JLabel class.
two = new JLabel("CODE");

// Initialization of object
// "tcode" of JTextField class.
tcode = new JTextField(20);

// Initialization of object
// "three" of JLabel class.
three = new JLabel("DESIGNATION");

// Initialization of object
// "tdesig" of JTextField class.
tdesig = new JTextField(20);

// Initialization of object
// "four" of JLabel class.
four = new JLabel("SALARY");

// Initialization of object
// "tsalary" of JTextField class.
tsalary = new JTextField(20);

// Initialization of object
// "buttonsave" of JButton class.
buttonSave = new JButton("SAVE");

// Initialization of object
// "buttonexit" of JButton class.
buttonExit = new JButton("EXIT");

// Adding Jlabel "one" on JFrame.


p1.add(one);

// Adding JTextField "tname" on JFrame.


p1.add(tname);

// Adding Jlabel "two" on JFrame.


p1.add(two);

// Adding JTextField "tcode" on JFrame.


p1.add(tcode);

// Adding Jlabel "three" on JFrame.


p1.add(three);

// Adding JTextField "tdesig" on JFrame.


p1.add(tdesig);

// Adding Jlabel "four" on JFrame.


p1.add(four);

// Adding JTextField "tsalary" on JFrame.


p1.add(tsalary);

// Adding JButton "buttonsave" on JFrame.


p2.add(buttonSave);

// Adding JButton "buttonexit" on JFrame.


p2.add(buttonExit);

// add the p1 object which


// refer to the Jpanel
add(p1, "North");

// add the p2 object which


// refer to the Jpanel
add(p2, "South");

// Function to set visible


// status of JFrame.
setVisible(true);
// this Keyword refers to current
// object. Function to set size of JFrame.
this.setSize(400, 180);
}

// Main Method
public static void main(String args[])
{

// calling the constructor


new GridLayoutDemo();
}
}

Card Layout :
The CardLayout class manages the components in such a way that only one component is visible at a time. It treats each
component as a card in the container. Only one card is visible at a time, and the container acts as a stack of cards. The first
component added to a CardLayout object is the visible component when the container is first displayed.

Constructors:

CardLayout(): It is used to create a new card layout with gaps of size is zero.
CardLayout(int horizontalgap, int verticalgap): It is used to create a new CardLayout class with the specified
horizontal and vertical gaps.
Commonly Used Methods:

getLayoutAlignmentX(Container parent): Returns the alignment along the x-axis.


getLayoutAlignmentY(Container parent): Returns the alignment along the y-axis.
getVgap(): Used to get the vertical gap between components.
addLayoutComponent(Component cm, Object cn): Used to add the specified component to this card layout’s internal table
of names.
getHgap(): Used to get the horizontal gap between components.
toString(): Returns a string representation of the state of this card layout.
removeLayoutComponent(Component cm): Used to remove the specified component from the layout.
Below programs illustrate the CardLayout class:

// Java program to show Example of CardLayout.


// in java. Importing different Package.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

// class extends JFrame


public class CardLayoutDemo extends JFrame {

// Initialization the value of


// current card is 1 .
private int currentCard = 1;

// Declaration of objects
// of CardLayout class.
private CardLayout cl;

public CardLayoutDemo()
{

// Function to set visibility of JFrame


setTitle("Card Layout Example");

// Function to set visibility of JFrame


setSize(300, 150);

// Creating Object of "Jpanel" class


JPanel cardPanel = new JPanel();

// Initialization of object "c1"


// of CardLayout class.
cl = new CardLayout();

// set the layout


cardPanel.setLayout(cl);

// Initialization of object
// "jp1" of JPanel class.
JPanel jp1 = new JPanel();

// Initialization of object
// "jp2" of CardLayout class.
JPanel jp2 = new JPanel();

// Initialization of object
// "jp3" of CardLayout class.
JPanel jp3 = new JPanel();

// Initialization of object
// "jp4" of CardLayout class.
JPanel jp4 = new JPanel();

// Initialization of object
// "jl1" of JLabel class.
JLabel jl1 = new JLabel("Card1");

// Initialization of object
// "jl2" of JLabel class.
JLabel jl2 = new JLabel("Card2");

// Initialization of object
// "jl3" of JLabel class.
JLabel jl3 = new JLabel("Card3");

// Initialization of object
// "jl4" of JLabel class.
JLabel jl4 = new JLabel("Card4");

// Adding JPanel "jp1" on JFrame.


jp1.add(jl1);

// Adding JPanel "jp2" on JFrame.


jp2.add(jl2);

// Adding JPanel "jp3" on JFrame.


jp3.add(jl3);

// Adding JPanel "jp4" on JFrame.


jp4.add(jl4);

// Adding the cardPanel on "jp1"


cardPanel.add(jp1, "1");

// Adding the cardPanel on "jp2"


cardPanel.add(jp2, "2");

// Adding the cardPanel on "jp3"


cardPanel.add(jp3, "3");

// Adding the cardPanel on "jp4"


cardPanel.add(jp4, "4");

// Creating Object of "JPanel" class


JPanel buttonPanel = new JPanel();

// Initialization of object
// "firstbtn" of JButton class.
JButton firstBtn = new JButton("First");

// Initialization of object
// "nextbtn" of JButton class.
JButton nextBtn = new JButton("Next");

// Initialization of object
// "previousbtn" of JButton class.
JButton previousBtn = new JButton("Previous");

// Initialization of object
// "lastbtn" of JButton class.
JButton lastBtn = new JButton("Last");

// Adding JButton "firstbtn" on JFrame.


buttonPanel.add(firstBtn);

// Adding JButton "nextbtn" on JFrame.


buttonPanel.add(nextBtn);

// Adding JButton "previousbtn" on JFrame.


buttonPanel.add(previousBtn);

// Adding JButton "lastbtn" on JFrame.


buttonPanel.add(lastBtn);

// add firstbtn in ActionListener


firstBtn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{

// used first c1 CardLayout


cl.first(cardPanel);

// value of currentcard is 1
currentCard = 1;
}
});

// add lastbtn in ActionListener


lastBtn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{

// used last c1 CardLayout


cl.last(cardPanel);

// value of currentcard is 4
currentCard = 4;
}
});

// add nextbtn in ActionListener


nextBtn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{

// if condition apply
if (currentCard < 4)
{

// increment the value of currentcard by 1


currentCard += 1;

// show the value of currentcard


cl.show(cardPanel, "" + (currentCard));
}
}
});

// add previousbtn in ActionListener


previousBtn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
// if condition apply
if (currentCard > 1) {
// decrement the value
// of currentcard by 1
currentCard -= 1;

// show the value of currentcard


cl.show(cardPanel, "" + (currentCard));
}
}
});

// used to get content pane


getContentPane().add(cardPanel, BorderLayout.NORTH);

// used to get content pane


getContentPane().add(buttonPanel, BorderLayout.SOUTH);
}

// Main Method
public static void main(String[] args)
{

// Creating Object of CardLayoutDemo class.


CardLayoutDemo cl = new CardLayoutDemo();

// Function to set default operation of JFrame.


cl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Function to set visibility of JFrame.


cl.setVisible(true);
}
}

GridBagLayout :
GridBagLayout class is a flexible layout manager. It is used to aligns the components horizontally, vertically, or along their
baseline. It doesn’t require the components of the same size. Each GridBagLayout object manages a rectangular grid of cells,
dynamic with each component occupying one or more cells, called its display area. GridBagLayout components are associated with
the instance of GridBagConstraints. These constraints are used to define the component’s display area and their positions. In
addition to its constraints object, the GridBagLayout also considers each component’s minimum and preferred sizes in order to
determine a component’s size. GridBagLayout components are also arranged in the rectangular grid but can have different sizes
and can occupy the multiple rows or columns.

Constructor:

GridBagLayout(): It is used to creates a grid bag layout manager.


Commonly Used Methods:

removeLayoutComponent(Component cmp): Removes the specified component from this layout.


getLayoutAlignmentY(Container p): Returns the alignment along the y-axis.
addLayoutComponent(Component cmp, Object cons): Add the specified component with the specified name to the layout.
toString(): Returns a string representation of this grid bag layout’s values.
getLayoutAlignmentX(Container p): Returns the alignment along the x-axis.
getConstraints(Component cmp): Gets the constraints for the specified component.
maximumLayoutSize(Container tar): Returns the maximum dimensions for this layout given the components in the
specified target container.
minimumLayoutSize(Container par): Determines the minimum size of the parent container using this grid bag layout.
Below programs illustrate the GridBagLayout class:

// Java program to demonstrate GridBagLayout class.


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

// Constructor of GridBagLayout class.


public class GridBagLayoutDemo {

final static boolean shouldFill = true;


final static boolean shouldWeightX = true;
final static boolean RIGHT_TO_LEFT = false;

public static void addComponentsToPane(Container pane)


{

// if condition
if (RIGHT_TO_LEFT) {

pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
}

// Declaration of objects of JButton class


JButton button;

// set the layout


pane.setLayout(new GridBagLayout());

// creates a constraints object


GridBagConstraints c = new GridBagConstraints();

// if condition
if (shouldFill) {

// natural height, maximum width


c.fill = GridBagConstraints.HORIZONTAL;
}

// Initialization of object
// "button" of JButton class.
button = new JButton("Button 1");

// if condition
if (shouldWeightX) {
c.weightx = 0.5;
}

// column 0
c.gridx = 0;

// row 0
c.gridy = 0;

// Adding JButton "button" on JFrame.


pane.add(button, c);

// Initialization of object
// "button" of JButton class.
button = new JButton("Button 2");

// column 1
c.gridx = 1;

// row 0
c.gridy = 0;

// Adding JButton "button" on JFrame.


pane.add(button, c);

// Initialization of object
// "button" of JButton class.
button = new JButton("Button 3");

// column 1
c.gridx = 2;

// row 0
c.gridy = 0;

// Adding JButton "button" on JFrame.


pane.add(button, c);

// Initialization of object
// "button" of JButton class.
button = new JButton("Long-Named Button 4");

// increases components height by 40 pixels


c.ipady = 40;

// column width 0
c.weightx = 0.0;

// row width 3
c.gridwidth = 3;

// column 1
c.gridx = 0;

// row 1
c.gridy = 1;

// Adding JButton "button" on JFrame.


pane.add(button, c);

// Initialization of object
// "button" of JButton class.
button = new JButton("Button 5");

// increases components height by 0 pixels


c.ipady = 0;

// request any extra vertical space


c.weighty = 1.0;

// bottom of space
c.anchor = GridBagConstraints.PAGE_END;

// top padding
c.insets = new Insets(10, 0, 0, 0);

// column 2
c.gridx = 1;

// 2 columns wide
c.gridwidth = 2;

// row 3
c.gridy = 2;

// Adding JButton "button" on JFrame.


pane.add(button, c);
}

// Create the GUI and show it. For thread safety,


// this method should be invoked from the
// event-dispatching thread.
private static void createAndShowGUI()
{

// to set a Jframe default


JFrame.setDefaultLookAndFeelDecorated(true);

// Create and set up the window.


JFrame frame = new JFrame("GridBagLayoutDemo");

// Function to close the operation of JFrame.


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// adding the content pane.


addComponentsToPane(frame.getContentPane());

// Display the window.


frame.pack();

// Function to set visible status of JFrame.


frame.setVisible(true);
}

// Main Method
public static void main(String[] args)
{

// Schedule a job for the event-dispatching thread:


// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {

public void run()


{
createAndShowGUI();
}
});
}
}

Event Handling in Java - The Delegation event model- Events, Event sources, Event
Listeners, Event classes :
An event can be defined as changing the state of an object or behavior by performing actions. Actions can be a button
click, cursor movement, keypress through keyboard or page scrolling, etc.

The java.awt.event package can be used to provide various event classes.

Classification of Events
Foreground Events
Background Events

1. Foreground Events
Foreground events are the events that require user interaction to generate, i.e., foreground events are generated due to
interaction by the user on components in Graphic User Interface (GUI). Interactions are nothing but clicking on a button, scrolling
the scroll bar, cursor moments, etc.

2. Background Events
Events that don’t require interactions of users to generate are known as background events. Examples of these events are
operating system failures/interrupts, operation completion, etc.

Event Handling
It is a mechanism to control the events and to decide what should happen after an event occur. To handle the events, Java
follows the Delegation Event model.

Delegation Event model


It has Sources and Listeners.
Source: Events are generated from the source. There are various sources like buttons, checkboxes, list, menu-item,
choice, scrollbar, text components, windows, etc., to generate events.
Listeners: Listeners are used for handling the events generated from the source. Each of these listeners represents
interfaces that are responsible for handling events.
To perform Event Handling, we need to register the source with the listener.

Registering the Source With Listener


Different Classes provide different registration methods.

Syntax:
addTypeListener()
where Type represents the type of event.

Example 1: For KeyEvent we use addKeyListener() to register.


Example 2:that For ActionEvent we use addActionListener() to register.

Event Classes in Java

Event Class Listener Interface Description

An event that indicates that a component-defined action occurred like a button click
ActionEvent ActionListener
or selecting an item from the menu-item list.

AdjustmentEvent AdjustmentListener The adjustment event is emitted by an Adjustable object like Scrollbar.

An event that indicates that a component moved, the size changed or changed its
ComponentEvent ComponentListener
visibility.

When a component is added to a container (or) removed from it, then this event is
ContainerEvent ContainerListener
generated by a container object.

FocusEvent FocusListener These are focus-related events, which include focus, focusin, focusout, and blur.

ItemEvent ItemListener An event that indicates whether an item was selected or not.

KeyEvent KeyListener An event that occurs due to a sequence of keypresses on the keyboard.

MouseListener &
MouseEvent The events that occur due to the user interaction with the mouse (Pointing Device).
MouseMotionListener

MouseWheelEvent MouseWheelListener An event that specifies that the mouse wheel was rotated in a component.
TextEvent TextListener An event that occurs when an object’s text changes.

WindowEvent WindowListener An event which indicates whether a window has changed its status or not.

Note: As Interfaces contains abstract methods which need to implemented by the registered class to handle events.

Different interfaces consists of different methods which are specified below.

Listener Interface Methods

ActionListener ● actionPerformed()

AdjustmentListener ● adjustmentValueChanged()

● componentResized()
● componentShown()
ComponentListener
● componentMoved()
● componentHidden()

● componentAdded()
ContainerListener
● componentRemoved()

● focusGained()
FocusListener
● focusLost()

ItemListener ● itemStateChanged()

● keyTyped()
KeyListener ● keyPressed()
● keyReleased()

● mousePressed()
● mouseClicked()
MouseListener ● mouseEntered()
● mouseExited()
● mouseReleased()

● mouseMoved()
MouseMotionListener
● mouseDragged()

MouseWheelListener ● mouseWheelMoved()

TextListener ● textChanged()

● windowActivated()
● windowDeactivated()
● windowOpened()
WindowListener ● windowClosed()
● windowClosing()
● windowIconified()
● windowDeiconified()

Flow of Event Handling


User Interaction with a component is required to generate an event.
The object of the respective event class is created automatically after event generation, and it holds all information of the event
source.
The newly created object is passed to the methods of the registered listener.
The method executes and returns the result.
Code-Approaches
The three approaches for performing event handling are by placing the event handling code in one of the below-specified places.

Within Class
Other Class
Anonymous Class

Note: Use any IDE or install JDK to run the code, Online compiler may throw errors due to the unavailability of some packages.

Event Handling Within Class

// Java program to demonstrate the


// event handling within the class

import java.awt.*;
import java.awt.event.*;

class GFGTop extends Frame implements ActionListener {

TextField textField;

GFGTop()
{
// Component Creation
textField = new TextField();

// setBounds method is used to provide


// position and size of the component
textField.setBounds(60, 50, 180, 25);
Button button = new Button("click Here");
button.setBounds(100, 120, 80, 30);

// Registering component with listener


// this refers to current instance
button.addActionListener(this);

// add Components
add(textField);
add(button);

// set visibility
setVisible(true);
}

// implementing method of actionListener


public void actionPerformed(ActionEvent e)
{
// Setting text to field
textField.setText("GFG!");
}

public static void main(String[] args)


{
new GFGTop();
}
}
Explanation
Firstly extend the class with the applet and implement the respective listener.
Create Text-Field and Button components.
Registered the button component with respective event. i.e. ActionEvent by addActionListener().
In the end, implement the abstract method.
Event Handling by Other Class

// Java program to demonstrate the


// event handling by the other class
import java.awt.*;
import java.awt.event.*;

class GFG1 extends Frame {

TextField textField;

GFG2()
{
// Component Creation
textField = new TextField();

// setBounds method is used to provide


// position and size of component
textField.setBounds(60, 50, 180, 25);
Button button = new Button("click Here");
button.setBounds(100, 120, 80, 30);

Other other = new Other(this);

// Registering component with listener


// Passing other class as reference
button.addActionListener(other);

// add Components
add(textField);
add(button);

// set visibility
setVisible(true);
}

public static void main(String[] args)


{
new GFG2();
}
}

/// import necessary packages


import java.awt.event.*;

// implements the listener interface


class Other implements ActionListener {

GFG2 gfgObj;

Other(GFG1 gfgObj) {
this.gfgObj = gfgObj;
}

public void actionPerformed(ActionEvent e)


{
// setting text from different class
gfgObj.textField.setText("Using Different Classes");
}
}
Event Handling By Anonymous Class

// Java program to demonstrate the


// event handling by the anonymous class

import java.awt.*;
import java.awt.event.*;

class GFG3 extends Frame {

TextField textField;

GFG3()
{
// Component Creation
textField = new TextField();

// setBounds method is used to provide


// position and size of component
textField.setBounds(60, 50, 180, 25);
Button button = new Button("click Here");
button.setBounds(100, 120, 80, 30);

// Registering component with listener anonymously


button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
// Setting text to field
textField.setText("Anonymous");
}
});

// add Components
add(textField);
add(button);

//make size viewable


setSize(300,300);
// set visibility
setVisible(true);
}

public static void main(String[] args)


{
new GFG3();
}
}
Handling Mouse and Keyboard Events :
MouseListener and MouseMotionListener is an interface in java.awt.event package . Mouse events
are of two types.
MouseListener handles the events when the mouse is not in motion. While MouseMotionListener
handles the events when mouse is in motion.
There are five types of events that MouseListener can generate. There are five abstract functions that represent these five events.

The abstract functions are :

void mouseReleased(MouseEvent e) : Mouse key is released


void mouseClicked(MouseEvent e) : Mouse key is pressed/released
void mouseExited(MouseEvent e) : Mouse exited the component
void mouseEntered(MouseEvent e) : Mouse entered the component
void mousepressed(MouseEvent e) : Mouse key is pressed

There are two types of events that MouseMotionListener can generate. There are two abstract functions that represent these two
events. The abstract functions are :

void mouseDragged(MouseEvent e) : Invoked when a mouse button is pressed in the component and dragged. Events
are passed until the user releases the mouse button.
void mouseMoved(MouseEvent e) : invoked when the mouse cursor is moved from one point to another within the
component, without pressing any mouse buttons.

The following programs are a illustration of MouseListener and MouseMotionListener.


1. Program to handle MouseListener events

// Java program to handle MouseListener events


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Mouse extends Frame implements MouseListener {

// Jlabels to display the actions of events of mouseListener


// static JLabel label1, label2, label3;

// default constructor
Mouse()
{
}

// main class
public static void main(String[] args)
{
// create a frame
JFrame f = new JFrame("MouseListener");

// set the size of the frame


f.setSize(600, 100);

// close the frame when close button is pressed


f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// create a new panel


JPanel p = new JPanel();

// set the layout of the panel


p.setLayout(new FlowLayout());

// initialize the labels


label1 = new JLabel("no event ");

label2 = new JLabel("no event ");

label3 = new JLabel("no event ");

// create an object of mouse class


Mouse m = new Mouse();

// add mouseListener to the frame


f.addMouseListener(m);

// add labels to the panel


p.add(label1);
p.add(label2);
p.add(label3);

// add panel to the frame


f.add(p);

f.show();
}

// getX() and getY() functions return the


// x and y coordinates of the current
// mouse position
// getClickCount() returns the number of
// quick consecutive clicks made by the user

// this function is invoked when the mouse is pressed


public void mousePressed(MouseEvent e)
{

// show the point where the user pressed the mouse


label1.setText("mouse pressed at point:"+ e.getX() + " " + e.getY());
}

// this function is invoked when the mouse is released


public void mouseReleased(MouseEvent e)
{

// show the point where the user released the mouse click
label1.setText("mouse released at point:"+ e.getX() + " " + e.getY());
}

// this function is invoked when the mouse exits the component


public void mouseExited(MouseEvent e)
{

// show the point through which the mouse exited the frame
label2.setText("mouse exited through point:"+ e.getX() + " " + e.getY());
}

// this function is invoked when the mouse enters the component


public void mouseEntered(MouseEvent e)
{

// show the point through which the mouse entered the frame
label2.setText("mouse entered at point:"+ e.getX() + " " + e.getY());
}

// this function is invoked when the mouse is pressed or released


public void mouseClicked(MouseEvent e)
{

// getClickCount gives the number of quick,


// consecutive clicks made by the user
// show the point where the mouse is i.e
// the x and y coordinates
label3.setText("mouse clicked at point:" + e.getX() + " "+ e.getY() + "mouse clicked :" + e.getClickCount());
}
}

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MouseEventHandler extends JFrame implements MouseListener, MouseMotionListener {
public MouseEventHandler() {
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked at (" + e.getX() + "," + e.getY() + ")");
}
public void mousePressed(MouseEvent e) {
System.out.println("Mouse pressed at (" + e.getX() + "," + e.getY() + ")");
}
public void mouseReleased(MouseEvent e) {
System.out.println("Mouse released at (" + e.getX() + "," + e.getY() + ")");
}
public void mouseEntered(MouseEvent e) {
System.out.println("Mouse entered at (" + e.getX() + "," + e.getY() + ")");
}
public void mouseExited(MouseEvent e) {
System.out.println("Mouse exited at (" + e.getX() + "," + e.getY() + ")");
}
public void mouseDragged(MouseEvent e) {
System.out.println("Mouse dragged at (" + e.getX() + "," + e.getY() + ")");
}
public void mouseMoved(MouseEvent e) {
System.out.println("Mouse moved at (" + e.getX() + "," + e.getY() + ")");
}
public static void main(String[] args) {
MouseEventHandler frame = new MouseEventHandler();
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Output :
Mouse entered at (277,285)
Mouse moved at (277,285)
Mouse moved at (275,278)
Mouse moved at (273,272)
Mouse moved at (273,268)
Mouse moved at (273,265)
Mouse moved at (273,263)
Mouse moved at (274,263)
Mouse moved at (279,266)
Mouse moved at (289,273)
Mouse exited at (427,402)

KeyBoard Events :
The Java KeyListener in the Abstract Window Toolkit (AWT) is a fundamental tool for achieving this. The KeyListener
Interface is found in “java.awt.event” package. In this article, we’ll explore what the KeyListener is, and its declaration methods, and
supply examples with explanatory comments.

Java KeyListener in AWT


The KeyListener port in Java AWT is quite used to listen for keyboard events, such as key presses and key releases. It
allows your program to respond to user input from the keyboard, which is crucial for building interactive applications.

Declaring KeyListener
public interface KeyListener extends EventListener
Methods of Java KeyListener in AWT
The KeyListener port defines three methods that you must implement:

Method Description

keyPressed(KeyEvent e) Invoked when a key is pressed down.

keyReleased(KeyEvent e) Called when a key is released.

keyTyped(KeyEvent e) Fired when a key press/release results in a character.

Example 1:
Below is the implementation of the Java KeyListener:

// Java program to demonstrate textfield and


// display typed text using KeyListener
import java.awt.*;
import java.awt.event.*;

public class KeyListenerExample extends Frame implements KeyListener {

private TextField textField;


private Label displayLabel;

// Constructor
public KeyListenerExample() {
// Set frame properties
setTitle("Typed Text Display");
setSize(400, 200);
setLayout(new FlowLayout());

// Create and add a TextField for text input


textField = new TextField(20);
textField.addKeyListener(this);
add(textField);

// Create and add a Label to display typed text


displayLabel = new Label("Typed Text: ");
add(displayLabel);

// Ensure the frame can receive key events


setFocusable(true);
setFocusTraversalKeysEnabled(false);

// Make the frame visible


setVisible(true);
}

// Implement the keyPressed method


@Override
public void keyPressed(KeyEvent e) {
// You can add custom logic here if needed
}

// Implement the keyReleased method


@Override
public void keyReleased(KeyEvent e) {
// You can add custom logic here if needed
}

// Implement the keyTyped method


@Override
public void keyTyped(KeyEvent e) {
char keyChar = e.getKeyChar();
displayLabel.setText("Typed Text: " + textField.getText() + keyChar);
}

public static void main(String[] args) {


new KeyListenerExample();
}
}

//Java program to demonstrate keyPressed,


// keyReleased and keyTyped method
import java.awt.*;
import java.awt.event.*;

public class KeyListenerExample extends Frame implements KeyListener {

private TextField textField;


private Label displayLabel;

// Constructor
public KeyListenerExample() {
// Set frame properties
setTitle("Typed Text Display");
setSize(400, 200);
setLayout(new FlowLayout());

// Create and add a TextField for text input


textField = new TextField(20);
textField.addKeyListener(this);
add(textField);

// Create and add a Label to display typed text


displayLabel = new Label("Typed Text: ");
add(displayLabel);

// Ensure the frame can receive key events


setFocusable(true);
setFocusTraversalKeysEnabled(false);

// Make the frame visible


setVisible(true);
}

// Implement the keyPressed method


@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
System.out.println("Key Pressed: " + KeyEvent.getKeyText(keyCode));
}

// Implement the keyReleased method


@Override
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
System.out.println("Key Released: " + KeyEvent.getKeyText(keyCode));
}

// Implement the keyTyped method


@Override
public void keyTyped(KeyEvent e) {
char keyChar = e.getKeyChar();
System.out.println("Key Typed: " + keyChar);
displayLabel.setText("Typed Text: " + textField.getText() + keyChar);
}

public static void main(String[] args) {


new KeyListenerExample();
}
}
—--------------------------------------------------------------------

You might also like