JAVA All Merged
JAVA All Merged
Features of JAVA
Object Oriented − In Java, everything is an Object. Java can be easily extended
since it is based on the Object model.
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.
programs that can perform many tasks simultaneously. This design feature
allows the developers to construct interactive applications that can run
smoothly.
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.
Let us look at a simple code that will print the words Hello World.
Example
Open a command prompt window and go to the directory where you saved the
class. Assume it's C:\.
You will be able to see ' Hello World ' printed on the window.
Output
Basic Syntax
About Java programs, it is very important to keep in mind the following points.
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.
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
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.
Java Modifiers
Like other languages, it is possible to modify classes, methods, etc., by using modifiers.
There are two categories of modifiers −
Java Variables
Local Variables
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.
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
Output
Hello World
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.
In Java language, primitive data types are the building blocks of data manipulation.
These are the most basic data types available in Java language.
Byte 0 1 byte
Short 0 2 byte
Int 0 4 byte
Long 0L 8 byte
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.
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.
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.
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.
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.
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.
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.
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.
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.
1
Computing the Area of a Circle
This program computes the area of the
circle.
2
animation
// 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
// 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
// Compute area
area = radius * radius * 3.14159;
// Display results
System.out.println("The area for the circle of
radius " +
radius + " is " + area);
}
}
5
animation
// Display results
System.out.println("The area for the circle of
radius " +
radius + " is " + area);
}
}
6
animation
// 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);
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;
11
int x = 1;
double d = 1.4;
12
1. Create a Scanner object
Scanner input = new Scanner(System.in);
13
java.util.* ; // Implicit import
No performance difference
14
Scanner input = new Scanner(System.in);
int value = input.nextInt();
Method Description
15
Name Meaning Example Result
+ Addition 34 + 1 35
% Remainder 20 % 3 2
16
+, -, *, /, and %
5 / 2 yields an integer 2.
5.0 / 2 yields a double value 2.5
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,
16 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:
21
22
23
int i = 10; Same effect as
int newNum = 10 * i++; int newNum = 10 * i;
i = i + 1;
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.
2
Java Mathematics Name Example Result
Operator Symbol (radius is 5)
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;
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
10
animation
11
animation
12
animation
13
animation
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
|| or logical disjunction
20
p !p Example (assume age = 24, weight = 140)
true false !(age > 18) is false, because (age > 18) is true.
21
p1 p2 p1 && p2 Example (assume age = 24, weight = 140)
false false false (age <= 18) && (weight < 140) is false, because both
true false false (age > 18) && (weight > 140) is false, because (weight
true true true (age > 18) && (weight >= 140) is true, because both
22
p1 p2 p1 || p2 Example (assume age = 24, weight = 140)
false true true (age > 34) || (weight <= 140) is true, because (age > 34)
true
true false (age > 14) || (weight >= 150) is false, because
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;
}
5
A method is a collection of statements that are
grouped together to perform an operation.
Define a method Invoke a method
return result;
}
6
A method is a collection of statements that are
grouped together to perform an operation.
Define a method Invoke a method
7
Method signature is the combination of the method name and the
parameter list.
8
The variables defined in the method header are known as
formal parameters.
9
When a method is invoked, you pass a value to the parameter. This
value is referred to as actual parameter or argument.
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
11
animation
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!");
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;
} 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.
7
Trace while Loop, cont.
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.
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.
13
Trace while Loop, cont.
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:
18
TemperatureTable2.java
{
System.out.println("Celsius\tFahrenheit");
19
Nested Loops
20
1
The char type only represents one character. To
represent a string of characters, use the data type
called String. For example,
2
Method Description
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;
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
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:
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.
Object Definitions:
class <class_name>
field;
method;
}
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
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.
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.
File: Student.java
System.out.println(s1.name);
}
}
Output:
0
null
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
1. By reference variable
2. By method
3. By constructor
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
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
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
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
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.
Every time an object is created using the new() keyword, at least one
constructor is called.
Output:
Bike is created
Output:
0 null
0 null
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.
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);}
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.
Output:
111 Rama 0
222 Amit 25
Programming JAVA
next →← prev
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.
Syntax :
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.
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.
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.
class Student{
int rollno;
String name;
String college="ITS";
s2.display();
Programming JAVA
}
}
o/p:
111 karan ITS
222 Aryan ITS
Counter(){
count++;//incrementing value
System.out.println(count);
}
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.
Counter2(){
count++;//incrementing the value of static variable
System.out.println(count);
}
Output:
1
2
3
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.
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();
}
}
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;
}
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
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.
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
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");}
}
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.
//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.
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.
//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
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.
There are mainly three reasons to use interface. They are given below.
Syntax:
interface <interface_name>{
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");}
Output:
Hello
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
Output:
drawing circle
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
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");}
Output:Hello
Welcome
interface Printable{
void print();
}
interface Showable{
void print();
}
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:
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:
Integer myInt = 5;
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.
Example
System.out.println(myString.length());
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.
1) By nulling a reference:
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:
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.
Note: Garbage collection is performed by Garbage Collector(GC). This thread calls the finalize()
method before object is garbage collected.
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.
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.
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.
On the basis of class, there can be three types of inheritance in java: single, multilevel
and hierarchical.
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...
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...
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
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
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.
A method which is declared as abstract and does not have implementation is known as
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.
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
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
File: TestBank.java
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
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.
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
Output:
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).
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();
}
}
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 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.
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{
}
}
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){
return i;
}
try
{
res = divideByZero(a,b);
}
// doesn't matches with ArithmeticException
catch(NumberFormatException ex)
{
System.out.println("NumberFormatException is occured");
}
return res;
}
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.
class GFG {
public static void main (String[] args) {
// array of size 4.
int[] arr = new int[4];
}
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.
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:
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.
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
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:
The try block within a try block is known as nested try block in java.
Programming in JAVA 9
5th Semester, Math & computing.CET
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)
{
}
....
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
// ArithmeticException
class ArithmeticException_Demo {
try {
int a = 30, b = 0;
catch (ArithmeticException e) {
}
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 {
try {
// size 5
catch (ArrayIndexOutOfBoundsException e) {
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 {
Object o = class.forName(args[0]).newInstance();
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 {
try {
Programming in JAVA 13
5th Semester, Math & computing.CET
catch (FileNotFoundException e) {
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 {
FileInputStream f = null;
f = new FileInputStream("abc.txt");
int i;
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{
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
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(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:
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax:
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).
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
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
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...");
}
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();
}}
deposit completed...
withdraw completed
5th Semester, Math and computing Int MSC, CET 1
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.
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.
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.
import java.io.FileInputStream;
try{
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:
package com.cetcampusa;
import java.io.FileInputStream;
try{
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.
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;
try {
inputStream = new FileReader("students.txt");
outputStream = new FileWriter("characteroutput.txt");
int c;
5th Semester, Math and computing Int MSC, CET 5
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.
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.IOException;
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
JDBC Connectivity
The forName() method of Class class is used to register the driver class. This method is
used to dynamically load the driver class.
1. Class.forName("oracle.jdbc.driver.OracleDriver");
By closing connection object statement and ResultSet will be closed automatically. The
close() method of Connection interface is used to close the connection.
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
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 −
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.
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.
try {
JDBC Connectivity 6
5th Semester, Math. And computing, CET
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)
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.
Number/databaseName
Thread Scheduling
2. Types of scheduling
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() 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.
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
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:
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.
th1.start();
th2.start();
th3.start();
}
}
@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
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.
}
}
@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:
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.
}
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
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.
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
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.
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.
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.
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.
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 AwtControlDemo(){
prepareGUI();
}
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
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);
}
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
A thread is a:
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
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.
Note: The Thread and Runnable are available in the java.lang.* package
Example:
Example:
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.
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
Below diagram clearly depicts the various phases of thread life cycle in java.
Ending Thread
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