0% found this document useful (0 votes)
112 views227 pages

JAVA All Merged

The document discusses key features of the Java programming language such as being object-oriented, platform independent, simple, secure, and portable. It also discusses applications of Java like for enterprise applications and mobile applications. The document provides an example of a simple Java program to print "Hello World" and explains how to save, compile, and run a Java program. It covers basic Java syntax, identifiers, variables, and the Java Virtual Machine.

Uploaded by

Kioni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
112 views227 pages

JAVA All Merged

The document discusses key features of the Java programming language such as being object-oriented, platform independent, simple, secure, and portable. It also discusses applications of Java like for enterprise applications and mobile applications. The document provides an example of a simple Java program to print "Hello World" and explains how to save, compile, and run a Java program. It covers basic Java syntax, identifiers, variables, and the Java Virtual Machine.

Uploaded by

Kioni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 227

‘JAVA Programming’ By: Mrs. R.

Mallick, Lecturer, CSA,CET 1


5th Sem. Integrated Math & Computing

Features of JAVA
 Object Oriented − In Java, everything is an Object. Java can be easily extended
since it is based on the Object model.

 Platform Independent − Unlike many other programming languages including


C and C++, when Java is compiled, it is not compiled into platform specific
machine, rather into platform independent byte code. This byte code is
distributed over the web and interpreted by the Virtual Machine (JVM) on
whichever platform it is being run on.

 Simple − Java is designed to be easy to learn. If you understand the basic


concept of OOP Java, it would be easy to master.

 Secure − With Java's secure feature it enables to develop virus-free, tamper-free


systems. Authentication techniques are based on public-key encryption.

 Architecture-neutral − Java compiler generates an architecture-neutral object file


format, which makes the compiled code executable on many processors, with
the presence of Java runtime system.

 Portable − Being architecture-neutral and having no implementation dependent


aspects of the specification makes Java portable. Compiler in Java is written in
ANSI C with a clean portability boundary, which is a POSIX subset.

 Robust − Java makes an effort to eliminate error prone situations by


emphasizing mainly on compile time error checking and runtime checking.

Applications of Java Programming

The latest release of the Java Standard Edition is Java SE 8. With the advancement of
Java and its widespread popularity, multiple configurations were built to suit various
types of platforms. For example: J2EE for Enterprise Applications, J2ME for Mobile
Applications.
‘JAVA Programming’ By: Mrs. R.Mallick, Lecturer, CSA,CET 2
5th Sem. Integrated Math & Computing

The new J2 versions were renamed as Java SE, Java EE, and Java ME respectively. Java
is guaranteed to be Write Once, Run Anywhere.

 Multithreaded − With Java's multithreaded feature it is possible to write

programs that can perform many tasks simultaneously. This design feature
allows the developers to construct interactive applications that can run
smoothly.

 Interpreted − Java byte code is translated on the fly to native machine

instructions and is not stored anywhere. The development process is more rapid
and analytical since the linking is an incremental and light-weight process.

 High Performance − With the use of Just-In-Time compilers, Java enables high

performance.

 Distributed − Java is designed for the distributed environment of the internet.

 Dynamic − Java is considered to be more dynamic than C or C++ since it is

designed to adapt to an evolving environment. Java programs can carry


extensive amount of run-time information that can be used to verify and resolve
accesses to objects on run-time.

First Java Program

Let us look at a simple code that will print the words Hello World.

Example

public class MyFirstJavaProgram {

public static void main(String [ ]args) {


System.out.println("Hello World"); // prints Hello World
}
}
how to save the file, compile, and run the program.
‘JAVA Programming’ By: Mrs. R.Mallick, Lecturer, CSA,CET 3
5th Sem. Integrated Math & Computing

Open notepad and add the code as above.

Save the file as: MyFirstJavaProgram.java.

Open a command prompt window and go to the directory where you saved the
class. Assume it's C:\.

Type 'javac MyFirstJavaProgram.java and press enter to compile your code. If


there are no errors in your code, the command prompt will take you to the next
line (Assumption : The path variable is set).

Now, type ' java MyFirstJavaProgram ' to run your program.

You will be able to see ' Hello World ' printed on the window.

Output

C:\> javac MyFirstJavaProgram.java


C:\> java MyFirstJavaProgram
Hello World

Basic Syntax

About Java programs, it is very important to keep in mind the following points.

Case Sensitivity − Java is case sensitive, which means


identifier Hello and hello would have different meaning in Java.

Class Names − For all class names the first letter should be in Upper Case. If
several words are used to form a name of the class, each inner word's first letter
should be in Upper Case.

Example: class MyFirstJavaClass

Method Names − All method names should start with a Lower Case letter. If
several words are used to form the name of the method, then each inner word's
first letter should be in Upper Case.
‘JAVA Programming’ By: Mrs. R.Mallick, Lecturer, CSA,CET 4
5th Sem. Integrated Math & Computing

Example: public void myMethodName()

Program File Name − Name of the program file should exactly match the class
name.

When saving the file, you should save it using the class name (Remember Java is
case sensitive) and append '.java' to the end of the name (if the file name and the
class name do not match, your program will not compile).

But please make a note that in case you do not have a public class present in the
file then file name can be different than class name. It is also not mandatory to
have a public class in the file.

Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should
be saved as 'MyFirstJavaProgram.java'

public static void main(String args[]) − Java program processing starts from the
main() method which is a mandatory part of every Java program.

Java Identifiers

All Java components require names. Names used for classes, variables, and methods
are called identifiers.

In Java, there are several points to remember about identifiers. They are as follows −

All identifiers should begin with a letter (A to Z or a to z), currency character ($)
or an underscore (_).

After the first character, identifiers can have any combination of characters.

A key word cannot be used as an identifier.

Most importantly, identifiers are case sensitive.

Examples of legal identifiers: age, $salary, _value, __1_value.

Examples of illegal identifiers: 123abc, -salary.


‘JAVA Programming’ By: Mrs. R.Mallick, Lecturer, CSA,CET 5
5th Sem. Integrated Math & Computing

Java Modifiers

Like other languages, it is possible to modify classes, methods, etc., by using modifiers.
There are two categories of modifiers −

 Access Modifiers − default, public , protected, private

 Non-access Modifiers − final, abstract

Java Variables

Following are the types of variables in Java −

 Local Variables

 Class Variables (Static Variables)

 Instance Variables (Non-static Variables)

Java Virtual Machine (JVM)

Java is a high level programming language. A program written in high level language
cannot be run on any machine directly. First, it needs to be translated into that
particular machine language. The javac compiler does this thing, it takes java program
(.java file containing source code) and translates it into machine code (referred as byte
code or .class file).

Java Virtual Machine (JVM) is a virtual machine that resides in the real machine
(your computer) and the machine language for JVM is byte code. This makes it easier
for compiler as it has to generate byte code for JVM rather than different machine code
for each type of machine. JVM executes the byte code generated by compiler and
produce output. JVM is the one that makes java platform independent.
‘JAVA Programming’ By: Mrs. R.Mallick, Lecturer, CSA,CET 6
5th Sem. Integrated Math & Computing

Each operating system has different JVM, however the output they produce after
execution of byte code is same across all operating systems. Which means that the
byte code generated on Windows can be run on Mac OS and vice versa. That is why we
call java as platform independent language. The same thing can be seen in the diagram
below:

: The Java Virtual machine (JVM) is the virtual machine that runs on actual machine
(your computer) and executes Java byte code. The JVM doesn’t understand Java source
code, that’s why we need to have javac compiler that compiles *.java files to obtain
*.class files that contain the byte codes understood by the JVM. JVM makes java
portable (write once, run anywhere). Each operating system has different JVM, however
the output they produce after execution of byte code is same across all operating
systems.

Java Keywords

The following list shows the reserved words in Java. These reserved words may not be
used as constant or variable or any other identifier names.

Abstract assert boolean break


‘JAVA Programming’ By: Mrs. R.Mallick, Lecturer, CSA,CET 7
5th Sem. Integrated Math & Computing

Byte case catch char

Class const continue default

Do double else enum

Extends final finally float

For goto if implements

Import instanceof int interface

Long native new package

Private protected public return

Short static strictfp super

Switch synchronized this throw

Throws transient try void

Volatile while
‘JAVA Programming’ By: Mrs. R.Mallick, Lecturer, CSA,CET 8
5th Sem. Integrated Math & Computing

Comments in Java

Java supports single-line and multi-line comments very similar to C and C++. All
characters available inside any comment are ignored by Java compiler.

Example

public class MyFirstJavaProgram {

/* This is my first java program.


* This will print 'Hello World' as the output
* This is an example of multi-line comments.
*/

public static void main(String []args) {


// This is an example of single line comment
/* This is also an example of single line comment. */
System.out.println("Hello World");
}
}

Output

Hello World

Data Types in Java

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

1. Primitive data types: The primitive data types include boolean, char, byte, short,
int, long, float and double.

2. Non-primitive data types: The non-primitive data types


include Classes, Interfaces, and Arrays.
‘JAVA Programming’ By: Mrs. R.Mallick, Lecturer, CSA,CET 9
5th Sem. Integrated Math & Computing

Java Primitive Data Types

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

Java is a statically-typed programming language. It means, all variables must be


declared before its use. That is why we need to declare variable's type and name.

There are 8 types of primitive data types:

boolean data type

byte data type

char data type

short data type

int data type

long data type

float data type

double data type


‘JAVA Programming’ By: Mrs. R.Mallick, Lecturer, CSA,CET 10
5th Sem. Integrated Math & Computing

Data Type Default Value Default size

Boolean False 1 bit

Char '\u0000' 2 byte

Byte 0 1 byte

Short 0 2 byte

Int 0 4 byte

Long 0L 8 byte

Float 0.0f 4 byte

Double 0.0d 8 byte

Boolean Data Type

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

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

Example: Boolean one = false


‘JAVA Programming’ By: Mrs. R.Mallick, Lecturer, CSA,CET 11
5th Sem. Integrated Math & Computing

Byte Data Type

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

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

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

Short Data Type

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

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

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

Int Data Type

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

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

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


‘JAVA Programming’ By: Mrs. R.Mallick, Lecturer, CSA,CET 12
5th Sem. Integrated Math & Computing

Long Data Type

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

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

Float Data Type

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

Example: float f1 = 234.5f

Double Data Type

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

Example: double d1 = 12.3


‘JAVA Programming’ By: Mrs. R.Mallick, Lecturer, CSA,CET 13
5th Sem. Integrated Math & Computing

Char Data Type

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

Example: char letterA = 'A'

Java Identifiers

All Java components require names. Names used for classes, variables, and methods
are called identifiers.

In Java, there are several points to remember about identifiers. They are as follows −

All identifiers should begin with a letter (A to Z or a to z), currency character ($)
or an underscore (_).

After the first character, identifiers can have any combination of characters.

A key word cannot be used as an identifier.

Most importantly, identifiers are case sensitive.

Examples of legal identifiers: age, $salary, _value, __1_value.

Examples of illegal identifiers: 123abc, -salary.


Mrs. ROJALIN MALLICK
Lecturer, CSA,CET

1
Computing the Area of a Circle
This program computes the area of the
circle.

2
animation

public class ComputeArea { allocate memory


/** Main method */ for radius
public static void main(String[] args) {
double radius; radius no value
double area;

// Assign a radius
radius = 20;

// Compute area
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle of
radius " +
radius + " is " + area);
}
}

3
animation

public class ComputeArea {


/** Main method */ memory
public static void main(String[] args) {
double radius; radius no value
double area; area no value

// Assign a radius
radius = 20;
allocate memory
// Compute area for area
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle of
radius " +
radius + " is " + area);
}
}

4
animation

public class ComputeArea { assign 20 to radius


/** Main method */
public static void main(String[] args) {
double radius; radius 20
double area;
area no value
// Assign a radius
radius = 20;

// Compute area
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle of
radius " +
radius + " is " + area);
}
}

5
animation

public class ComputeArea {


/** Main method */ memory
public static void main(String[] args) {
double radius; radius 20
double area;
area 1256.636
// Assign a radius
radius = 20;

// Compute area compute area and assign it


area = radius * radius * 3.14159; to variable area

// Display results
System.out.println("The area for the circle of
radius " +
radius + " is " + area);
}
}

6
animation

public class ComputeArea {


/** Main method */ memory
public static void main(String[] args) {
double radius; radius 20
double area;
area 1256.636
// Assign a radius
radius = 20;

// Compute area
area = radius * radius * 3.14159; print a message to the
console
// Display results
System.out.println("The area for the circle of
radius " +
radius + " is " + area);
}
}

7
 An identifier is a sequence of characters that
consist of letters, digits, underscores (_), and
dollar signs ($).
 An identifier must start with a letter, an
underscore (_), or a dollar sign ($). It cannot
start with a digit.
 An identifier cannot be a reserved word.
 An identifier cannot be true, false, or
null.
 An identifier can be of any length.

8
// Compute the first area
radius = 1.0;
area = radius * radius * 3.14159;
System.out.println("The area is “ +
area + " for radius "+radius);

// Compute the second area


radius = 2.0;
area = radius * radius * 3.14159;
System.out.println("The area is “ +
area + " for radius "+radius);

9
int x; // Declare x to be an
// integer variable;
double radius; // Declare radius to
// be a double variable;
char a; // Declare a to be a
// character variable;

10
x = 1; // Assign 1 to x;

radius = 1.0; // Assign 1.0 to radius;


a = 'A'; // Assign 'A' to a;

11
 int x = 1;
 double d = 1.4;

12
1. Create a Scanner object
Scanner input = new Scanner(System.in);

2. Use the method nextDouble() to obtain to a double value.


For example,
System.out.print("Enter a double value: ");
Scanner input = new Scanner(System.in);
double d = input.nextDouble();

13
java.util.* ; // Implicit import

java.util.Scanner; // Explicit Import

No performance difference

14
Scanner input = new Scanner(System.in);
int value = input.nextInt();

Method Description

nextByte() reads an integer of the byte type.


nextShort() reads an integer of the short type.
nextInt() reads an integer of the int type.
nextLong() reads an integer of the long type.
nextFloat() reads a number of the float type.
nextDouble() reads a number of the double type.

15
Name Meaning Example Result

+ Addition 34 + 1 35

- Subtraction 34.0 – 0.1 33.9

* Multiplication 300 * 30 9000

/ Division 1.0 / 2.0 0.5

% Remainder 20 % 3 2

16
+, -, *, /, and %

5 / 2 yields an integer 2.
5.0 / 2 yields a double value 2.5

5 % 2 yields 1 (the remainder of the


division)

17
System.out.println(Math.pow(2, 3));
// Displays 8.0
System.out.println(Math.pow(4, 0.5));
// Displays 2.0
System.out.println(Math.pow(2.5, 2));
// Displays 6.25
System.out.println(Math.pow(2.5, -2));
// Displays 0.16

18
The double type values are more accurate than the
float type values. For example,

System.out.println("1.0 / 3.0 is " + 1.0 / 3.0);

displays 1.0 / 3.0 is 0.3333333333333333

16 digits

System.out.println("1.0F / 3.0F is " + 1.0F / 3.0F);

displays 1.0F / 3.0F is 0.33333334


7 digits

19
Though Java has its own way to evaluate an
expression behind the scene, the result of a Java
expression and its corresponding arithmetic
expression are the same. Therefore, you can safely
apply the arithmetic rule for evaluating a Java
expression. 3 + 4 * 4 + 5 * (4 + 3) - 1
(1) inside parentheses first
3 + 4 * 4 + 5 * 7 – 1
(2) multiplication
3 + 16 + 5 * 7 – 1
(3) multiplication
3 + 16 + 35 – 1
(4) addition
19 + 35 – 1
(5) addition
54 - 1
(6) subtraction
53

20
Write a program that converts a Fahrenheit degree
to Celsius using the formula:

celsius  ( 95 )( fahrenheit  32)

Note: you have to write


celsius = (5.0 / 9) * (fahrenheit – 32)

21
22
23
int i = 10; Same effect as
int newNum = 10 * i++; int newNum = 10 * i;
i = i + 1;

int i = 10; Same effect as


int newNum = 10 * (++i); i = i + 1;
int newNum = 10 * i;

24
Mrs. ROJALIN MALLICK
Lecturer, CSA,CET
1
Often in a program you need to compare two
values, such as whether i is greater than j. Java
provides six comparison operators (also known
as relational operators) that can be used to
compare two values. The result of the
comparison is a Boolean value: true or false.

boolean b = (1 > 2);

2
Java Mathematics Name Example Result
Operator Symbol (radius is 5)

< < less than radius < 0 false


<= ≤ less than or equal to radius <= 0 false
> > greater than radius > 0 true
>= ≥ greater than or equal to radius >= 0 true
== = equal to radius == 0 false
!= ≠ not equal to radius != 0 true

3
if (radius >= 0) {
area = radius * radius * PI;
if (boolean-expression) { System.out.println("The area"
statement(s);
} + " for the circle of radius "
+ radius + " is " + area);
}

4
if i > 0 { if (i > 0) {
System.out.println("i is positive"); System.out.println("i is positive");
} }
(a) Wrong (b) Correct

if (i > 0) { if (i > 0)
System.out.println("i is positive"); Equivalent System.out.println("i is positive");
}

(a) (b)

5
if (boolean-expression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}

6
if (radius >= 0) {
area = radius * radius * 3.14159;

System.out.println("The area for the “


+ “circle of radius " + radius +
" is " + area);
}
else {
System.out.println("Negative input");
}

7
if (score >= 90.0) if (score >= 90.0)
System.out.print("A"); System.out.print("A");
else else if (score >= 80.0)
if (score >= 80.0) Equivalent System.out.print("B");
System.out.print("B"); else if (score >= 70.0)
else System.out.print("C");
if (score >= 70.0) else if (score >= 60.0)
System.out.print("C"); System.out.print("D");
else else
if (score >= 60.0) System.out.print("F");
System.out.print("D"); This is better
else
System.out.print("F");

(a) (b)

8
9
animation

Suppose score is 70.0 The condition is false

if (score >= 90.0)


System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");

10
animation

Suppose score is 70.0 The condition is false

if (score >= 90.0)


System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");

11
animation

Suppose score is 70.0 The condition is true

if (score >= 90.0)


System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");

12
animation

Suppose score is 70.0 grade is C

if (score >= 90.0)


System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");

13
animation

Suppose score is 70.0 Exit the if statement

if (score >= 90.0)


System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");

14
The else clause matches the most recent if
clause in the same block.

15
Nothing is printed from the preceding
statement. To force the else clause to match
the first if clause, you must add a pair of
braces:
int i = 1;
int j = 2;
int k = 3;
if (i > j) {
if (i > k)
System.out.println("A");
}
else
System.out.println("B");
This statement prints B.

16
Adding a semicolon at the end of an if clause is a
common mistake.
if (radius >= 0);
Wrong
{
area = radius*radius*PI;
System.out.println(
"The area for the circle of radius " +
radius + " is " + area);
}
This mistake is hard to find, because it is not a
compilation error or a runtime error, it is a logic error.
This error often occurs when you use the next-line
block style.
17
if (number % 2 == 0) Equivalent
even = true; boolean even
else = number % 2 == 0;
even = false;
(a) (b)

18
Equivalent if (even)
if (even == true)
System.out.println( System.out.println(
"It is even."); "It is even.");
(a) (b)

19
Operator Name Description

! not logical negation

&& and logical conjunction

|| or logical disjunction

^ exclusive or logical exclusion

20
p !p Example (assume age = 24, weight = 140)

true false !(age > 18) is false, because (age > 18) is true.

false true !(weight == 150) is true, because (weight == 150) is false.

21
p1 p2 p1 && p2 Example (assume age = 24, weight = 140)

false false false (age <= 18) && (weight < 140) is false, because both

conditions are both false.

false true false

true false false (age > 18) && (weight > 140) is false, because (weight

> 140) is false.

true true true (age > 18) && (weight >= 140) is true, because both

(age > 18) and (weight >= 140) are true.

22
p1 p2 p1 || p2 Example (assume age = 24, weight = 140)

false false false

false true true (age > 34) || (weight <= 140) is true, because (age > 34)

is false, but (weight <= 140) is true.

true
true false (age > 14) || (weight >= 150) is false, because

(age > 14) is true.

true
true true
23
This program first prompts the user to enter a year as
an int value and checks if it is a leap year.
A year is a leap year if it is divisible by 4 but not by
100, or it is divisible by 400.
(year % 4 == 0 && year % 100 != 0) || (year % 400
== 0)

LeapYear Run

24
switch (status) {
case 0: compute taxes for single filers;
break;
case 1: compute taxes for married file jointly;
break;
case 2: compute taxes for married file separately;
break;
case 3: compute taxes for head of household;
break;
default: System.out.println("Errors: invalid status");
System.exit(1);
}

25
1
Find the sum of integers from 1 to 10, from 20 to 30, and
from 35 to 45, respectively.

2
int sum = 0;
for (int i = 1; i <= 10; i++)
sum += i;
System.out.println("Sum from 1 to 10 is " + sum);

sum = 0;
for (int i = 20; i <= 30; i++)
sum += i;
System.out.println("Sum from 20 to 30 is " + sum);

sum = 0;
for (int i = 35; i <= 45; i++)
sum += i;
System.out.println("Sum from 35 to 45 is " + sum);

3
int sum = 0;
for (int i = 1; i <= 10; i++)
sum += i;
System.out.println("Sum from 1 to 10 is " + sum);

sum = 0;
for (int i = 20; i <= 30; i++)
sum += i;
System.out.println("Sum from 20 to 30 is " + sum);

sum = 0;
for (int i = 35; i <= 45; i++)
sum += i;
System.out.println("Sum from 35 to 45 is " + sum);

4
public static int sum(int i1, int i2) {
int sum = 0;
for (int i = i1; i <= i2; i++)
sum += i;
return sum;
}

public static void main(String[] args) {


System.out.println("Sum from 1 to 10 is " + sum(1, 10));
System.out.println("Sum from 20 to 30 is " + sum(20, 30));
System.out.println("Sum from 35 to 45 is " + sum(35, 45));
}

5
A method is a collection of statements that are
grouped together to perform an operation.
Define a method Invoke a method

int z = max(x, y);


public static int max(int num1, int num2) {
actual parameters
int result; (arguments)

if (num1 > num2)


result = num1;
else
result = num2;

return result;
}

6
A method is a collection of statements that are
grouped together to perform an operation.
Define a method Invoke a method

return value method formal


modifier type name parameters
int z = max(x, y);
method
public static int max(int num1, int num2) {
header
actual parameters
int result; (arguments)
method
body parameter list
if (num1 > num2)
result = num1;
else
method
result = num2; signature

return result; return value


}

7
Method signature is the combination of the method name and the
parameter list.

Define a method Invoke a method

return value method formal


modifier type name parameters
int z = max(x, y);
method
public static int max(int num1, int num2) {
header
actual parameters
int result; (arguments)
method
body parameter list
if (num1 > num2)
result = num1;
else
method
result = num2; signature

return result; return value


}

8
The variables defined in the method header are known as
formal parameters.

Define a method Invoke a method

return value method formal


modifier type name parameters
int z = max(x, y);
method
public static int max(int num1, int num2) {
header
actual parameters
int result; (arguments)
method
body parameter list
if (num1 > num2)
result = num1;
else
method
result = num2; signature

return result; return value


}

9
When a method is invoked, you pass a value to the parameter. This
value is referred to as actual parameter or argument.

Define a method Invoke a method

return value method formal


modifier type name parameters
int z = max(x, y);
method
public static int max(int num1, int num2) {
header
actual parameters
int result; (arguments)
method
body parameter list
if (num1 > num2)
result = num1;
else
method
result = num2; signature

return result; return value


}

10
A method may return a value. The returnValueType is the data type
of the value the method returns. If the method does not return a
value, the returnValueType is the keyword void. For example, the
returnValueType in the main method is void.
Define a method Invoke a method

return value method formal


modifier type name parameters
int z = max(x, y);
method
public static int max(int num1, int num2) {
header
actual parameters
int result; (arguments)
method
body parameter list
if (num1 > num2)
result = num1;
else
method
result = num2; signature

return result; return value


}

11
animation

pass the value of i


pass the value of j

12
NOTE: One of the benefits of methods is for reuse.
The max method can be invoked from any class
besides TestMax. If you create a new class Test,
you can invoke the max method using
ClassName.methodName (e.g., TestMax.max).

13
14
 public class ExampleMinNumber
 {
 public static void main(String[] args)
 { int a = 11; int b = 6;
 int c = minFunction(a, b);
System.out.println("Minimum Value = " + c); }
/** returns the minimum of two numbers */
public static int minFunction(int n1, int n2)
 { int min;
 if (n1 > n2)
 min = n2;
 else min = n1;
 return min; } } 15
LOOP IN JAVA
Mrs. Rojalin Mallick
Lecturer, CSA,CET
Motivations
Suppose that you need to print a string (e.g., "Welcome to Java!") a
hundred times. It would be tedious to have to write the following
statement a hundred times:

System.out.println("Welcome to Java!");

So, how do you solve this problem?

2
Opening Problem
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");


System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");

100 times….
3
Introducing while Loops

int count = 0;
while (count < 100) {
System.out.println("Welcome to Java");
count++;
}

4
while Loop Flow Chart
while (loop-continuation-condition) { int count = 0;

// loop-body; while (count < 100) {

Statement(s); System.out.println("Welcome to Java!");

} count++;
}

5
Trace while Loop
Initialize count
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

6
Trace while Loop, cont.

(count < 2) is true


int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

7
Trace while Loop, cont.

Print Welcome to Java


int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

8
Trace while Loop, cont.
Increase count by 1
int count = 0;
count is 1 now
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

9
Trace while Loop, cont.
(count < 2) is still true since
int count = 0;
count is 1
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

10
Trace while Loop, cont.

Print Welcome to Java


int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

11
Trace while Loop, cont.
Increase count by 1
int count = 0;
count is 2 now
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

12
Trace while Loop, cont.

(count < 2) is false since


int count = 0;
count is 2 now
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

13
Trace while Loop, cont.

The loop exits. Execute the


int count = 0;
next statement after the
while (count < 2) {
loop.
System.out.println("Welcome to Java!");
count++;
}

14
do-while Loop

do {
// Loop body;
Statement(s);
} while (loop-continuation-condition);

15
Caution, cont.
Similarly, the following loop is also wrong:
int i=0;
while (i < 10); Logic Error
{
System.out.println("i is " + i);
i++;
}
In the case of the do loop, the following semicolon is needed to end
the loop.
int i=0;
do {
System.out.println("i is " + i);
i++;
Correct 16
} while (i<10);
for Loops
for (initial-action; loop-continuation- int i;
condition; action-after-each-iteration) { for (i = 0; i < 100; i++) {
// loop body; System.out.println(
Statement(s); "Welcome to Java!");
} }

17
Note
If the loop-continuation-condition in a for loop is omitted, it is implicitly true.
Thus the statement given below in (a), which is an infinite loop, is correct.
Nevertheless, it is better to use the equivalent loop in (b) to avoid
confusion:

for ( ; ; ) { Equivalent while (true) {


// Do something // Do something
} }
(a) (b)

18
TemperatureTable2.java

{
System.out.println("Celsius\tFahrenheit");

for (long celsius = 0; celsius <= 30; celsius += 5 ) {


long fahrenheit = Math.round(1.8 * celsius + 32);
System.out.println(celsius + "\t\t\t" + fahrenheit);
}
}

19
Nested Loops

Problem: Write a program that uses nested for


loops to print a multiplication table.

20
1
The char type only represents one character. To
represent a string of characters, use the data type
called String. For example,

String message = "Welcome to Java";

String is actually a predefined class in the Java library


just like the System class and Scanner class. The String
type is not a primitive type. It is known as a reference
type. Any Java class can be used as a reference type ”.

2
Method Description

length() Returns the number of characters in this string.


charAt(index) Returns the character at the specified index from this string.
concat(s1) Returns a new string that concatenates this string with string s1.
toUpperCase() Returns a new string with all letters in uppercase.
toLowerCase() Returns a new string with all letters in lowercase.
trim() Returns a new string with whitespace characters trimmed on both sides.

3
Strings are objects in Java. The methods in the preceding
table can only be invoked from a specific string instance.
For this reason, these methods are called instance methods.
A non-instance method is called a static method. A static
method can be invoked without using an object. All the
methods defined in the Math class are static methods. They
are not tied to a specific object instance. The syntax to
invoke an instance method is

referenceVariable.methodName(arguments).

4
String message = "Welcome to Java";
System.out.println("The length of " + message + " is "
+ message.length());

5
String message = "Welcome to Java";
System.out.println("The first character in message is "
+ message.charAt(0));

6
"Welcome".toLowerCase() returns a new string,
welcome.
"Welcome".toUpperCase() returns a new string,
WELCOME.
" Welcome ".trim() returns a new string,
Welcome.

7
String s3 = s1.concat(s2); or String s3 = s1 + s2;

// Three strings are concatenated


String message = "Welcome " + "to " + "Java";

// String Chapter is concatenated with number 2


String s = "Chapter" + 2; // s becomes Chapter2

// String Supplement is concatenated with


character B
String s1 = "Supplement" + 'B'; // s1 becomes
SupplementB

8
Scanner input = new Scanner(System.in);
System.out.print("Enter three words separated by
spaces: ");
String s1 = input.next();
String s2 = input.next();
String s3 = input.next();
System.out.println("s1 is " + s1);
System.out.println("s2 is " + s2);
System.out.println("s3 is " + s3);

9
Scanner input = new Scanner(System.in);
System.out.print("Enter a character: ");
String s = input.nextLine();
char ch = s.charAt(0);
System.out.println("The character entered is "
+ ch);

10
Method Description

equals(s1) Returns true if this string is equal to string s1 .


equalsIgnoreCase(s1) Returns true if this string is equal to string s1 ; it is case insensitive.
compareTo(s1) Returns an integer greater than 0 , equal to 0 , or less than 0 to indicate whether
this string is greater than, equal to, or less than s1 .
compareToIgnoreCase(s1) Same as compareTo except that the comparison is case insensitive.
startsWith(prefix) Returns true if this string starts with the specified prefix.
endsWith(suffix) Returns true if this string ends with the specified suffix.

11
Method Description

substring(beginIndex) Returns this string’s substring that begins with the character at the specified
beginIndex and extends to the end of the string,

substring(beginIndex, Returns this string’s substring that begins at the specified beginIndex and
endIndex) extends to the character at index endIndex – 1, Note that the character at
endIndex is not part of the substring.

12
Method Description

indexOf(ch) Returns the index of the first occurrence of ch in the string. Returns -1 if not
matched.
indexOf(ch, fromIndex) Returns the index of the first occurrence of ch after fromIndex in the string.
Returns -1 if not matched.
indexOf(s) Returns the index of the first occurrence of string s in this string. Returns -1 if
not matched.
indexOf(s, fromIndex) Returns the index of the first occurrence of string s in this string after
fromIndex. Returns -1 if not matched.
lastIndexOf(ch) Returns the index of the last occurrence of ch in the string. Returns -1 if not
matched.
lastIndexOf(ch, Returns the index of the last occurrence of ch before fromIndex in this
fromIndex) string. Returns -1 if not matched.
lastIndexOf(s) Returns the index of the last occurrence of string s. Returns -1 if not matched.
lastIndexOf(s, Returns the index of the last occurrence of string s before fromIndex.
fromIndex) Returns -1 if not matched.

13
int k = s.indexOf(' ');
String firstName = s.substring(0, k);
String lastName = s.substring(k + 1);

14
CLASS AND OBJECT IN JAVA

Rojalin Mallick

Lecturer CSAdept.

CET BBSR
What is an object in Java

An entity that has state and behavior is known as an object e.g., chair, bike,
marker, pen, table, car, etc. It can be physical or logical (tangible and
intangible). An object has three characteristics:

o State: represents the data (value) of an object.


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

For Example, Pen is an object. Its name is Reynolds; color is white, known
as its state. It is used to write, so writing is its behavior.

An object is an instance of a class. A class is a template or blueprint from


which objects are created. So, an object is the instance(result) of a class.

Object Definitions:

o An object is a real-world entity.


o An object is a runtime entity.
o The object is an entity which has state and behavior.
o The object is an instance of a class.

What is a class in Java

A class is a group of objects which have common properties. It is a


template or blueprint from which objects are created. It is a logical entity. It
can't be physical.

A class in Java can contain:


o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface

Syntax to declare a class:

class <class_name>

field;
method;
}

Instance variable in Java

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

Method in Java

In Java, a method is like a function which is used to expose the behavior of


an object.

Advantage of Method
o Code Reusability
o Code Optimization
new keyword in Java

The new keyword is used to allocate memory at runtime. All objects get
memory in Heap memory area.

Object and Class Example: main within the class

In this example, we have created a Student class which has two data
members id and name. We are creating the object of the Student class by
new keyword and printing the object's value.

Here, we are creating a main() method inside the class.

File: Student.java

//Java Program to illustrate how to define a class and fields


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

System.out.println(s1.name);
}
}

Output:
0
null

Object and Class Example: main outside the class

Let's see a simple example, where we are having main() method in another
class.

We can have multiple classes in different Java files or single Java file. If you
define multiple classes in a single Java source file, it is a good idea to save
the file name with the class name which has main() method.

File: TestStudent1.java

//Java Program to demonstrate having the main method in


//another class
//Creating Student class.
class Student{
int id;
String name;
}
//Creating another class TestStudent1 which contains the main method
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Output:
0
null
3 Ways to initialize object

There are 3 ways to initialize object in Java.

1. By reference variable
2. By method
3. By constructor

1) Object and Class Example: Initialization through reference

Initializing an object means storing data into the object. Let's see a simple
example where we are going to initialize the object through a reference
variable.

File: TestStudent2.java

class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Rama";
System.out.println(s1.id+" "+s1.name);//printing members with a white s
pace
}
}

Output:

101 Rama

We can also create multiple objects and store information in it through


reference variable.

File: TestStudent3.java

class Student{
int id;
String name;
}
class TestStudent3{
public static void main(String args[]){
//Creating objects
Student s1=new Student();
Student s2=new Student();
//Initializing objects
s1.id=101;
s1.name="Rama";
s2.id=102;
s2.name="Amit";
//Printing data
System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name);
}
}

Output:

101 Rama

102 Amit

2) Object and Class Example: Initialization through method

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

File: TestStudent4.java

class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation()
{System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Rama");
s2.insertRecord(222,"Amit");
s1.displayInformation();
s2.displayInformation();
}
}

Output:

111 Rama
222 Amit

3) Object and Class Example: Initialization through a constructor

Object and Class Example: Employee

Let's see an example where we are maintaining records of employees.

File: TestEmployee.java

class Employee{
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
e1.display();
e2.display();
e3.display();
}
}

Output:
101 ajeet 45000.0
102 irfan 25000.0
103 nakul 55000.0

Object and Class Example: Rectangle

There is given another example that maintains the records of Rectangle


class.

File: TestRectangle1.java

class Rectangle{
int length;
int width;
void insert(int l, int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
}
class TestRectangle1{
public static void main(String args[]){
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}

Output:

55
45

Assignment:
1. Java Program to demonstrate the working of a banking-system
where we deposit and withdraw amount from our account.
Creating an Account class which has deposit() and withdraw() methods
Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called
when an instance of the class is created. At the time of calling constructor,
memory for the object is allocated in the memory.

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

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

it calls a default constructor if there is no constructor available in the class.


In such case, Java compiler provides a default constructor by default.

There are two types of constructors in Java:

no-arg constructor, and parameterized constructor.

Note: It is called constructor because it constructs the values at the time of


object creation. It is not necessary to write a constructor for a class. It is
because java compiler creates a default constructor if your class doesn't
have any.

Rules for creating Java constructor


There are two rules defined for the constructor.

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


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors

There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Java Default Constructor

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


parameter.

Syntax of default constructor:


<class_name>()
{}
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class.

It will be invoked at the time of object creation.

//Java Program to create and call a default constructor


class Bike1{
//creating a default constructor
Bike1()
{
System.out.println("Bike is created");}
//main method
public static void main(String args[])
{
//calling a default constructor
Bike1 b=new Bike1();
}
}

Output:

Bike is created

Example of default constructor that displays the default values


class Student3{
int id;
String name;
//method to display the value of id and name
void display()
{System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects
Student3 s1=new Student3();
Student3 s2=new Student3();
//displaying values of the object
s1.display();
s2.display();
}

Output:

0 null
0 null

Explanation:In the above class,you are not creating any constructor so


compiler provides you a default constructor. Here 0 and null values are
provided by default constructor.

Java Parameterized Constructor

A constructor which has a specific number of parameters is called a


parameterized constructor.

Why use the parameterized constructor?

The parameterized constructor is used to provide different values to


distinct objects. However, you can provide the same values also.
Example of parameterized constructor

In this example, we have created the constructor of Student class that have
two parameters. We can have any number of parameters in the constructor.

//Java Program to demonstrate the use of the parameterized constructor.

class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display()
{System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects and passing values
Student4 s1 = new Student4(111,"Rama");
Student4 s2 = new Student4(222,"Amit");
//calling method to display the values of object
s1.display();
s2.display();
}
}

Output:

111 Rama
222 Amit
Constructor Overloading in Java

In Java, a constructor is just like a method but without return type. It can
also be overloaded like Java methods.
Constructor overloading in Java is a technique of having more than one
constructor with different parameter lists. They are arranged in a way that
each constructor performs a different task. They are differentiated by the
compiler by the number of parameters in the list and their types.

Example of Constructor Overloading


//Java program to overload constructors
class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a)
{
id = i;
name = n;
age=a;
}
void display()
{System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Rama");
Student5 s2 = new Student5(222,"Amit",25);
s1.display();
s2.display();
}
}

Output:
111 Rama 0
222 Amit 25
Programming JAVA

next →← prev

What is Static Variable in Java?

Static variable in Java is variable which belongs to the class and initialized only once at
the start of the execution. It is a variable which belongs to the class and not to
object(instance ). Static variables are initialized only once, at the start of the execution.
These variables will be initialized first, before the initialization of any instance variables.

 A single copy to be shared by all instances of the class


 A static variable can be accessed directly by the class name and doesn’t need any
object

Syntax :

What is Static Variable in Java?

Static variable in Java is variable which belongs to the class and initialized only once at
the start of the execution. It is a variable which belongs to the class and not to
object(instance ). Static variables are initialized only once, at the start of the execution.
These variables will be initialized first, before the initialization of any instance variables.

 A single copy to be shared by all instances of the class


 A static variable can be accessed directly by the class name and doesn’t need any
object.

Java static keyword

The static keyword in Java is used for memory management mainly. We can apply
static keyword with variables, methods, blocks and nested classes. The static keyword
belongs to the class than an instance of the class.

The static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block
4. Nested class
Programming JAVA

Java static variable

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

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

Advantages of static variable

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

class Student{
int rollno;
String name;
String college="ITS";

Example of static variable


//Java Program to demonstrate the use of static variable
class Student{
int rollno;//instance variable
String name;
static String college ="ITS";//static variable
//constructor
Student(int r, String n){
rollno = r;
name = n;
}
//method to display the values
void display (){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code
//Student.college="BBDIT";
s1.display();

s2.display();
Programming JAVA

}
}
o/p:
111 karan ITS
222 Aryan ITS

Program of the counter without static variable

In this example, we have created an instance variable named count which is


incremented in the constructor. Since instance variable gets the memory at the time of
object creation, each object will have the copy of the instance variable. If it is
incremented, it won't reflect other objects. So each object will have the value 1 in the
count variable.

//Java Program to demonstrate the use of an instance variable


//which get memory each time when we create an object of the class.
class Counter{
int count=0;//will get memory each time when the instance is created

Counter(){
count++;//incrementing value
System.out.println(count);
}

public static void main(String args[]){


//Creating objects
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}
o/p: 1
1
1

Program of counter by static variable

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

//Java Program to illustrate the use of static variable which


//is shared with all objects.
class Counter2{
static int count=0;//will get memory only once and retain its value
Programming JAVA

Counter2(){
count++;//incrementing the value of static variable
System.out.println(count);
}

public static void main(String args[]){


//creating objects
Counter2 c1=new Counter2();
Counter2 c2=new Counter2();
Counter2 c3=new Counter2();
}

Output:

1
2
3

2) Java static method

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

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

Example of static method


//Java Program to demonstrate the use of a static method.
class Student{
int rollno;
String name;
static String college = "ITS";
//static method to change the value of static variable
static void change(){
college = "BBDIT";
}
//constructor to initialize the variable
Student(int r, String n){
Programming JAVA

rollno = r;
name = n;
}
//method to display values
void display(){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to create and display the values of object
public class TestStaticMethod{
public static void main(String args[]){
Student.change();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
s1.display();
s2.display();
s3.display();
}
}

Output:111 Karan BBDIT

222 Aryan BBDIT


333 Sonoo BBDIT

EXAMPLE

//Java Program to get the cube of a given number using the static method

class Calculate{
static int cube(int x){
return x*x*x;
}

public static void main(String args[]){


int result=Calculate.cube(5);
System.out.println(result);
}
}
Output:125
Programming JAVA

Restrictions for the static method

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

1. The static method can not use non static data member or call non-static method
directly.
2. this and super cannot be used in static context.

class A{
int a=40;//non static

public static void main(String args[]){


System.out.println(a);
}
}
Output:Compile Time Error
Access Modifiers in Java

There are two types of modifiers in Java: access modifiers and non-access modifiers.

The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods,
and class by applying the access modifier on it.

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It cannot
be accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It
cannot be accessed from outside the package. If you do not specify any access
level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and
outside the package through child class. If you do not make the child class, it
cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed
from within the class, outside the class, within the package and outside the
package.

There are many non-access modifiers, such as static, abstract, synchronized, native,
volatile, transient, etc

Understanding Java Access Modifiers


Access within within outside package by outside
Modifier class package subclass only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y
Simple example of private access modifier

In this example, we have created two classes A and Simple. A class contains private
data member and private method. We are accessing these private members from
outside the class, so there is a compile-time error.

class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}

Role of Private Constructor

If you make any class constructor private, you cannot create the instance of that class
from outside the class. For example:

class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}

2) Default

If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. It cannot be accessed from outside the package. It
provides more accessibility than private. But, it is more restrictive than protected, and
public.

Example of default access modifier


In this example, we have created two packages pack and mypack. We are accessing the
A class from outside its package, since A class is not public, so it cannot be accessed
from outside the package.

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

}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}

In the above example, the scope of class A and its method msg() is default so it cannot
be accessed from outside the package.

3) Protected

The protected access modifier is accessible within package and outside the package but
through inheritance only.

The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class.

It provides more accessibility than the default modifer.

Example of protected access modifier

In this example, we have created the two packages pack and mypack. The A class of
pack package is public, so can be accessed from outside the package. But msg method of
this package is declared as protected, so it can be accessed from outside the class only
through inheritance.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;

class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello

4) Public

The public access modifier is accessible everywhere. It has the widest scope among all
other modifiers.

Example of public access modifier

//save by A.java

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

package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
Interface in Java

An interface in Java is a blueprint of a class. It has static constants and abstract


methods.

The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in Java.

In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.

Java Interface also represents the IS-A relationship.

It cannot be instantiated just like the abstract class.

we can have default and static methods in an interface.

we can have private methods in an interface.

Why use Java interface?

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

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.

How to declare an interface?

An interface is declared by using the interface keyword. It provides total abstraction;


means all the methods in an interface are declared with the empty body, and all the
fields are public, static and final by default. A class that implements an interface must
implement all the methods declared in the interface.

Syntax:
interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}

The relationship between classes and interfaces

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

Java
Interface Example

In this example, the Printable interface has only one method, and its implementation is
provided in the A6 class.

interface printable
{
void print();
}
class A6 implements printable{
public void print()
{System.out.println("Hello");}

public static void main(String args[]){


A6 obj = new A6();
obj.print();
}
}

Output:
Hello

Java Interface Example: Drawable

In this example, the Drawable interface has only one method. Its implementation is
provided by Rectangle and Circle classes. In a real scenario, an interface is defined by
someone else, but its implementation is provided by different implementation
providers. Moreover, it is used by someone else. The implementation part is hidden by
the user who uses the interface.

File: TestInterface1.java

//Interface declaration: by first user


interface Drawable{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable{
public void draw()
{System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
//Using interface: by third user
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();
d.draw();
}}

Output:

drawing circle

Java Interface Example: Bank

Let's see another example of java interface which provides the implementation of Bank
interface.

File: TestInterface2.java
interface Bank{
float rateOfInterest();

}
class SBI implements Bank{
public float rateOfInterest(){return 9.15f;}
}
class PNB implements Bank{
public float rateOfInterest(){return 9.7f;}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}}

Output:

ROI: 9.15

Multiple inheritance in Java by interface

If a class implements multiple interfaces, or an interface extends multiple interfaces, it is


known as multiple Inheritance

interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
}
}

Output:Hello
Welcome

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


interface, why?

As we have explained in the inheritance chapter, multiple inheritance is not supported


in the case of class because of ambiguity. However, it is supported in case of an
interface because there is no ambiguity. It is because its implementation is provided by
the implementation class. For example:

interface Printable{
void print();
}
interface Showable{
void print();
}

class TestInterface3 implements Printable, Showable{


public void print()
{
System.out.println("Hello");
}
public static void main(String args[])
{
TestInterface3 obj = new TestInterface3();
obj.print();
}
}
you can see in the above example, Printable and Showable interface have same methods
but its implementation is provided by class TestTnterface1, so there is no ambiguity.

java Wrapper Classes

Wrapper classes provide a way to use primitive data types (int, boolean, etc..) as objects.

The table below shows the primitive type and the equivalent wrapper class:

Primitive Data Type Wrapper Class

Byte Byte

Short Short

Int Integer

Long Long

Loat Float

Double Double

Boolean Boolean

Char Character
Crea
ting Wrapper Objects

To create a wrapper object, use the wrapper class instead of the primitive type. To get
the value, you can just print the object:

public static void main(String[] args) {

Integer myInt = 5;

Double myDouble = 5.99;

Character myChar = 'A';

System.out.println(myInt);

System.out.println(myDouble);

System.out.println(myChar);

other useful method is the toString() method, which is used to convert wrapper objects
to strings.

In the following example, we convert an Integer to a String, and use


the length() method of the String class to output the length of the "string":

Example

public class MyClass {

public static void main(String[] args) {

Integer myInt = 100;

String myString = myInt.toString();

System.out.println(myString.length());

o }?An abstract class must be declared with an abstract keyword.


o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body

>An abstract class must be declared with an abstract keyword.


o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body

Java Garbage Collection

In java, garbage means unreferenced objects.

Garbage Collection is process of reclaiming the runtime unused memory automatically.


In other words, it is a way to destroy the unused objects.

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

Advantage of Garbage Collection


o It makes java memory efficient because garbage collector removes the
unreferenced objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we don't need
to make extra efforts.

How can an object be unreferenced?

There are many ways:

o By nulling the reference


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

1) By nulling a reference:

Employee e=new Employee();


e=null;

2) By assigning a reference to another:


Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage collection

3) By anonymous object:
new Employee();

finalize() method

The finalize() method is invoked each time before the object is garbage collected. This
method can be used to perform cleanup processing. This method is defined in Object
class as:

1. protected void finalize(){}

Note: The Garbage collector of JVM collects only those objects that are created by new
keyword. So if you have created any object without new, you can use finalize method
to perform cleanup processing (destroying remaining objects).

gc() method

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

1. public static void gc(){}

Note: Garbage collection is performed by Garbage Collector(GC). This thread calls the finalize()
method before object is garbage collected.

Simple Example of garbage collection in java


public class TestGarbage1{
public void finalize()
{

System.out.println("object is garbage collected");


}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}
Output:

object is garbage collected


object is garbage collected
Method Overloading in Java

If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.

If we have to perform only one operation, having same name of the methods increases
the readability of the program.

Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int,int) for two parameters,
and b(int,int,int) for three parameters then it may be difficult for you as well as other
programmers to understand the behavior of the method because its name differs.

Method Overloading: changing no. of arguments

In this example, we have created two methods, first add() method performs addition of
two numbers and second add method performs addition of three numbers.

][[\++[n this example, we are creating static methods so that we don't need to create
instance for calling methods.

class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}

Inheritance in Java

Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system).

The idea behind inheritance in Java is that you can create new classes that are built
upon existing classes. When you inherit from an existing class, you can reuse methods
and fields of the parent class. Moreover, you can add new methods and fields in your
current class also.

Inheritance represents the IS-A relationship which is also known as a parent-


child relationship.

Why use inheritance in java


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

Terms used in Inheritance


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

The syntax of Java Inheritance


class Subclass-name extends Super class-name
{
//methods and fields
}

The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.

In the terminology of Java, a class which is inherited is called a parent or super class,
and the new class is called child or subclass.

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel
and hierarchical.

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


only. We will learn about interfaces later.

Note: Multiple inheritance is not supported in Java through class.

When one class inherits multiple classes, it is known as multiple inheritance. For
Example:
Single Inheritance Example

When a class inherits another class, it is known as a single inheritance. In the example
given below, Dog class inherits the Animal class, so there is the single inheritance.

File: TestInheritance.java

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

barking...
eating...

Multilevel Inheritance Example

When there is a chain of inheritance, it is known as multilevel inheritance. As you can see
in the example given below, BabyDog class inherits the Dog class which again inherits
the Animal class, so there is a multilevel inheritance.

File: TestInheritance2.java

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}

Output:

weeping...
barking...
eating...

Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.

Consider a scenario where A, B, and C are three classes. The C class inherits A and B
classes. If A and B classes have the same method and you call it from child class object,
there will be ambiguity to call the method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time
error if you inherit 2 classes. So whether you have same method or different, there will
be compile time error.

class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were

public static void main(String args[]){


C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Output:

Compile Time Error


Abstract class in Java

A class which is declared with the abstract keyword is known as an abstract class
in Java. It can have abstract and non-abstract methods (method with the body).

Before learning the Java abstract class, let's understand the abstraction in Java first.

Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only


functionality to the user.

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

Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java


1. Abstract class
2. Interface

Example of abstract class

abstract class A{}

Abstract Method in Java

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

Example of abstract method

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

Example of Abstract class that has an abstract method

In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.

abstract class Bike{


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

In this example, Shape is the abstract class, and its implementation is provided by the
Rectangle and Circle classes.

In this example, if you create the instance of Rectangle class, draw() method of
Rectangle class will be invoked.
File: TestAbstraction1.java

abstract class Shape{


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

class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., get
Shape() method
s.draw();
}
}
drawing circle

Another example of Abstract class in java

File: TestBank.java

abstract class Bank{


abstract int getRateOfInterest();
}
class SBI extends Bank{
int getRateOfInterest(){return 7;}
}
class PNB extends Bank{
int getRateOfInterest(){return 8;}
}

class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}}
Output:
Rate of Interest is: 7 %
Rate of Interest is: 8 %
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body

Method Overriding in Java

1. Understanding the problem without method overriding


2. Can we override the static method
3. Method overloading vs. method overriding

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

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

Usage of Java Method Overriding


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

Rules for Java Method Overriding


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

Example of method overriding

In this example, we have defined the run method in the subclass as defined in the
parent class but it has some specific implementation. The name and parameter of the
method are the same, and there is IS-A relationship between the classes, so there is
method overriding.
/Java Program to illustrate the use of Java Method Overriding

//Creating a parent class.


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

public static void main(String args[]){


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

Output:

Bike is running safely


Final:

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

1. variable
2. method
3. class

The final keyword can be applied with the variables, a final variable that have no value
it is called blank final variable or uninitialized final variable. It can be initialized in the
constructor only. The blank final variable can be static also which will be initialized in
the static block only. We will have detailed learning of these. Let's first learn the basics
of final keyword.
1) Java final variable

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

Example of final variable

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

class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}

Output:Compile Time Error

Java final class

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


Example of final class
final class Bike{}

class Honda1 extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
honda.run();
}
}
Output: compile time error

3) Java final method

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

Example of final method


class Bike{
final void run()
{System.out.println("running");}
}

class Honda extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


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

Output:compile time error


Programming in JAVA 1
5th Semester, Math & computing.CET

Exceptions in Java
What is an Exception?
An 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.
Error vs Exception
Error: An Error indicates serious problem that a reasonable application should not try
to catch.

Exception: Exception indicates conditions that a reasonable application might try to


catch.

Exception Hierarchy
All exception and errors types are sub classes of class Throwable, which is base class of
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 are 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.

How JVM handle an Exception?

Default Exception Handling : Whenever inside a method, if an exception has occurred,


the method creates an Object known as Exception Object and hands it off to the run-
time system(JVM). The exception object contains name and description of the exception,
and current state of the program where exception has occurred. Creating the Exception
Object and handling it to the run-time system is called throwing an Exception.There
might be the list of the methods that had been called to get to the method where
Programming in JAVA 2
5th Semester, Math & computing.CET

exception was occurred. This ordered list of the methods is called Call Stack.Now the
following procedure will happen.

 The run-time system searches the call stack to find the method that contains block
of code that can handle the occurred exception. The block of the code is
called Exception handler.
 The run-time system starts searching from the method in which exception
occurred, proceeds through call stack in the reverse order in which methods were
called.
If it finds appropriate handler then it passes the occurred exception to it. Appropriate
handler means the type of the exception object thrown matches the type of the
exception object it can handle.

Example :
// Java program to demonstrate how exception is thrown.
class ThrowsExecp{

public static void main(String args[]){

String str = null;


System.out.println(str.length());

}
}
Output :
Exception in thread "main" java.lang.NullPointerException
at ThrowsExecp.main
Let us see an example that illustrate how run-time system searches appropriate
exception handling code on the call stack :
// Java program to demonstrate exception is thrown
// how the runTime system searches th call stack
// to find appropriate exception handler.
class ExceptionThrown
{
// It throws the Exception(ArithmeticException).
// Appropriate Exception handler is not found within this method.
static int divideByZero(int a, int b){

// this statement will cause ArithmeticException(/ by zero)


int i = a/b;
Programming in JAVA 3
5th Semester, Math & computing.CET

return i;
}

// The runTime System searches the appropriate Exception handler


// in this method also but couldn't have found. So looking forward
// on the call stack.
static int computeDivision(int a, int b) {

int res =0;

try
{
res = divideByZero(a,b);
}
// doesn't matches with ArithmeticException
catch(NumberFormatException ex)
{
System.out.println("NumberFormatException is occured");
}
return res;
}

// In this method found appropriate Exception handler.


// i.e. matching catch block.
public static void main(String args[]){

int a = 1;
int b = 0;

try
{
int i = computeDivision(a,b);

// matching ArithmeticException
catch(ArithmeticException ex)
{
// getMessage will print description of exception(here / by zero)
System.out.println(ex.getMessage());
}
Programming in JAVA 4
5th Semester, Math & computing.CET

}
}
Output :
/ by zero.
How Programmer handles an exception?

 If run-time system searches all the methods on call stack and couldn’t have found
the appropriate handler then run-time system handover the Exception Object
to default exception handler , which is part of run-time system. This handler
prints the exception information in the following format and terminates
program abnormally.

Customized Exception Handling : Java exception handling is managed via five


keywords: try, catch, throw, throws, and finally. Briefly, here is how they work.
Program statements that you think can raise exceptions are contained within a try
block. If an exception occurs within the try block, it is thrown. Your code can catch this
exception (using catch block) and handle it in some rational manner. System-generated
exceptions are automatically thrown by the Java run-time system. To manually throw
an exception, use the keyword throw. Any exception that is thrown out of a method
must be specified as such by a throws clause. Any code that absolutely must be
executed after a try block completes is put in a finally block.
Detailed Article: Control flow in try catch finally block

Need of try-catch clause(Customized Exception Handling)

Consider the following java program.


// java program to demonstrate
// need of try-catch clause

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

// array of size 4.
int[] arr = new int[4];

// this statement causes an exception


int i = arr[4];

// the following statement will never execute


System.out.println("Hi, I want to execute");
}
Programming in JAVA 5
5th Semester, Math & computing.CET

}
Output :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4

Explanation : In the above example an array is defined with size i.e. you can access
elements only from index 0 to 3. But you trying to access the elements at index 4(by
mistake) that’s why it is throwing an exception.In this case, JVM terminates the
program abnormally. The statement System.out.println(“Hi, I want to execute”); will
never execute. To execute it, we must handled the exception using try-catch. Hence to
continue normal flow of the program, we need try-catch clause.
How to use try-catch clause
try {
// block of code to monitor for errors
// the code you think can raise an exception
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// optional
finally {
// block of code to be executed after try block ends
}
In a method, there can be more than one statements that might throw exception, So
put all these statements within its own try block and provide separate exception
handler within own catch block for each of them.
If an exception occurs within the try block, that exception is handled by the
exception handler associated with it. To associate exception handler, we must
put catch block after it. There can be more than one exception handlers.
Each catch block is a exception handler that handles the exception of the type
indicated by its argument. The argument, ExceptionType declares the type of the
exception that it can handle and must be the name of the class that inherits
from Throwable class.
Programming in JAVA 6
5th Semester, Math & computing.CET

For each try block there can be zero or more catch blocks, but only one finally
block.
The finally block is optional.It always gets executed whether an exception occurred
in try block or not . If exception occurs, then it will be executed after try and catch
blocks. And if exception does not occur then it will be executed after
the try block. The finally block in java is used to put important codes such as clean
up code e.g. closing the file or closing the connection.
Customized Exception Handling : Java exception handling is managed via five
keywords: try, catch, throw, throws, and finally. Briefly, here is how they work.
Program statements that you think can raise exceptions are contained within a try
block. If an exception occurs within the try block, it is thrown. Your code can catch
this exception (using catch block) and handle it in some rational manner. System-
generated exceptions are automatically thrown by the Java run-time system. To
manually throw an exception, use the keyword throw. Any exception that is
thrown out of a method must be specified as such by a throws clause. Any code
that absolutely must be executed after a try block completes is put in a finally
block.
User defined exception in java
In java we have already defined, exception classes such as ArithmeticException,
NullPointerException etc. These exceptions are already set to trigger on pre-
defined conditions such as when you divide a number by zero it triggers
ArithmeticException, In the last tutorial we learnt how to throw these exceptions
explicitly based on your conditions using throw keyword.

In java we can create our own exception class and throw that exception using
throw keyword. These exceptions are known as user-
defined or custom exceptions. In this tutorial we will see how to create your own
custom exception and throw it on a particular condition.

Example of User defined exception in Java

/* This is my Exception class, I have named it MyException


* you can give any name, just remember that it should
* extend Exception class
*/
class MyException extends Exception{
String str1;
/* Constructor of custom exception class
* here I am copying the message that we are passing while
* throwing the exception to a string and then displaying
* that string along with the message.
*/
Programming in JAVA 7
5th Semester, Math & computing.CET

MyException(String str2) {
str1=str2;
}
public String toString(){
return ("MyException Occurred: "+str1) ;
}
}

class Example1{
public static void main(String args[]){
try{
System.out.println("Starting of try block");
// I'm throwing the custom exception using throw
throw new MyException("This is My error Message");
}
catch(MyException exp){
System.out.println("Catch Block") ;
System.out.println(exp) ;
}
}
}
Output:

Starting of try block


Catch Block
MyException Occurred: This is My error Message

Explanation:
You can see that while throwing custom exception I gave a string
in parenthesis ( throw new MyException("This is My error Message");). That’s
why we have a parameterized constructor (with a String parameter) in my
custom exception class.

Notes:
1. User-defined exception must extend Exception class.
2. The exception is thrown using throw keyword.

Java Multi-catch block

A try block can be followed by one or more catch blocks. Each catch block must contain
a different exception handler. So, if you have to perform different tasks at the
occurrence of different exceptions, use java multi-catch block.
Programming in JAVA 8
5th Semester, Math & computing.CET

 At a time only one exception occurs and at a time only one catch block is
executed.
 All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.

Example 1

Let's see a simple example of java multi-catch block.

public class MultipleCatchBlock1 {

public static void main(String[] args) {

try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
output:

Arithmetic Exception occurs


rest of the code
java Nested try block

The try block within a try block is known as nested try block in java.
Programming in JAVA 9
5th Semester, Math & computing.CET

Why use nested try block

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

Syntax:
....
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
....

Java nested try example

Let's see a simple example of java nested try block.

class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}

try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
Programming in JAVA 10
5th Semester, Math & computing.CET

System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}

System.out.println("normal flow..");
}
}
Built-in Exceptions in Java with examples

Types of Exceptions in Java


Built-in exceptions are the exceptions which 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.

Examples of Built-in Exception:

1. Arithmetic exception : It is thrown when an exceptional condition has occurred


in an arithmetic operation.
// 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");

}
Programming in JAVA 11
5th Semester, Math & computing.CET

Output:
Can't divide a number by 0
2. ArrayIndexOutOfBounds Exception : 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.
// 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
3. ClassNotFoundException : This Exception is raised when we try to access a class
whose definition is not found.
// Java program to illustrate the

// concept of ClassNotFoundException
Programming in JAVA 12
5th Semester, Math & computing.CET

class Welcome {

} class Mca {

} class MyClass {

public static void main(String[] args)

Object o = class.forName(args[0]).newInstance();

System.out.println("Class created for" + o.getClass().getName());

Output:
ClassNotFoundException
4. FileNotFoundException : This Exception is raised when a file is not accessible or
does not open.
// 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 {
Programming in JAVA 13
5th Semester, Math & computing.CET

// 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
5. IOException : It is thrown when an input-output operation failed or interrupted
// Java program to illustrate IOException

import java.io.*;

class Geeks {

public static void main(String args[])

FileInputStream f = null;

f = new FileInputStream("abc.txt");

int i;

while ((i = f.read()) != -1) {

System.out.print((char)i);
Programming in JAVA 14
5th Semester, Math & computing.CET

f.close();

Output:
error: unreported exception IOException; must be caught or declared to be thrown
6. InterruptedException : It is thrown when a thread is waiting, sleeping, or doing
some processing, and it is interrupted.
// Java Program to illustrate

// InterruptedException

class Inter{

public static void main(String args[])

Thread t = new Thread();

t.sleep(10000);

Output:
error: unreported exception InterruptedException; must be caught or declared to be
thrown
Inter-thread communication in Java 1
5th . Semester, Math and computing, CET

Inter-thread communication in Java

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


threads to communicate with each other.

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


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

wait()

notify()

notifyAll()

1) wait() method

Causes current thread to release the lock and wait until either another thread invokes
the notify() method or the notifyAll() method for this object, or a specified amount of
time has elapsed.

e current thread must own this object's monitor, so it must be called from the
synchronized method only otherwise it will throw exception.

Method Description

public final void wait()throws waits until object is notified.


InterruptedException
Inter-thread communication in Java 2
5th . Semester, Math and computing, CET

public final void wait(long timeout)throws waits for the specified amount
InterruptedException of time.

2) notify() method

Wakes up a single thread that is waiting on this object's monitor. If any threads are
waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and
occurs at the discretion of the implementation. Syntax:

public final void notify()

3) notifyAll() method

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

public final void notifyAll()

Understanding the process of inter-thread communication

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

1. Threads enter to acquire lock.

2. Lock is acquired by on thread.

3. Now thread goes to waiting state if you call wait() method on the object.
Otherwise it releases the lock and exits.

4. If you call notify() or notifyAll() method, thread moves to the notified state
(runnable state).

5. Now thread is available to acquire lock.

6. After completion of the task, thread releases the lock and exits the monitor state
of the object.
Inter-thread communication in Java 3
5th . Semester, Math and computing, CET

Difference between wait and sleep Method

wait() sleep()

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

wait() is the method of Object class sleep() is the method of Thread class

wait() is the non-static method sleep() is the static method

wait() is the non-static method sleep() is the static method

should be notified by notify() or after the specified amount of time, sleep


notifyAll() methods is completed.

Example of inter thread communication in java

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

class Customer{
int amount=10000;
synchronized void withdraw(int amount){
System.out.println("going to withdraw...");

if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}
catch(Exception e)
{}
Inter-thread communication in Java 4
5th . Semester, Math and computing, CET

}
this.amount-=amount;
System.out.println("withdraw completed...");
}

synchronized void deposit(int amount){


System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}

class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run()
{c.withdraw(15000);}
}.start();
new Thread(){
public void run(){c.deposit(10000);}
}.start();

}}

Output: going to withdraw...


Less balance; waiting for deposit...
going to deposit...
Inter-thread communication in Java 5
5th . Semester, Math and computing, CET

deposit completed...
withdraw completed
5th Semester, Math and computing Int MSC, CET 1

Java FileInputStream Class

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

Java FileInputStream class declaration

Let's see the declaration for java.io.FileInputStream class:

1. public class FileInputStream extends InputStream

Java FileInputStream class methods

Method Description

int available() It is used to return the estimated number of bytes that can be
read from the input stream.

int read() It is used to read the byte of data from the input stream.

int read(byte[] b) It is used to read up to b.length bytes of data from the input
stream.

int read(byte[] b, int It is used to read up to len bytes of data from the input
off, int len) stream.

long skip(long x) It is used to skip over and discards x bytes of data from the
input stream.

FileChannel It is used to return the unique FileChannel object associated


getChannel() with the file input stream.
5th Semester, Math and computing Int MSC, CET 2

FileDescriptor It is used to return the FileDescriptor object.


getFD()

protected void It is used to ensure that the close method is call when there is
finalize() no more reference to the file input stream.

void close() It is used to closes the stream.

Java FileInputStream example 1: read single character

import java.io.FileInputStream;

public class DataStreamExample {

public static void main(String args[]){

try{

FileInputStream fin=new FileInputStream("D:\\testout.txt");

int i=fin.read();

System.out.print((char)i);

fin.close();

}catch(Exception e){System.out.println(e);}

Note: Before running the code, a text file named as "testout.txt" is required to be created.
In this file, we are having following content:

Welcome to cetcampusa

After executing the above program, you will get a single character from the file which is
87 (in byte form). To see the text, you need to convert it into character.
5th Semester, Math and computing Int MSC, CET 3

Output:

Java FileInputStream example 2: read all characters

package com.cetcampusa;

import java.io.FileInputStream;

public class DataStreamExample {

public static void main(String args[]){

try{

FileInputStream fin=new FileInputStream("D:\\testout.txt");

int i=0;

while((i=fin.read())!=-1){

System.out.print((char)i);

fin.close();

}catch(Exception e){System.out.println(e);}

Output:

Welcome to cetcampusa

Character Streams
5th Semester, Math and computing Int MSC, CET 4

The Java platform stores character values using Unicode conventions. Character stream
I/O automatically translates this internal format to and from the local character set. In
Western locales, the local character set is usually an 8-bit superset of ASCII.

For most applications, I/O with character streams is no more complicated than I/O
with byte streams. Input and output done with stream classes automatically translates
to and from the local character set. A program that uses character streams in place of
byte streams automatically adapts to the local character set and is ready for
internationalization — all without extra effort by the programmer.

Using Character Streams

All character stream classes are descended from Reader and Writer. As with byte streams,
there are character stream classes that specialize in file I/O: FileReader and FileWriter.
The CopyCharacters example illustrates these classes.

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CopyCharacters {


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

FileReader inputStream = null;


FileWriter outputStream = null;

try {
inputStream = new FileReader("students.txt");
outputStream = new FileWriter("characteroutput.txt");
int c;
5th Semester, Math and computing Int MSC, CET 5

while ((c = inputStream.read()) != -1) {


outputStream.write(c);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
}

CopyCharacters is very similar to CopyBytes. The most important difference is


that CopyCharacters uses FileReader and FileWriter for input and output in place
of FileInputStream and FileOutputStream. Notice that both CopyBytes and CopyCharacters use
an int variable to read to and write from. However, in CopyCharacters, the int variable
holds a character value in its last 16 bits; in CopyBytes, the int variable holds a byte value
in its last 8 bits.

Character Streams that Use Byte Streams

Character streams are often "wrappers" for byte streams. The character stream uses the
byte stream to perform the physical I/O, while the character stream handles translation
between characters and bytes. FileReader, for example, uses FileInputStream,
while FileWriter uses FileOutputStream There are two general-purpose byte-to-character
"bridge" streams: InputStreamReader and OutputStreamWriter. Use them to create character
streams when there are no prepackaged character stream classes that meet your needs.
5th Semester, Math and computing Int MSC, CET 6

The sockets lesson in the networking trail shows how to create character streams from
the byte streams provided by socket classes.

Line-Oriented I/O

Character I/O usually occurs in bigger units than single characters. One common unit is
the line: a string of characters with a line terminator at the end. A line terminator can be
a carriage-return/line-feed sequence ("\r\n"), a single carriage-return ("\r"), or a single
line-feed ("\n"). Supporting all possible line terminators allows programs to read text
files created on any of the widely used operating systems.

The CopyLines example invokes BufferedReader.readLine and PrintWriter.println to do input


and output one line at a time.

import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.IOException;

public class CopyLines {


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

BufferedReader inputStream = null;


PrintWriter outputStream = null;

try {
inputStream = new BufferedReader(new FileReader("student.txt"));
outputStream = new PrintWriter(new FileWriter("characteroutput.txt"));

String l;
5th Semester, Math and computing Int MSC, CET 7

while ((l = inputStream.readLine()) != null) {


outputStream.println(l);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
}
JDBC Connectivity 1
5th Semester, Math. And computing, CET

JDBC Connectivity

Java Database Connectivity with 5 Steps

5 Steps to connect to the database in java

1. Register the driver class

2. Create the connection object

3. Create the Statement object

4. Execute the query

5. Close the connection object

1) Register the driver class

The forName() method of Class class is used to register the driver class. This method is
used to dynamically load the driver class.

Syntax of forName() method


1. public static void forName(String className)throws ClassNotFoundException

Example to register the OracleDriver class

Here, Java program is loading oracle driver to esteblish database connection.

1. Class.forName("oracle.jdbc.driver.OracleDriver");

2) Create the connection object

The getConnection() method of DriverManager class is used to establish


connection with the database.
JDBC Connectivity 2
5th Semester, Math. And computing, CET

Syntax of getConnection() method


1. 1) public static Connection getConnection(String url)throws SQLException
2. 2) public static Connection getConnection(String url,String name,String password)
3. throws SQLException

Example to establish connection with the Oracle database


1. Connection con=DriverManager.getConnection(
2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");

3) Create the Statement object

The createStatement() method of Connection interface is used to create


statement. The object of statement is responsible to execute queries with the
database.

Syntax of createStatement() method


1. public Statement createStatement()throws SQLException

Example to create the statement object


1. Statement stmt=con.createStatement();

4) Execute the query


The executeQuery() method of Statement interface is used to execute queries to the
database. This method returns the object of ResultSet that can be used to get all the records
of a table.

Syntax of executeQuery() method


JDBC Connectivity 3
5th Semester, Math. And computing, CET

1. public ResultSet executeQuery(String sql)throws SQLException

Example to execute query


1. ResultSet rs=stmt.executeQuery("select * from emp");
2.
3. while(rs.next()){
4. System.out.println(rs.getInt(1)+" "+rs.getString(2));
5. }

5) Close the connection object

By closing connection object statement and ResultSet will be closed automatically. The
close() method of Connection interface is used to close the connection.

Syntax of close() method


1. public void close()throws SQLException

Example to close connection


1. con.close();

After you've installed the appropriate driver, it is time to establish a database


connection using JDBC.

The programming involved to establish a JDBC connection is fairly simple. Here are
these simple four steps −

 Import JDBC Packages: Add import statements to your Java program to import
required classes in your Java code.

 Register JDBC Driver: This step causes the JVM to load the desired driver
implementation into memory so it can fulfill your JDBC requests.
JDBC Connectivity 4
5th Semester, Math. And computing, CET

 Database URL Formulation: This is to create a properly formatted address that


points to the database to which you wish to connect.

 Create Connection Object: Finally, code a call to


the DriverManager object's getConnection( ) method to establish actual database
connection.

Import JDBC Packages

The Import statements tell the Java compiler where to find the classes you reference in
your code and are placed at the very beginning of your source code.

To use the standard JDBC package, which allows you to select, insert, update, and
delete data in SQL tables, add the following imports to your source code −

import java.sql.* ; // for standard JDBC programs


import java.math.* ; // for BigDecimal and BigInteger support

Register JDBC Driver

You must register the driver in your program before you use it. Registering the driver is the
process by which the Oracle driver's class file is loaded into the memory, so it can be utilized
as an implementation of the JDBC interfaces.

You need to do this registration only once in your program. You can register a driver in one of
two ways.

Approach I - Class.forName()

The most common approach to register a driver is to use Java's Class.forName() method, to
dynamically load the driver's class file into memory, which automatically registers it. This
method is preferable because it allows you to make the driver registration configurable and
portable.

The following example uses Class.forName( ) to register the Oracle driver −

try {
JDBC Connectivity 5
5th Semester, Math. And computing, CET

Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}

You can use getInstance() method to work around noncompliant JVMs, but then you'll have to
code for two extra Exceptions as follows −

try {
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
catch(IllegalAccessException ex) {
System.out.println("Error: access problem while loading!");
System.exit(2);
catch(InstantiationException ex) {
System.out.println("Error: unable to instantiate driver!");
System.exit(3);
}

Approach II - DriverManager.registerDriver()

The second approach you can use to register a driver, is to use the
static DriverManager.registerDriver() method.

You should use the registerDriver() method if you are using a non-JDK compliant JVM, such as
the one provided by Microsoft.

The following example uses registerDriver() to register the Oracle driver −

try {
JDBC Connectivity 6
5th Semester, Math. And computing, CET

Driver myDriver = new oracle.jdbc.driver.OracleDriver();


DriverManager.registerDriver( myDriver );
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}

Database URL Formulation

After you've loaded the driver, you can establish a connection using
the DriverManager.getConnection() method. For easy reference, let me list the three
overloaded DriverManager.getConnection() methods −

 getConnection(String url)

 getConnection(String url, Properties prop)

 getConnection(String url, String user, String password)

Here each form requires a database URL. A database URL is an address that points to your
database.

Formulating a database URL is where most of the problems associated with establishing a
connection occurs.

Following table lists down the popular JDBC driver names and database URL.

RDBMS JDBC driver name URL format

MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/


databaseName

ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:port


Number:databaseName

DB2 COM.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:port


JDBC Connectivity 7
5th Semester, Math. And computing, CET

Number/databaseName

Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:hostname: port


Number/databaseName
Thread Scheduling in JAVA 1
5th Semester, Math and compting, CET

Thread Scheduling

 Execution of multiple threads on a single CPU, in some order, is called scheduling.


 In general, the runnable thread with the highest priority is active (running)
 Java is priority-preemptive
 If a high-priority thread wakes up, and a low-priority thread is running
 Then the high-priority thread gets to run immediately
Allows on-demand processing
Efficient use of CPU

2. Types of scheduling

 Waiting and Notifying


 Waiting [wait()] and notifying [notify(), notifyAll()] provides means of
communication between threads that synchronize on the same object.
wait(): when wait() method is invoked on an object, the thread executing that code
gives up its lock on the object immediately and moves the thread to the wait state.
notify(): This wakes up threads that called wait() on the same object and moves the
thread to ready state.
notifyAll(): This wakes up all the threads that called wait() on the same object.
Running and Yielding
 Yield() is used to give the other threads of the same priority a chance to execute i.e.
causes current running thread to move to runnable state.
Sleeping and Waking up
 Sleep() is used to pause a thread for a specified period of time i.e. moves the current
running thread to Sleep state for a specified amount of time, before moving it to
runnable state. Thread.sleep(no. of milliseconds);

Thread Priority

 When a Java thread is created, it inherits its priority from the thread that created it.
Thread Scheduling in JAVA 2
5th Semester, Math and compting, CET

 You can modify a thread’s priority at any time after its creation using
the setPriority method.
 Thread priorities are integers ranging between MIN_PRIORITY (1)
and MAX_PRIORITY (10) . The higher the integer, the higher the
priority.Normally the thread priority will be 5.

isAlive() and join() methods

 isAlive() method is used to determine if a thread is still alive. It is the best way to
determine if a thread has been started but has not yet completed its run()
method. final boolean isAlive();
 The nonstatic join() method of class Thread lets one thread “join onto the end” of
another thread. This method waits until the thread on which it is called
terminates. final void join();

3. Blocking Threads

 When reading from a stream, if input is not available, the thread will block
 Thread is suspended (“blocked”) until I/O is available
 Allows other threads to automatically activate
 When I/O available, thread wakes back up again
 Becomes “runnable” i.e. gets into ready state

A thread can not be moved to a new group after the thread has been created.

Thread join() method in Java with example

The join() method is used to hold the execution of currently running thread until the
specified thread is dead(finished execution). In this tutorial we will discuss the purpose
and use of join() method with examples.
Thread Scheduling in JAVA 3
5th Semester, Math and compting, CET

Why we use join() method?

In normal circumstances we generally have more than one thread, thread scheduler
schedules the threads, which does not guarantee the order of execution of threads.
For example lets have a look at the following code:

Without using join()

Here we have three threads th1, th2 and th3. Even though we have started the threads
in a sequential manner the thread scheduler does not start and end them in the specified
order. Everytime you run this code, you may get a different result each time. So the
question is: How can we make sure that the threads executes in a particular order.
The Answer is: By using join() method appropriately.

public class JoinExample2 {


public static void main(String[] args) {
Thread th1 = new Thread(new MyClass2(), "th1");
Thread th2 = new Thread(new MyClass2(), "th2");
Thread th3 = new Thread(new MyClass2(), "th3");

th1.start();
th2.start();
th3.start();
}
}

class MyClass2 implements Runnable{

@Override
public void run() {
Thread Scheduling in JAVA 4
5th Semester, Math and compting, CET

Thread t = Thread.currentThread();
System.out.println("Thread started: "+t.getName());
try {
Thread.sleep(4000);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
System.out.println("Thread ended: "+t.getName());
}
}
OutputThread started: th1
Thread started: th3
Thread started: th2
Thread ended: th1
Thread ended: th3
Thread ended: th2

Example with join()

Lets say our requirement is to execute them in the order of first, second and third. We
can do so by using join() method appropriately.

public class JoinExample {


public static void main(String[] args) {
Thread th1 = new Thread(new MyClass(), "th1");
Thread th2 = new Thread(new MyClass(), "th2");
Thread th3 = new Thread(new MyClass(), "th3");

// Start first thread immediately


th1.start();
Thread Scheduling in JAVA 5
5th Semester, Math and compting, CET

/* Start second thread(th2) once first thread(th1)


* is dead
*/
try {
th1.join();
} catch (InterruptedException ie) {
ie.printStackTrace();
}
th2.start();

/* Start third thread(th3) once second thread(th2)


* is dead
*/
try {
th2.join();
} catch (InterruptedException ie) {
ie.printStackTrace();
}
th3.start();

// Displaying a message once third thread is dead


try {
th3.join();
} catch (InterruptedException ie) {
ie.printStackTrace();
}
System.out.println("All three threads have finished execution");
Thread Scheduling in JAVA 6
5th Semester, Math and compting, CET

}
}

class MyClass implements Runnable{

@Override
public void run() {
Thread t = Thread.currentThread();
System.out.println("Thread started: "+t.getName());
try {
Thread.sleep(4000);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
System.out.println("Thread ended: "+t.getName());

}
}
Output:

Thread started: th1


Thread ended: th1
Thread started: th2
Thread ended: th2
Thread started: th3
Thread ended: th3
All three threads have finished execution
Thread Scheduling in JAVA 7
5th Semester, Math and compting, CET
Thread Priority 1
5th SemesterInt Msc Math & computing,CET

Priority of a Thread (Thread Priority):

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

3 constants defined in Thread class:

1. public static int MIN_PRIORITY

2. public static int NORM_PRIORITY

3. public static int MAX_PRIORITY

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


1 and the value of MAX_PRIORITY is 10.

Example of priority of a Thread:

class TestMultiPriority1 extends Thread{


public void run(){
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());

}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
Thread Priority 2
5th SemesterInt Msc Math & computing,CET

m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}
Output: running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1

What if we call run() method directly instead start() method?

o Each thread starts in a separate call stack.

o Invoking the run() method from main thread, the run() method goes onto the
current call stack rather than at the beginning of a new call stack.

class TestCallRun1 extends Thread{


public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestCallRun1 t1=new TestCallRun1();
t1.run();
}
0utput:running...

Problem if you direct call run() method


Thread Priority 3
5th SemesterInt Msc Math & computing,CET

class TestCallRun2 extends Thread{


public void run(){
for(int i=1;i<5;i++){
try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestCallRun2 t1=new TestCallRun2();
TestCallRun2 t2=new TestCallRun2();

t1.run();
t2.run();
}
}
Output:1
2
3
4
5
1
2
3
4
5
Event Handling in Java 1
5th semester Int Math and computing. Semester,CET

What is an Event?

Change in the state of an object is known as event i.e. event describes the change in
state of source. Events are generated as result of user interaction with the graphical
user interface components. For example, clicking on a button, moving the mouse,
entering a character through keyboard, selecting an item from list, scrolling the page
are the activities that causes an event to happen.

Types of Event

The events can be broadly classified into two categories:


 Foreground Events - Those events which require the direct interaction of
user.They are generated as consequences of a person interacting with the
graphical components in Graphical User Interface. For example, clicking on a
button, moving the mouse, entering a character through keyboard,selecting an
item from list, scrolling the page etc.

 Background Events - Those events that require the interaction of end user are
known as background events. Operating system interrupts, hardware or
software failure, timer expires, an operation completion are the example of
background events.

What is Event Handling?

Event Handling is the mechanism that controls the event and decides what should
happen if an event occurs. This mechanism have the code which is known as event
handler that is executed when an event occurs. Java Uses the Delegation Event Model
to handle the events. This model defines the standard mechanism to generate and
handle the events.Let's have a brief introduction to this model.

The Delegation Event Model has the following key participants namely:
Event Handling in Java 2
5th semester Int Math and computing. Semester,CET

 Source - The source is an object on which event occurs. Source is responsible for
providing information of the occurred event to it's handler. Java provide as with
classes for source object.

 Listener - It is also known as event handler.Listener is responsible for generating


response to an event. From java implementation point of view the listener is also
an object. Listener waits until it receives an event. Once the event is received ,
the listener process the event an then returns.

The benefit of this approach is that the user interface logic is completely separated
from the logic that generates the event. The user interface element is able to delegate
the processing of an event to the separate piece of code. In this model ,Listener needs
to be registered with the source object so that the listener can receive the event
notification. This is an efficient way of handling the event because the event
notifications are sent only to those listener that want to receive them.

Steps involved in event handling

 The User clicks the button and the event is generated.

 Now the object of concerned event class is created automatically and


information about the source and the event get populated with in same object.

 Event object is forwarded to the method of registered listener class.

 the method is now get executed and returns.

Points to remember about listener

 In order to design a listener class we have to develop some listener


interfaces.These Listener interfaces forecast some public abstract callback
methods which must be implemented by the listener class.
Event Handling in Java 3
5th semester Int Math and computing. Semester,CET

 If you do not implement the any if the predefined interfaces then your class can
not act as a listener class for a source object.

Callback Methods

These are the methods that are provided by API provider and are defined by the
application programmer and invoked by the application developer. Here the callback
methods represents an event method. In response to an event java jre will fire callback
method. All such callback methods are provided in listener interfaces.

If a component wants some listener will listen to it's events the the source must register
itself to the listener.

Event Handling Example

Create the following java program using any editor of your choice in say D:/ > AWT >
com > tutorialspoint > gui >
AwtControlDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

private Frame mainFrame;


private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;

public AwtControlDemo(){
prepareGUI();
}

public static void main(String[] args){


AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showEventDemo();
}
Event Handling in Java 4
5th semester Int Math and computing. Semester,CET

private void prepareGUI(){


mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);

controlPanel = new Panel();


controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}

private void showEventDemo(){


headerLabel.setText("Control in action: Button");

Button okButton = new Button("OK");


Button submitButton = new Button("Submit");
Button cancelButton = new Button("Cancel");

okButton.setActionCommand("OK");
submitButton.setActionCommand("Submit");
cancelButton.setActionCommand("Cancel");

okButton.addActionListener(new ButtonClickListener());
submitButton.addActionListener(new ButtonClickListener());
cancelButton.addActionListener(new ButtonClickListener());

controlPanel.add(okButton);
controlPanel.add(submitButton);
controlPanel.add(cancelButton);
Event Handling in Java 5
5th semester Int Math and computing. Semester,CET

mainFrame.setVisible(true);
}

private class ButtonClickListener implements ActionListener{


public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if( command.equals( "OK" )) {
statusLabel.setText("Ok Button clicked.");
}
else if( command.equals( "Submit" ) ) {
statusLabel.setText("Submit Button clicked.");
}
else {
statusLabel.setText("Cancel Button clicked.");
}
}
}
}
Compile the program using command prompt. Go to D:/ > AWT and type the
following command.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java
If no error comes that means compilation is successful. Run the program using
following command.
Thread in JAVA 1
5th . Semester, int.msc math &computing, CET

What are Java Threads?

A thread is a:

Facility to allow multiple activities within a single process


Referred as lightweight process
A thread is a series of executed statements
Each thread has its own program counter, stack and local variables
A thread is a nested sequence of method calls
Its shares memory, files and per-process state

What's the need of a thread or why we use Threads?

To perform asynchronous or background processing


Increases the responsiveness of GUI applications
Take advantage of multiprocessor systems
Simplify program logic when there are multiple independent entities

What happens when a thread is invoked?

When a thread is invoked, there will be two paths of execution. One path will execute
the thread and the other path will follow the statement after the thread invocation.
There will be a separate stack and memory space for each thread.

Risk Factor

Proper co-ordination is required between threads accessing common variables [use


of synchronized and volatile] for consistence view of data
overuse of java threads can be hazardous to program’s performance and its
maintainability.
Thread in JAVA 2
5th . Semester, int.msc math &computing, CET

Threads in Java

Java threads facility and API is deceptively simple: Every java program creates at least
one thread [ main() thread ]. Additional threads are created through the Thread
constructor or by instantiating classes that extend the Thread class.

Thread creation in Java

Thread implementation in java can be achieved in two ways:

1. Extending the java.lang.Thread class


2. Implementing the java.lang.Runnable Interface

Note: The Thread and Runnable are available in the java.lang.* package

1) By extending thread class

The class should extend Java Thread class.


The class should override the run() method.
The functionality that is expected by the Thread to be executed is written in the
run() method.

void start(): Creates a new thread and makes it runnable.


void run(): The new thread begins its life inside this method.

Example:

public class MyThread extends Thread {


public void run(){
System.out.println("thread is running...");
}
public static void main(String[] args) {
MyThread obj = new MyThread();
obj.start();
}
Thread in JAVA 3
5th . Semester, int.msc math &computing, CET

2) By Implementing Runnable interface

The class should implement the Runnable interface


The class should implement the run() method in the Runnable interface
The functionality that is expected by the Thread to be executed is put in the run()
method

Example:

public class MyThread implements Runnable {


public void run(){
System.out.println("thread is running..");
}
public static void main(String[] args) {
Thread t = new Thread(new MyThread());
t.start();
}
Extends Thread class vs Implements Runnable Interface?

Extending the Thread class will make your class unable to extend other classes,
because of the single inheritance feature in JAVA. However, this will give you a
simpler code structure. If you implement Runnable, you can gain better object-
oriented design and consistency and also avoid the single inheritance problems.
If you just want to achieve basic functionality of a thread you can simply
implement Runnable interface and override run() method. But if you want to do
something serious with thread object as it has other methods like suspend(),
resume(), ..etc which are not available in Runnable interface then you may prefer
to extend the Thread class.

Thread Life cycle in Java

The start method creates the system resources, necessary to run the thread,
schedules the thread to run, and calls the thread’s run method.
Thread in JAVA 4
5th . Semester, int.msc math &computing, CET

A thread becomes “Not Runnable” when one of these events occurs:

 If sleep method is invoked.


 The thread calls the wait method.
 The thread is blocking on I/O.

A thread dies naturally when the run method exits.

Below diagram clearly depicts the various phases of thread life cycle in java.

Ending Thread

A Thread ends due to the following reasons:

The thread ends when it comes when the run() method finishes its execution.
When the thread throws an Exception or Error that is not being caught in the
program.
Java program completes or ends.
Another thread calls stop() methods.
Thread in JAVA 5
5th . Semester, int.msc math &computing, CET

Synchronization of Threads

In many cases concurrently running threads share data and two threads try to do
operations on the same variables at the same time. This often results in corrupt
data as two threads try to operate on the same data.
A popular solution is to provide some kind of lock primitive. Only one thread can
acquire a particular lock at any particular time. This can be achieved by using a
keyword “synchronized” .
By using the synchronize only one thread can access the method at a time and a
second call will be blocked until the first call returns or wait() is called inside the
synchronized method.
SWING 101
UI FRAMEWORKS CONCEPTS
 Events
 A way for components (in general) to communicate with each other asynchronously
(meaning, without directly calling methods on each other or using polling)
 In java, it simply means that you register an interface (usually called a Listener) to an
event generator and when an event generator wants to notify all the registered
listeners it iterates over them calls methods define in them
The parameter passed to the interface methods is an called an Event object
 MVC (Model – View – Controller)
 A model that represents the data for the application
 The view that is the visual representation of that data
 A controller that takes user input on the view and translates that to changes in the
model
UI FRAMEWORKS CONCEPTS
 UI runs in another thread called the EDT (Event Dispatch Thread)
 This is done in order to make the UI responsive
 Separate UI code from Business Logic code
 User code can run in the EDT, but for long loops and actions (like network
operations, database operations, etc.) it is usually preferred to run the code in
another thread
 In order to run a code in the EDT (after a thread has finished its work) use:
SwingUtilities.invokeLater()
(J)COMPONENT IN SWING
 JComponents (extends Container)
 JButton, JLabel, JTable, JTree, JCheckBox, etc.

 Containers
 Components that groups other components and other containers
 Can be used with Layout Manager to automatically set the size and location of their
child components
 Top Level Containers
 The root objects for swing application
 At least one is mandatory for the application to start
 JFrame, JDialog, JApplet, JWindow
(J)COMPONENT IN SWING
 JComponents have the following capabilities:
 Properties (such as color, preferred size)
 Methods (for getting and setting data like setText(), etc.)
 Events (a component might send more that one type of event)
(J)COMPONENT IN SWING
 All the components (from AWT or from Swing) have properties that
changes how the component looks and behaves
 You can register different types of Event Listeners to a component in
order to receive events from it (for example: MouseEvent on a JPanel,
ChangeEvent on a JCheckBox, etc.)
 Some components have several Models in them for different data: a JList
component have a Selection Model that represents the current selected
items in the component (and you can register a listener for that as well)
 All components have a ‘paintComponent’ method that actually tell the
JVM how to draw the component. Overwriting this method is done for
advanced cases…
SWING 101.0
PAINT AND LAYOUT
 Swing components painting and layout order
 First you set properties on components
 Then swings lays outs components
 Then paints them
 Note: until the top level container has been set to visible and laid out you can not know
the size and location of your component
 paint, repaint, invalidate, validate
 paint() – paints the component. Invoked internally by Swing – DO NOT USE
 repaint() – instructs Swing to paint the given region when the “time is right” – Safe to use
 validate() –checks if the container (and its children) have been changed and if so instructs
Swing to perform a re-layout
 invalidate() –marks a container as invalid but does not perform a re-layout
CONTAINERS
 The main containers are: JPanel, JSplitPane, JScrollPane and JTabbedPane
 Have properties that defines their looks and behavior (just like
components)
 Don’t have data models
 Have events (mouse events, size changes events, etc.)
 Adding components– add the component to the children list of the
container and set the component parent to be the container
 When you add a component you link it to the container – not create a
copy of it in the container
 getParent() – for containers and components
 getChildren() – for containers only
 Each component or container has a single parent
LAYOUT MANAGER
 Only valid for containers
 Automatically set the size and location of all the child components in
the container
 Different layout algorithms – some have properties (for example: gap
between components)
 Some require additional data for each child component – that data
should be added in advanced when adding a component to a container
 Settings size constrains (size, preferred, minimum, maximum)
COMPLEX LAYOUT
 A container an contains child containers (same as components)
 When it resizes – all of its child containers will be resized as well and
then re-layout their child component recursively
 You can mix different layout algorithms (for example: a JPanel with
Border Layout that contains 3 JPanels with Flow Layout each)
ACTIONS
 Just like the interface Runnable – this is Swing’s way to pass “a
parameter of a method to a component” – meaning, pass some code to
execute when a common event occurs
 Actions are not JComponents (not UI objects)
 The same action instance can be passed to several UI components
(menu item, JButton, etc.)
 Actions have properties for the component that will use them:
 Label
 Icon
 Tooltip
DIALOGS
 JDialogs are Top-Level containers
 Open a dialog that displayed some content (like JFrame)
 To set custom content – add it to the dialog’s content pane
 After calling setVisible(true) on a dialog – no events are dispatched to
the rest of the UI components (except in the dialog itself)
 You can customize the dialog’s buttons (change the number of buttons,
the text on each button, etc.)
GUI EDITORS
 Great for all the things in the world… except when you need to change
a component programmatically
 Here are some recommendations:
 NetBeans
 JFormDesigner
 Eclipse UI editor

 Another issue – some editors might add dependencies on external Jars


(which you’ll need to bundle with your complied code in order for it to
execute)
 Adding external jars to project
OTHER SWING STUFF
 Menus
 Renderers (and Editors)
 How to set native look and feel
 Selection events, change events(Optional)

You might also like