Java All Units-1
Java All Units-1
com
Unit – I
Introduction to OOPs
Object means a real-world entity such as a pen, chair, table, computer, watch,
etc. Object-Oriented Programming is a methodology or paradigm to design a program
using classes and objects. It simplifies software development and maintenance by providing
some concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
o Polymorphism
o Dynamic Binding
o Message Passing
Fig: Object Oriented Programming in Java
1
Object oriented programming in java |iv Sem [Link]
1) Object:
Any entity that has state and behavior is known as an object. For example, a chair, pen, table,
keyboard, bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class. An object contains an address and takes
up some space in memory. Objects can communicate without knowing the details of each
other's data or code. The only necessary thing is the type of message accepted and the type of
response returned by the objects.
Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.
2) Class:
A class can also be defined as a blueprint from which you can create an individual object.
Class doesn't consume any space.
3) Inheritance:
When one object acquires all the properties and behaviors of a parent object, it is known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
4) Polymorphism:
Another example can be to speak something; for example, a cat speaks meow, dog barks
woof, etc.
2
Object oriented programming in java |iv Sem [Link]
5) Abstraction:
Hiding internal details and showing functionality is known as abstraction. For example phone
call, we don't know the internal processing.
6) Encapsulation:
Binding (or wrapping) code and data together into a single unit are known as encapsulation.
For example, a capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.
7) Dynamic binding:
8) Message communication:
3
Object oriented programming in java |iv Sem [Link]
Introduction to Java
Introduction:
JAVA was developed by James Gosling at Sun Microsystems Inc in the year 1995,
later acquired by Oracle Corporation.
It is a simple programming language.
Java makes writing, compiling, and debugging programming easy. It helps to create
reusable code and modular programs.
Java is a class-based, object-oriented programming language and is designed to have
as few implementation dependencies as possible.
A general-purpose programming language made for developers to write once run
anywhere that is compiled Java code can run on all platforms that support Java.
Java applications are compiled to byte code that can run on any Java Virtual
Machine. The syntax of Java is similar to c/c++.
Java’s history is very interesting. It is a programming language created in 1991. James
Gosling, Mike Sheridan, and Patrick Naughton, a team of Sun engineers known as the
Green team initiated the Java language in 1991. Sun Microsystems released its first
public implementation in 1996 as Java 1.0. It provides no-cost -run-times on popular
platforms.
Java is the name of an island in Indonesia where the first coffee(named java coffee)
was produced. And this name was chosen by James Gosling while having coffee near
his office. Note that Java is just a name, not an acronym.
Q) What are the feature of java? Explain.
Features of Java:
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
4
Object oriented programming in java |iv Sem [Link]
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
[Link]
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to
Sun Microsystems, Java language is a simple programming language because:
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
[Link]-oriented
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
5
Object oriented programming in java |iv Sem [Link]
[Link] Independent
Java is platform independent because it is different from other languages like C, C++, etc.
which are compiled into platform specific machines while Java is a write once, run anywhere
language. A platform is the hardware or software environment in which a program runs.
There are two types of platforms software-based and hardware-based. Java provides a
software-based platform.
The Java platform differs from most other platforms in the sense that it is a software-based
platform that runs on top of other hardware-based platforms. It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris,
Mac/OS, etc. Java code is compiled by the compiler and converted into bytecode. This
bytecode is a platform-independent code because it can be run on multiple platforms, i.e.,
Write Once and Run Anywhere (WORA).
[Link]
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't
require any implementation.
[Link]
Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
6
Object oriented programming in java |iv Sem [Link]
Java language provides these securities by default. Some security can also be provided by an
application developer explicitly through SSL, JAAS, Cryptography, etc.
[Link]
7
Object oriented programming in java |iv Sem [Link]
[Link]-neutral
Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4
bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32
and 64-bit architectures in Java.
[Link]
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't
require any implementation.
[Link]-performance
Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g.,
C++). Java is an interpreted language that is why it is slower than compiled languages, e.g.,
C, C++, etc.
[Link]
Java is distributed because it facilitates users to create distributed applications in Java. RMI
and EJB are used for creating distributed applications. This feature of Java makes us able to
access files by calling the methods from any machine on the internet.
[Link]-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that
deal with many tasks at once by defining multiple threads. The main advantage of multi-
threading is that it doesn't occupy memory for each thread. It shares a common memory area.
Threads are important for multi-media, Web applications, etc.
8
Object oriented programming in java |iv Sem [Link]
[Link]
Java is a dynamic language. It supports the dynamic loading of classes. It means classes are
loaded on demand. It also supports functions from its native languages, i.e., C and C++.
Java supports dynamic compilation and automatic memory management (garbage collection).
9
Object oriented programming in java |iv Sem [Link]
Java naming convention is a rule to follow as you decide what to name your identifiers such
as class, package, variable, constant, method, etc.
But, it is not forced to follow. So, it is known as convention not rule. These conventions are
suggested by several Java communities such as Sun Microsystems and Netscape.
The following table shows the popular conventions used for the different identifiers.
Class It should start with the uppercase letter. public class Employee
It should be a noun such as Color, Button, System, {
Thread,etc. //code snippet
Use appropriate words, instead of acronyms. }
10
Object oriented programming in java |iv Sem [Link]
Variable It should start with a lowercase letter such as id, name. class Employee
It should not start with the special characters like & {
(ampersand),$(dollar),_(underscore). // variable
If the name contains multiple words, start it with the int id;
lowercase letter followed by an uppercase letter such as //code snippet
firstName,lastName. }
Avoid using one-character variables such as x, y, z.
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.
11
Object oriented programming in java |iv Sem [Link]
A primitive data type specifies the size and type of variable values, and it has no additional
methods.
They are:
o Boolean data type
o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double data type
Integer type:
12
Object oriented programming in java |iv Sem [Link]
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:
The float data type is a single-precision 32-bit IEEE 754 floating [Link] 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.
13
Object oriented programming in java |iv Sem [Link]
Example:
float f1 = 234.5f
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.
char
The char data type is a single 16-bit Unicode character.
Syntax:
char charVar;
Size: 2 byte (16 bits)
Here is an example of the Hello Java program to understand the class structure and features.
There are a few lines in the program, and the primary task of the program is to print Hello
Java text on the screen.
14
Object oriented programming in java |iv Sem [Link]
Program Output:
Hello Java
Here are the most important points to note about the Java programs:
Comments :
which will be helpful for developers to understand the existing code in the future easily.
Braces:
15
Object oriented programming in java |iv Sem [Link]
Two curly brackets {...} are used to group all the commands, so it is known that the
commands belong to that class or method.
When the main method is declared public, it means that it can also be used by code
outside of its class, due to which the main method is declared public.
The word static used when we want to access a method without creating its object, as
we call the main method, before creating any class objects.
The word void indicates that a method does not return a value. main() is declared as
void because it does not return a value.
main is a method; this is a starting point of a Java program.
You will notice that the main method code has been moved to some spaces left. It is
called indentation which used to make a program easier to read and understand.
String[] args:
It is an array where each element of it is a string, which has been named as "args". If your
Java program is run through the console, you can pass the input parameter, and main()
method takes it as input.
[Link]();
This statement is used to print text on the screen as output, where the system is a predefined
class, and out is an object of the PrintWriter class defined in the system. The
method println prints the text on the screen with a new line. You can also use print() method
instead of println() method. All Java statement ends with a semicolon.
Program Output:
Hello Java
16
Object oriented programming in java |iv Sem [Link]
Scanner class in Java is found in the [Link] package. Java provides various ways to
read input from the keyboard, the [Link] class is one of them.
The Java Scanner class is widely used to parse text for strings and primitive types
using a regular expression.
It is the simplest way to get input in Java. By the help of Scanner in Java, we can get
input from the user in primitive types such as int, long, double, byte, float, short, etc.
To get the instance of Java Scanner which reads input from the user, we need to pass
the input stream ([Link]) in the constructor of Scanner class.
For Example:
To get the instance of Java Scanner which parses the strings, we need to pass the strings in
the constructor of Scanner class. For Example:
Example programme:
import [Link];
class Hello{
public static void main(String args[])
{
[Link]("Your name is:");
Scanner a= new Scanner([Link]);
String name=[Link]();
[Link]("Your name is:" + name);
}
}
17
Object oriented programming in java |iv Sem [Link]
Example:
class Example
There are three easy steps for successfully executing the Java program:
1. Entering the Source Code The above program can be written in any text editor (like
Notepad) but make sure it is written exactly the same way it is shown.
2. Saving the Source Code Now that you’ve written the code in Notepad, this is how you’ll
save it.
3. Compiling and Running the Source Java programs are compiled using DOS. For
opening OS, type cmd at the run prompt and move to the folder that contains the saved
[Link] file. Now compile the program using javac, specifying the name of the source
file on the command line as shown below. (Assuming the file was saved in a folder ‘javaeg’
in the C drive.)
C:\javaeg\>javac [Link]
18
Object oriented programming in java |iv Sem [Link]
The javac compiler creates a file called Example. Class (in the same directory). This class
contains the bytecode version of the program.
This bytecode will be executed by the Java interpreter using java followed by the class name
as shown below.
C:\javaeg\>java Example
Output
Variable =constant;
Examples
(a) int a;
19
Object oriented programming in java |iv Sem [Link]
a = 10;
a = b;
c = a + b;
The arithmetic operators are used to perform arithmetic operations like addition,
subtraction, multiplication, division.
Here variables and constants are called operands symbols are operators.
Note: the + operator can be used for two purposes: concatenation and addition in the print
statements
20
Object oriented programming in java |iv Sem [Link]
The resultant condition (c1& &c2) is true only when both the conditions c1 and c2 are true.
Otherwise it will be false.
Logical OR (||):
The resultant condition (c1 || c2 ) is false, only when both the conditions c1 and c2 are false.
Otherwise it will be true.
C1 !C1
T F
F T
Here c1 is simply negated (Reverse).
21
Object oriented programming in java |iv Sem [Link]
Example:
a=6, b=8
(a>b)? a: b
If the both bits of op1 and op2 are both 1’s then the bit in the corresponding position of
the result would be 1, otherwise, it would be 0.
22
Object oriented programming in java |iv Sem [Link]
Bitwise OR ( | ) :
If the corresponding bits of op1 and op2 are both 0’s then the bit in the corresponding
position of the result would be 0, otherwise, it would be 1.
op1 | op2
If any one of the bits of operation 1 and operation 2 is 1 then the bit in the
corresponding position of the result would be 1, otherwise, it would be 0.
op1 ^ op2
Left shift operator is used to shift the bits into left side.
Ex:
0000010
0001000
23
Object oriented programming in java |iv Sem [Link]
Bitwise AND operator is used to set the bit as if both bits are 1 the corresponding bit is
1 and otherwise o.
Ex:
Instance of operator
instance of operator
The instance of the operator is used for type checking. It can be used to test if an object is
an instance of a class, a subclass, or an interface. General format-
object instance of class/subclass/interface
This operator allows us to determine whether the object belongs to a particular class
or not.
Member selection operator/ Dot operator:
The dot operator (.) is used to access the instance variables and methods of class
objects.
Q) Explain about the command line arguments in java?
The application is invoked from the command line and the arguments are also passed
to the application at the command line itself, these are called command-line
arguments.
The main() method of java is public static void main(String args[]).
The main() is declared, with an array variable, args, referring to an array of strings,
passed as command line arguments to the program.
Ex:
class Echo
int x = [Link];
24
Object oriented programming in java |iv Sem [Link]
[Link](args[i]);
After compiling the program, when it is executed, you can pass the command-line
arguments as follows:
C>java Echo A B C
Output
Example:
int a=10
A. Numerical Constants
B. Real Constants
C. Character constants
A. Numeric Constants
Numeric constants are refers to it consist of numerals, an optional sign and an optional
period.
They are further classified into two types:
Integer constants:
25
Object oriented programming in java |iv Sem [Link]
These are further classified into three types depending on the number systems they belong
to. They are:
(i) Decimal integer constants.
(a) It is a sequence of one or more digits [0…9,] the symbols of decimal number
system.
(a) It is a sequence of one or more digits [0…7, symbols of octal number system]
(a) It is a sequence of one or more symbols [0…9, A...Z, a...z, the symbols of
hexadecimal number system]
B. Real Constants
The real constants are also known as floating point constants are written as follows:
(a) They must have at least one digit and a decimal point.
Example:
346.67
-965.23
C. Character Constants
A single character constant consists of only one character and it is enclosed within a
pair of single quotes. For example,
String constant:
26
Object oriented programming in java |iv Sem [Link]
A string constant consists of one or more characters and it is enclosed within a pair of
double quotes. For example,
Java supports some special backslash character constants that are used in output
methods. For example, the symbol ‘\n’ stands for newline character. A list of such backslash
character constants is given in Table
27
Object oriented programming in java |iv Sem [Link]
Unit-2
28
Object oriented programming in java |iv Sem [Link]
Unit-2
Control Statements in Java: if... else, do... while Loop, while Loop, for loop, Switch
Statement, break Statement, continue Statement
Arrays: Types of Arrays, array name, length,
Strings: Creating Strings, String Class Methods, String Comparison, Immutability of Strings.
If Statement:
In Java, the "if" statement is used to evaluate a condition.
The control of the program is diverted depending upon the specific condition.
The condition of the If statement gives a Boolean value, either true or false. In Java, there are
four types of if-statements given below. Concepts in Java
1. Simple if statement
2. if-else statement
3. if-else-if ladder
29
Object oriented programming in java |iv Sem [Link]
4. Nested if-statement
Let's understand the if-statements one by one.
1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a
Boolean expression and enables the program to enter a block of code if the expression
evaluates to true.
Syntax of if statement is given below.
1. if(condition) {
2. statement 1; //executes when condition is true
3. }
Consider the following example in which we have used the if statement in the java code.
[Link]
[Link]
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
[Link]("x + y is greater than 20");
}
}
}
Output:
x + y is greater than 20
2) if-else statement
The if-else statement is an extension to the if-statement, which uses another block of code,
i.e., else block. The else block is executed if the condition of the if-block is evaluated as false.
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
Consider the following example.
[Link]
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y< 10) {
[Link]("x + y is less than 10");
}
else {
[Link]("x + y is greater than 20");
30
Object oriented programming in java |iv Sem [Link]
}
}
}
Output:
x + y is greater than 20
3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if
statements.
The chain of if-else statements that create a decision tree where the program may
enter in the block of code where the condition is true. We can also define an else
statement at the end of the chain.
Syntax of if-else-if statement is given below.
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
Consider the following example.
[Link]
class Student {
public static void main(String[] args)
{
int marks=75;
if(marks>=90) {
[Link]("First");
}
else if(marks>=75) {
[Link]("Second");
}
else if (marks>=50) {
[Link]("Third");
}
else if(marks>=35) {
[Link]("pass");
}
else if(marks<35) {
[Link]("fail");
}
else{
[Link]("invalid marks")
}
}
}
Output:
31
Object oriented programming in java |iv Sem [Link]
Second
4. Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside another if
or else-if statement.
Syntax of Nested if-statement is given below.
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}
Consider the following example.
[Link]
public class Student {
public static void main(String[] args) {
if(marks>35){
if(marks>=75){
[Link]("They can pay fee only 50%");
}
else{
[Link]("They have to pay full fee");
}
}
}
}
Output:
They can pay fee only 50%
Switch Statement:
In Java, Switch statements are similar to if-else-if statements.
The switch statement contains multiple blocks of code called cases and a single case
is executed based on the variable which is being switched.
The switch statement is easier to use instead of if-else-if statements.
It also enhances the readability of the program.
Points to be noted about switch statement:
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of
expression. It is optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
The syntax to use the switch statement is given below.
switch (expression){
case value1:
statement1;
break;
.
32
Object oriented programming in java |iv Sem [Link]
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Consider the following example to understand the flow of the switch statement.
[Link]
public class Student implements Cloneable {
public static void main(String[] args) {
int num = 2;
switch (num){
case 0:
[Link]("number is 0");
break;
case 1:
[Link]("number is 1");
break;
default:
[Link](num);
}
}
}
Output:
2
While using switch statements, we must notice that the case expression will be of the same
type as the variable. However, it will also be a constant value. The switch permits only int,
string, and Enum type variables to be used.
Q) What are the Loop Statements and explain?
In programming, sometimes we need to execute the block of code repeatedly while some
condition evaluates to true. However, loop statements are used to execute the set of
instructions in a repeated order. The execution of the set of instructions depends upon a
particular condition.
In Java, we have three types of loops that execute similarly. However, there are differences in
their syntax and condition checking time.
1. for loop
2. while loop
3. do-while loop
33
Object oriented programming in java |iv Sem [Link]
It enables us to initialize the loop variable, check the condition, and increment/decrement in a
single line of code. We use the for loop only when we exactly know the number of times, we
want to execute the block of code.
1. for(initialization, condition, increment/decrement) {
2. //block of statements
3. }
Consider the following example to understand the proper functioning of the for loop in java.
[Link]
class Calculation {
public static void main(String[] args) {
// It will generate 1 to 10 numbers
for (int j = 1; j<=10; j++) {
[Link](j);
}
}
}
Output:
1 2 3 4 5 6 7 8 9 10
34
Object oriented programming in java |iv Sem [Link]
The flow chart for the while loop is given in the following image.
Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10
35
Object oriented programming in java |iv Sem [Link]
It is also known as the exit-controlled loop since the condition is not checked in advance. The
syntax of the do-while loop is given below.
do
{
//statements
} while (condition);
The flow chart of the do-while loop is given in the following image.
Consider the following example to understand the functioning of the do-while loop in Java.
[Link]
public class Calculation {
public static void main(String[] args) {
// It will generate the 1 to 10 even numbers
int i = 0;
[Link]("Printing the list of first 10 even numbers \n");
do {
[Link](i);
i = i + 2;
}while(i<=10);
}
}
Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10
36
Object oriented programming in java |iv Sem [Link]
Jump statements are used to transfer the control of the program to the specific statements. In
other words, jump statements transfer the execution control to the other part of the program.
There are two types of jump statements in Java, i.e.,
1)break
2)continue.
1) Java break statement
The break statement cannot be used independently in the Java program, i.e., it can only be
written inside the loop or switch statement.
Consider the following example in which we have used the break statement with the for loop.
[Link]
public class BreakExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i<= 10; i++) {
[Link](i);
if(i==6) {
break;
}
}
}
}
Output:
0
1
2
3
4
5
6
37
Object oriented programming in java |iv Sem [Link]
Unlike break statement, The Continue statement doesn't break the loop, whereas, it skips the
specific part of the loop and jumps to the next iteration of the loop immediately.
Consider the following example to understand the functioning of the continue statement in
Java.
public class ContinueExample {
Output:
1 2 3 4 5 6 7 8 9 10
38
Object oriented programming in java |iv Sem [Link]
Java Arrays:
Q) What is the java Arrays and explain?
Normally, an array is a collection of similar type of elements which has contiguous memory
location.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on
In Java, array is an object of a dynamically generated class. Java array inherits the Object
class, and implements the Serializable as well as Cloneable interfaces. We can store primitive
values or objects in an array in Java. Like C/C++, we can also create single dimensional or
multidimensional arrays in Java.
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It doesn't grow
its size at runtime. To solve this problem, collection framework is used in Java which
grows automatically.
39
Object oriented programming in java |iv Sem [Link]
Q) What are types of arrays in java Explain? Or what is 1-D and 2-D arrays in
java?
Types of Array in java
There are two types of array.
o Single Dimensional Array
o Multidimensional Array
In such case, data is stored in row and column-based index (also known as matrix form).
Syntax to Declare Multidimensional Array in Java
1. dataType[][] arrayRefVar; (or)
2. dataType [][]arrayRefVar; (or)
40
Object oriented programming in java |iv Sem [Link]
41
Object oriented programming in java |iv Sem [Link]
Java String
In Java string is basically an object that represents sequence of char values. An array
1. char[] ch={‘v’,’i’,’s’,’w’,’a’,’m’};
2. String s=new String(ch);
is same as:
1. String s="viswam";
Java String class provides a lot of methods to perform operations on strings such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring()
etc.
CharSequence Interface
and StringBuilder
classes implement it. It means, we can create strings in Java by using these three classes.
42
Object oriented programming in java |iv Sem [Link]
The Java String is immutable which means it cannot be changed. Whenever we change any
string, a new instance is created. For mutable strings, you can use StringBuffer and
StringBuilder classes.
We will discuss immutable string later. Let's first understand what String in Java is and how
to create the String object.
1. By string literal
2. By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
1. String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first. If the
string already exists in the pool, a reference to the pooled instance is returned. If the string
doesn't exist in the pool, a new string instance is created and placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance
43
Object oriented programming in java |iv Sem [Link]
In the above example, only one object will be created. Firstly, JVM will not find any string
object with the value "Welcome" in string constant pool that is why it will create a new
object. After that it will find the string with the value "Welcome" in the pool, it will not
create a new object but will return the reference to the same instance.
Note: String objects are stored in a special memory area known as the "string constant pool".
2) By new keyword
1. String s=new String("Welcome");//creates two objects and one reference variable
will create a new string object in normal (non-pool) heap memory, and the literal "Welcome" will be
placed in the string constant pool. The variable s will refer to the object in a heap (non-pool).
44
Object oriented programming in java |iv Sem [Link]
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating Java string by new keyword
[Link](s1);
[Link](s2);
[Link](s3);
}}
Output:
java
strings
example
The above code, converts a char array into a String object. And displays the String
objects s1, s2, and s3 on console using println() method.
A String is an unavoidable type of variable while writing any application program. String
references are used to store various attributes like username, password, etc. In Java, String
objects are immutable. Immutable simply means unmodifiable or unchangeable.
Once String object is created its data or state can't be changed but a new String object is
created.
Let's try to understand the concept of immutability by the example given below:
[Link]
class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
[Link](" Tendulkar");//concat() method appends the string at the end
[Link](s);//will print Sachin because strings are immutable objects
}
}
Output:
Sachin
45
Object oriented programming in java |iv Sem [Link]
Now it can be understood by the diagram given below. Here Sachin is not changed but a new
object is created with Sachin Tendulkar. That is why String is known as immutable.
As you can see in the above figure that two objects are created but s reference variable still
refers to "Sachin" not to "Sachin Tendulkar".
But if we explicitly assign it to the reference variable, it will refer to "Sachin Tendulkar"
object.
For example:
[Link]
class Testimmutablestring1{
public static void main (String args[]){
String s="Sachin";
s=[Link](" Tendulkar");
[Link](s);
}
}
Output:
Sachin Tendulkar
In such a case, s points to the "Sachin Tendulkar". Please notice that still Sachin object is not
modified.
46
Object oriented programming in java |iv Sem [Link]
As Java uses the concept of String literal. Suppose there are 5 reference variables, all refer to
one object "Sachin". If one reference variable changes the value of the object, it will be
affected by all the reference variables. That is why String objects are immutable in Java.
Following are some features of String which makes String objects immutable.
1. ClassLoader:
2. Thread Safe
3. Security
4. Heap Space
The String class equals() method compares the original content of the string. It compares
values of string for equality. String class provides the following two methods. Java
o public boolean equals(Object another) compares this string to the specified object.
o public boolean equalsIgnoreCase(String another) compares this string to another
string, ignoring case.
[Link]
class Teststringcomparison2{
public static void main(String args[]){
String s1="Sachin";
String s2="SACHIN";
[Link]([Link](s2));//false
[Link]([Link](s2));//true
}
}
47
Object oriented programming in java |iv Sem [Link]
Output:
false
true
In the above program, the methods of String class are used. The equals() method returns true
if String objects are matching and both strings are of same case. equalsIgnoreCase() returns
true regardless of cases of strings.
2) By Using == operator
[Link]
class Teststringcomparison3{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
[Link](s1==s2);//true (because both refer to same instance)
[Link](s1==s3);//false(because s3 refers to instance created in nonpool)
}
}
Output:
true
false
The String class compareTo() method compares values lexicographically and returns an
integer value that describes if first string is less than, equal to or greater than second string.
48
Object oriented programming in java |iv Sem [Link]
[Link]
class Teststringcomparison4{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
[Link]([Link](s2));//0
[Link]([Link](s3));//1(because s1>s3)
[Link]([Link](s1));//-1(because s3 < s1 )
}
}
Output:
0
1
-1
49
IV-sem|JAVA_Unit-3
Unit -3
Classes and Objects: Object Creation, Initializing the Instance Variables, Access Specifiers,
Constructors
Inheritance: Inheritance, Types of Inheritance
Polymorphism: Method overloading, Operator overloading
Abstract Classes: Abstract Method and Abstract Class
o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface
Object:
An object in Java is the physical as well as a logical entity, whereas, a class in Java is a
logical entity only.
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). The example of an intangible object is the banking system.
They are:
1. State
2. Behavior
3. Identity
P a g e 1 | 22
IV-sem|JAVA_Unit-3
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.
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:
Q) What are the different ways to initialize object in java? Or How to create object and
explain?
Object class in Java
The Object class is the parent class of all the classes in java by default. In other words, it is the
topmost class of java.
The Object class is beneficial if you want to refer any object whose type you don't know. Notice
that parent class reference variable can refer the child class object, know as upcasting.
Let's take an example, there is getObject() method that returns an object but it can be of any
type like Employee,Student etc, we can use Object class reference to refer that object. For
example:
1. Object obj=getObject();//we don't know what object will be returned from this method
The Object class provides some common behaviors to all the objects such as object can be
compared, object can be cloned, object can be notified etc.
P a g e 2 | 22
IV-sem|JAVA_Unit-3
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: [Link]
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
[Link]=101;
[Link]="Sonoo";
[Link]([Link]+" "+[Link]);//printing members with a white space
}
}
Output:
101 Sonoo
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: [Link]
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){[Link](rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
[Link](111,"Karan");
P a g e 3 | 22
IV-sem|JAVA_Unit-3
[Link](222,"Aryan");
[Link]();
[Link]();
}
}
Output:
111 Karan
222 Aryan
As you can see in the above figure, object gets the memory in heap memory area. The reference
variable refers to the object allocated in the heap memory area. Here, s1 and s2 both are
reference variables that refer to the objects allocated in memory.
File: [Link]
class Employee{
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s;
}
void display(){[Link](id+" "+name+" "+salary);}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1=new Employee();
P a g e 4 | 22
IV-sem|JAVA_Unit-3
In any programming language, the program needs identifiers for storing different values that
can be used throughout the program. These identifiers are variables.
Variable in Java
o A variable is a name assigned to a value that is stored inside the system memory. The
value can be updated during the program execution.
o In Java programming, the variables used for the program need to declare them first.
o The variable is declared using a data type followed by the identifier name. The variable
can be initialized at the time of declaration or it can be assigned a value taken from the
user during the program execution.
o There are basically three types of variables in Java,
1. Java Local variable
2. Java Instance variable
3. Java Static variable / Java class variable
P a g e 5 | 22
IV-sem|JAVA_Unit-3
Features
1. To use an instance variable an object of the class must be created.
2. An instance variable is destroyed when the object it is associated with is destroyed.
3. An instance variable does not compulsory need to be initialized.
4. Instance variables are accessible inside the same class that declares them.
Q) What is the Access specifiers in java? Or What are the Access Modifiers in java?
Explain.
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.
1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
P a g e 6 | 22
IV-sem|JAVA_Unit-3
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. Here, we are going to learn the access modifiers [Link] Tutorial
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
1) Private
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(){[Link]("Hello java");}
}
P a g e 7 | 22
IV-sem|JAVA_Unit-3
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(){[Link]("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
Note: A class cannot be private or protected except nested class.
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.
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 [Link]
package pack;
class A{
void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
[Link]();//Compile Time Error
P a g e 8 | 22
IV-sem|JAVA_Unit-3
}
}
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 [Link]
package pack;
public class A{
protected void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
[Link]();
}
}
Output:Hello
4) Public
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
P a g e 9 | 22
IV-sem|JAVA_Unit-3
//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
Output:Hello
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.
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.
[Link] 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.
P a g e 10 | 22
IV-sem|JAVA_Unit-3
Output:
Bike is created
Rule: If there is no constructor in a class, compiler automatically creates a default
constructor.
P a g e 11 | 22
IV-sem|JAVA_Unit-3
The parameterized constructor is used to provide different values to distinct objects. However,
you can provide the same values also.
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.
P a g e 12 | 22
IV-sem|JAVA_Unit-3
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 superclass, and the
new class is called child or subclass.
P a g e 13 | 22
IV-sem|JAVA_Unit-3
As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
The relationship between the two classes is Programmer IS-A Employee. It means that
Programmer is a type of Employee.
Example:
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
[Link]("Programmer salary is:"+[Link]);
[Link]("Bonus of Programmer is:"+[Link]);
}
}
Output:
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.
P a g e 14 | 22
IV-sem|JAVA_Unit-3
In java programming, multiple and hybrid inheritance is supported through interface only. We
will learn about interfaces later.
When one class inherits multiple classes, it is known as multiple inheritance. For 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: [Link]
class Animal{
void eat(){[Link]("eating...");}
P a g e 15 | 22
IV-sem|JAVA_Unit-3
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
[Link]();
}}
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: [Link]
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class BabyDog extends Dog{
void weep(){[Link]("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
[Link]();
[Link]();
[Link]();
}}
P a g e 16 | 22
IV-sem|JAVA_Unit-3
Output:
weeping...
barking...
eating...
Hierarchical Inheritance Example
When two or more classes inherits a single class, it is known as hierarchical inheritance. In
the example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical
inheritance.
File: [Link]
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class Cat extends Animal{
void meow(){[Link]("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
[Link]();
[Link]();
//[Link]();//[Link]
}}
Output:
meowing...
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.
P a g e 17 | 22
IV-sem|JAVA_Unit-3
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(){[Link]("Hello");}
}
class B{
void msg(){[Link]("Welcome");}
}
class C extends A,B{//suppose if it were
Polymorphism:
Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many
and "morphs" means forms. So polymorphism means many forms.
Method Overloading:
multiple methods can have the same name with different parameters is called
Method overloading.
Method Overriding:
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java
P a g e 18 | 22
IV-sem|JAVA_Unit-3
Output:
60
150
P a g e 19 | 22
IV-sem|JAVA_Unit-3
Operator overloading:
Operator overloading is the ability to redefine the functionality of the operators. Programming
languages like c++ supports operator overloading.
you can redefine or overload most of the built-in operators available in C++. Thus, a
programmer can use operators with user-defined types as well.
Overloaded operators are functions with special names: the keyword "operator" followed by
the symbol for the operator being defined. Like any other function, an overloaded operator has
a return type and a parameter list.
Java does not support operator overloading due to the following reasons −
Data abstraction is the process of hiding certain details and showing only
essential information to the user.
Abstraction can be achieved with either abstract classes.
Abstract class:
Abstract method:
Abstract method can only be used in an abstract class, and it does not
have a body. The body is provided by the subclass (inherited from).
P a g e 20 | 22
IV-sem|JAVA_Unit-3
[Link]("Zzz");
From the example above, it is not possible to create an object of the Animal
class:
To access the abstract class, it must be inherited from another class. Let's
convert the Animal class we used in the Polymorphism chapter to an abstract
class:
Remember from the Inheritance chapter that we use the extends keyword to
inherit from a class.
Example:
// Abstract class
// Regular method
[Link]("Zzz");
P a g e 21 | 22
IV-sem|JAVA_Unit-3
class Main {
[Link]();
[Link]();
Output:
P a g e 22 | 22
Unit_IV Object oriented programming with Java IV-sem | Bcom
Unit-4
Packages: Package, Different Types of Packages, Creating Package and Accessing a Package
Streams: Stream classes, Creating a File using File Output Stream, Reading Data from a File
using File Input Stream, Creating a File using File Writer, Reading a File using File Reader
Java Package:
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined
packages.h2eview: The biggest upgrades in years
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
A package in Java is used to group related classes. Think of it as a folder in a file directory.
We use packages to avoid name conflicts, and to write a better maintainable code. Packages
are divided into two categories:
Built-in packages:
These are the packages which are already available in Java language. These packages
provide all most all necessary classes, interfaces and methods for the programmer to
perform any task in his programs.
P a g e 1 | 20
Unit_IV Object oriented programming with Java IV-sem | Bcom
[Link]:
lang stands for language. This package got primary classes and interfaces essential for
developing a basic Java program. There are classes like String, StringBuffer, classes to
handle strings. There is a Thread class to create various individual processes. Runtime and
System classes are also present in [Link] package which contain methods to execute an
application.
[Link]:
util stands for utility. This package contains useful classes and interfaces like Stack,
LinkedList, Hashtable, Vector, Arrays, etc..
[Link]:
io stands for input and output. This package contains streams. A stream represents flow
of data from one place to another place. Streams are useful to store data in the form of files
and also to perform input-output related tasks.
[Link]:
awt stands for abstract window toolkit. This helps to develop GUI (Graphical user
Interfaces) where programs with colorful screens, paintings and images etc., can be
developed.
[Link]:
This package helps to develop GUI like [Link]. The ‘x‘ in javax represents that it is
an extended package which means it is a package developed from another package by
adding new features to it. In fact, [Link] is an extended package of [Link].
[Link]:
net stands for network. Client-Server programming can be done by using this package.
Classes related to creating sockets at client and server to establish communication between
them are available in [Link] package.
[Link]:
applets are programs which come from a server into a client and get executed on the
client machine on a network. Applet class of this package is useful to create and use applets.
[Link]:
This package has two important classes, Date Format to format dates and times, and
NumberFormat which is useful to format numeric values.
[Link]:
sql stands structured query language. This package helps to connect to databases like
Oracle or Sybase, retrieve the data from them and use it in a Java program.
3) What is packages? and Explain it Types.
A package in Java is used to group related classes. Think of it as a folder in a file directory.
We use packages to avoid name conflicts, and to write a better maintainable code. Packages
are divided into two categories:
P a g e 2 | 20
Unit_IV Object oriented programming with Java IV-sem | Bcom
1.)Built-in Packages
The Java API is a library of prewritten classes, that are free to use, included in the Java
Development Environment.
The library contains components for managing input, database programming, and much much
more.
The library is divided into packages and classes. Meaning you can either import a single
class (along with its methods and attributes), or a whole package that contain all the classes
that belong to the specified package.
To use a class or a package from the library, you need to use the import keyword:
Syntax
Import a Class
If you find a class you want to use, for example, the Scanner class, which is used to get user
input, write the following code:
Example
import [Link];
In the example above, [Link] is a package, while Scanner is a class of the [Link] package.
To use the Scanner class, create an object of the class and use any of the available methods
found in the Scanner class documentation. In our example, we will use
the nextLine() method, which is used to read a complete line:
Example
import [Link];
class MyClass {
[Link]("Enter username");
P a g e 3 | 20
Unit_IV Object oriented programming with Java IV-sem | Bcom
Output:
Enter username
Bcom
Import a Package
There are many packages to choose from. In the previous example, we used the Scanner class
from the [Link] package. This package also contains date and time facilities, random-
number generator and other utility classes.
To import a whole package, end the sentence with an asterisk sign (*). The following
example will import ALL the classes in the [Link] package:
Example
import [Link].*;
2)User-defined Packages
To create your own package, you need to understand that Java uses a file system directory to
store them. Just like folders on your computer:
Example
└── root
└── mypack
└── [Link]
[Link]
package mypack;
class MyPackageClass {
[Link]("This is my package!");
P a g e 4 | 20
Unit_IV Object oriented programming with Java IV-sem | Bcom
The -d keyword specifies the destination for where to save the class file. You can use any
directory name, like c:/user (windows), or, if you want to keep the package within the same
directory, you can use the dot sign ".", like in the example above.
Note: The package name should be written in lower case to avoid conflict with class names.
When we compiled the package in the example above, a new folder was created, called
"mypack".
This is my package!
There are three ways to access the package from outside the package.
1. import package.*;
2. import [Link];
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but
not subpackages.
The import keyword is used to make the classes and interface of another package accessible to
the current package.
P a g e 5 | 20
Unit_IV Object oriented programming with Java IV-sem | Bcom
//save by [Link]
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
Output:Hello
2) Using [Link]
If you import [Link] then only declared class of this package will be accessible.
//save by [Link]
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
P a g e 6 | 20
Unit_IV Object oriented programming with Java IV-sem | Bcom
[Link]();
}
}
Output:Hello
If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.
It is generally used when two packages have same class name e.g. [Link] and [Link]
packages contain Date class.
If you import a package, all the classes and interface of that package will be imported excluding
the classes and interfaces of the subpackages. Hence, you need to import the subpackage as
well.
Note: Sequence of the program must be package then import then class.
P a g e 7 | 20
Unit_IV Object oriented programming with Java IV-sem | Bcom
If you find a class you want to use, for example, the Scanner class, which is used to get user
input, write the following code:
Example
import [Link];
In the example above, [Link] is a package, while Scanner is a class of the [Link] package.
To use the Scanner class, create an object of the class and use any of the available methods
found in the Scanner class documentation. In our example, we will use
the nextLine() method, which is used to read a complete line:
Example
import [Link];
class MyClass {
[Link]("Enter username");
Output:
Enter username
Bcom
P a g e 8 | 20
Unit_IV Object oriented programming with Java IV-sem | Bcom
Import a Package
There are many packages to choose from. In the previous example, we used the Scanner class
from the [Link] package. This package also contains date and time facilities, random-
number generator and other utility classes.
To import a whole package, end the sentence with an asterisk sign (*). The following
example will import ALL the classes in the [Link] package:
Example
import [Link].*;
Streams: Stream classes, Creating a File using File Output Stream, Reading Data from a
File using File Input Stream, Creating a File using File Writer, Reading a File using File
Reader
Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O system
to make input and output operation in java. A stream can be defined as a sequence of data.
The InputStream is used to read data from a source and the OutputStream is used for writing
data to a destination. InputStream and OutputStream are the basic stream classes in Java.
Types of streams:
Byte Stream : It provides a convenient means for handling input and output of
byte.
P a g e 9 | 20
Unit_IV Object oriented programming with Java IV-sem | Bcom
Character Stream : It provides a convenient means for handling input and output
of characters. Character stream uses Unicode and therefore can be
internationalized.
1. Byte Stream:
Byte Stream Classes are used to read bytes from an input stream and write bytes to an output
stream.
P a g e 10 | 20
Unit_IV Object oriented programming with Java IV-sem | Bcom
2. Character Stream:
Character stream is also defined by using two abstract classes at the top of the hierarchy, they
are Reader and Writer. These two abstract classes have several concrete classes that handle
Unicode characters.
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream
because it is like a stream of water that continues to flow.
In Java, 3 streams are created for us automatically. All these streams are attached with the
console.
P a g e 11 | 20
Unit_IV Object oriented programming with Java IV-sem | Bcom
Let's see the code to print output and an error message to the console.
1. [Link]("simple message");
2. [Link]("error message");
OutputStream vs InputStream
OutputStream
Java application uses an output stream to write data to a destination; it may be a file, an array,
peripheral device or socket.
InputStream
Java application uses an input stream to read data from a source; it may be a file, an array,
peripheral device or socket.
Let's understand the working of Java OutputStream and InputStream by the figure given below.
P a g e 12 | 20
Unit_IV Object oriented programming with Java IV-sem | Bcom
OutputStream class
OutputStream class is an abstract class. It is the superclass of all classes representing an output
stream of bytes. An output stream accepts output bytes and sends them to some sink.
1) public void write(int)throws IOException is used to write a byte to the current output stream.
2) public void write(byte[])throws is used to write an array of byte to the current output
IOException stream.
4) public void close()throws IOException is used to close the current output stream.
OutputStream Hierarchy
AD
InputStream class
InputStream class is an abstract class. It is the superclass of all classes representing an input
stream of bytes.
P a g e 13 | 20
Unit_IV Object oriented programming with Java IV-sem | Bcom
1) public abstract int read()throws reads the next byte of data from the input stream. It returns
IOException -1 at the end of the file.
2) public int available()throws returns an estimate of the number of bytes that can be read
IOException from the current input stream.
InputStream Hierarchy
6) How to create a file by using java FileOutputStream and Reading Data from a File
using File Input Stream?
If you have to write primitive values into a file, use FileOutputStream class. You can write
byte-oriented as well as character-oriented data through FileOutputStream class. But, for
character-oriented data, it is preferred to use FileWriter than FileOutputStream.
protected void finalize() It is used to clean up the connection with the file output stream.
void write(byte[] ary) It is used to write [Link] bytes from the byte array to the file output
stream.
void write(byte[] ary, int off, It is used to write len bytes from the byte array starting at offset off to
int len) the file output stream.
void write(int b) It is used to write the specified byte to the file output stream.
FileChannel getChannel() It is used to return the file channel object associated with the file output
stream.
FileDescriptor getFD() It is used to return the file descriptor associated with the stream.
Output:
Success...
P a g e 15 | 20
Unit_IV Object oriented programming with Java IV-sem | Bcom
[Link]
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.
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 [Link] bytes of data from the input stream.
int read(byte[] b, int off, It is used to read up to len bytes of data from the input stream.
int len)
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 with the
getChannel() file input stream.
P a g e 16 | 20
Unit_IV Object oriented programming with Java IV-sem | Bcom
protected void finalize() It is used to ensure that the close method is call when there is no more
reference to the file input stream.
[Link]();
}catch(Exception e){[Link](e);}
}
}
Note: Before running the code, a text file named as "[Link]" is required to be created. In
this file, we are having following content:
Welcome to SVU.
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.
Output:
W
AD
7) How to Creating a File using File Writer and Reading a File using File
Reader?
Unlike FileOutputStream class, you don't need to convert string into byte array because it
provides method to write string directly.
P a g e 17 | 20
Unit_IV Object oriented programming with Java IV-sem | Bcom
FileWriter(File file) Creates a new file. It gets file name in File object.
AD
In this example, we are writing the data in the file [Link] using Java FileWriter class.
package [Link];
import [Link];
public class FileWriterExample {
P a g e 18 | 20
Unit_IV Object oriented programming with Java IV-sem | Bcom
Output:
Success...
[Link]:
Welcome to SVU.
Java FileReader class is used to read data from the file. It returns data in byte format
like FileInputStream class.
FileReader(String It gets filename in string. It opens the given file in read mode. If file doesn't
file) exist, it throws FileNotFoundException.
P a g e 19 | 20
Unit_IV Object oriented programming with Java IV-sem | Bcom
FileReader(File file) It gets filename in file instance. It opens the given file in read mode. If file
doesn't exist, it throws FileNotFoundException.
int read() It is used to return a character in ASCII form. It returns -1 at the end of file.
AD
In this example, we are reading the data from the text file [Link] using Java
FileReader class.
package [Link];
import [Link];
public class FileReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:\\[Link]");
int i;
while((i=[Link]())!=-1)
[Link]((char)i);
[Link]();
}
}
Here, we are assuming that you have following data in "[Link]" file:
Welcome to javaTpoint.
Output:
Welcome to javaTpoint.
P a g e 20 | 20
Unit_V Object oriented programming with Java IV-sem | Bcom
Unit V
Exception Handling: Errors in Java Program, Exceptions, throws Clause, throw Clause, Types of
Exceptions
Threads: Single Tasking, Multi-Tasking, Uses of Threads, creating a Thread and Running it,
Terminating the Thread, Thread Class Methods.
Exception Handling:
1) What are the Errors in java programs?
Error is common to make mistakes while developing as well as typing a program. A mistake
might lead to an error causing the program to produce unexpected results. Errors are the
wrongs that can make a program go wrong.
An error may produce an incorrect output or may terminate the execution of the program
abruptly or even may cause the system to crash.
It is therefore important to detect and manage properly all the possible error conditions in the
program so that the program will not terminate or crash during execution.
Types of errors:
Errors may broadly be classified into two categories:
1. Compile-time errors
2. Run-time errors
Compile-Time errors:
All syntax errors will be detected and displayed by the java compiler and therefore these
errors are known as compiler-time errors. Whenever the compiler displays an error, it will not
create the .class file. It is therefore necessary that we fix all the errors before we can
successfully compile and run the program.
Example:
/* This Program contains an error*/
Class Error1
{
Public static void main(String args[])
{
[Link](“Hello Java”) //Missing;
}
}
P a g e 1 | 31
Unit_V Object oriented programming with Java IV-sem | Bcom
The compiler does a nice job of telling us where the errors are in the program.
The above example of program shows message will be displayed on the screen:
[Link]: ‘;’ expected
[Link](“Hello Java”)
^
1 error
Most of the compile-time errors are due to typing mistakes. The most common problems are:
1. Missing semicolons
2. Missing (or mismatch of) brackets in classes and methods
3. Misspelling of identifiers and keywords
4. Missing double quotes in strings
5. Use of undeclared variables
6. Incompatible types is assignments/ initialization
7. Use of= in place of = = Operator
And so on.
Other errors we may encounter are related to directory paths. An error such as
Javac : command not found
Run-Time Errors
Sometimes, a program may successfully creating the .class file but may not run properly.
Such programs may produce wrong results due to wrong logic or may terminate due to errors
such as stack overflow. Most common run-time errors are:
1. Dividing an integer by zero
2. Accessing an element that is out of the bounds of an array
3. Trying to store a value into an array of an incompatible class or type
4. Trying to cast an instance of a class to one of its subclasses
5. Passing a parameter that is not in a valid range or value for a method
6. Trying to illegally change the state of a thread.
7. Attempting to use a negative size for an array
8. Using a null object reference as a legitimate object reference to access a method or a
variable
9. Converting invalid string to a number
10. Accessing a character that is out of bounds of a string
Run-time errors Example program:
Class Error2
{
P a g e 2 | 31
Unit_V Object oriented programming with Java IV-sem | Bcom
P a g e 3 | 31
Unit_V Object oriented programming with Java IV-sem | Bcom
exception i.e checked exception exceptions can be declared and for the
cannot be propagated using propagation checked exception must
throw. use throws keyword followed by
specific exception class name.
4 Syntax Syntax wise throw keyword is On other hand syntax wise throws
followed by the instance keyword is followed by exception
variable. class names.
5 Declaration In order to use throw keyword On other hand throws keyword is used
we should know that throw with the method signature.
keyword is used within the
method.
This is example of throw: of throw vs throws
[Link]
public class JavaTester{
public void checkAge(int age){
if(age<18)
throw new ArithmeticException("Not Eligible for voting");
else
[Link]("Eligible for voting");
}
public static void main(String args[]){
JavaTester obj = new JavaTester();
[Link](13);
[Link]("End Of Program");
}
}
Output
Exception in thread "main" [Link]:
Not Eligible for voting
at [Link]([Link])
at [Link]([Link])
Example of Throws clause:
[Link]
public class JavaTester{
public int division(int a, int b) throws ArithmeticException{
int t = a/b;
P a g e 4 | 31
Unit_V Object oriented programming with Java IV-sem | Bcom
return t;
}
public static void main(String args[]){
JavaTester obj = new JavaTester();
try{
[Link]([Link](15,0));
}
catch(ArithmeticException e){
[Link]("You shouldn't divide number by zero");
}
}
}
Output
You shouldn't divide number by zero
3. Explain about try and catch block? Or Explain the Process of Handling
Exceptions with example.
Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException,
IOException, SQLException, RemoteException, etc.
The core advantage of exception handling is to maintain the normal flow of the application.
An exception normally disrupts the normal flow of the application; that is why we need to
handle exceptions. Let's consider a scenario:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
P a g e 5 | 31
Unit_V Object oriented programming with Java IV-sem | Bcom
Suppose there are 10 statements in a Java program and an exception occurs at statement 5; the
rest of the code will not be executed, i.e., statements 6 to 10 will not be executed.
However, when we perform exception handling, the rest of the statements will be executed.
That is why we use exception handling in Java.
Java provides five keywords that are used to handle the exception. The following table
describes each.
Keyword Description
Try The "try" keyword is used to specify a block where we should place an exception code.
It means we can't use try block alone. The try block must be followed by either catch or
finally.
Catch The "catch" block is used to handle the exception. It must be preceded by try block which
means we can't use catch block alone. It can be followed by finally block later.
Finally The "finally" block is used to execute the necessary code of the program. It is executed
whether an exception is handled or not.
Throw The "throw" keyword is used to throw an exception.
Throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an
exception in the method. It doesn't throw an exception. It is always used with method
signature.
Java try block is used to enclose the code that might throw an exception. It must be used within the
method.
If an exception occurs at the particular statement in the try block, the rest of the block code will not
execute. So, it is recommended not to keep the code in try block that will not throw an exception.
try{
P a g e 6 | 31
Unit_V Object oriented programming with Java IV-sem | Bcom
try{
//code that may throw an exception
}finally{}
Java catch block
Java catch block is used to handle the Exception by declaring the type of exception within the parameter.
The declared exception must be the parent class exception ( i.e., Exception) or the generated exception
type. However, the good approach is to declare the generated type of exception.
The catch block must be used after the try block only. You can use multiple catch block with a single
try block.
But if the application programmer handles the exception, the normal flow of the application is
maintained, i.e., rest of the code is executed.
Example 1
[Link]
Output:
P a g e 7 | 31
Unit_V Object oriented programming with Java IV-sem | Bcom
As displayed in the above example, the rest of the code is not executed (in such case, the rest of the
code statement is not printed).
There might be 100 lines of code after the exception. If the exception is not handled, all the code below
the exception won't be executed.
Let's see the solution of the above problem by a java try-catch block.
Example 2
[Link]
Output:
[Link]: / by zero
rest of the code
As displayed in the above example, the rest of the code is executed, i.e., the rest of the code statement
is printed.
P a g e 8 | 31
Unit_V Object oriented programming with Java IV-sem | Bcom
In Java, exception is an event that occurs during the execution of a program and disrupts the
normal flow of the program's instructions. Bugs or errors that we don't want and restrict our
program's normal execution of code are referred to as exceptions. In this section, we will focus
on the types of exceptions in Java and the differences between the two.
1. Built-in Exceptions
o Checked Exception
o Unchecked Exception
2. User-Defined Exceptions
Built-in Exception
Exceptions that are already available in Java libraries are referred to as built-in exception.
These exceptions are able to define the error situation so that we can understand the reason of
getting this error. It can be categorized into two broad categories, i.e., checked
exceptions and unchecked exception.
Checked Exception
Checked exceptions are called compile-time exceptions because these exceptions are checked
at compile-time by the compiler. The compiler ensures whether the programmer handles the
P a g e 9 | 31
Unit_V Object oriented programming with Java IV-sem | Bcom
exception or not. The programmer should have to handle the exception; otherwise, the system
has shown a compilation error.
Unchecked Exceptions
The unchecked exceptions are just opposite to the checked exceptions. The compiler will not
check these exceptions at compile time. In simple words, if a program throws an unchecked
exception, and even if we didn't handle or declare it, the program would not give a compilation
error. Usually, it occurs when the user provides bad data during the interaction with the
program.
Note: The RuntimeException class is able to resolve all the unchecked exceptions because
of the child-parent relationship.
Some of the Exceptions meaning:
P a g e 10 | 31
Unit_V Object oriented programming with Java IV-sem | Bcom
User-defined Exception
In Java,
User-defined Exceptions:
❖ The built-in exceptions in java are not able to describe a certain situation.
❖ Like the built-in exceptions, the user can also create his own exceptions which are
called ‘user-defined exceptions.
Steps to Creation of user-defined Exceptions:
1. The user should create an exception class as a sub-class to Exception class. All
exceptions are sub-classes of Exception class, the user should also make his class a
subclass to it.
This is done as:
Syntax:
2. The user can write a default constructor in his own exception class. He can use it; in
case he does not want to store any exception details. If the user does not want to
create an empty object to his exception class, he can eliminate writing the default
constructor.
P a g e 11 | 31
Unit_V Object oriented programming with Java IV-sem | Bcom
Syntax:
MyException()
Statements;
3. The user can create a parameterized constructor with a string as a parameter. He can
use this to store exception details. He can call super class (Exception) constructor
from this and send the string here.
Syntax:
MyException(String str)
4. When the user wants to raise his own exception, he should create an object to his
exception class and throw it using throw clause, as
Syntax:
throw me;
Extra Questions:
Q) What is the Exception? What Exception Handling in java?
Exceptions:
An exception is a condition that is caused by a run-time error in the program. When the java
interpreter encounters an error such as dividing an integer by zero, it creates an exception
object and throws it(i.e., informs us that an error has occurred).
(Or)
In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.
Exception Handling :
The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so
that the normal flow of the application can be maintained.
P a g e 12 | 31
Unit_V Object oriented programming with Java IV-sem | Bcom
The mechanism suggests incorporation of a separate error handling code that performs the
following tasks:
[Link] the problem (Hit the exception)
[Link] that an error has occurred (Throw the exception)
[Link] the error information (Catch the exception)
[Link] corrective actions (Handle the exception)
Thread:
5. What is meant by thread and multithread? Explain the following concepts
As creating thread, extending thread and Stopping and Blocking a
Thread?
1. Windows XP and Windows 7 may recognize that they can execute several programs
simultaneously. This ability is known as multitasking. In system’s terminology, it is called
multithreading.
2. Multithreading is a conceptual programming paradigm where a program (process) is
divided into two or more subprograms (processes), which can be implemented at the same
P a g e 13 | 31
Unit_V Object oriented programming with Java IV-sem | Bcom
time in parallel. For example, one subprogram can display an animation on the screen while
another may build the next animation to be displayed.
3. In most of our computers, we have only a single processor and therefore, in reality, the
processor is doing only one thing at a time. However, the processor switches between the
processes so fast that it appears to human beings that all of them are being done
simultaneously.
A thread is similar to a program that has a single flow of control. It has a beginning, a
body, and an end, and executes commands sequentially. In fact, all main programs in our
earlier examples can be called single-threaded programs. Every program will have at least
one thread as shown in Figure.
Single-threaded program
A unique property of Java is its support for multithreading. That is, Java enables us to
use multiple flows of control in developing programs. Each flow of control may be thought of
as a separate tiny program (or module) known as a thread that runs in parallel to others as
shown in Figure.
P a g e 14 | 31
Unit_V Object oriented programming with Java IV-sem | Bcom
Once initiated by the main thread, the threads A, B, and C run concurrently and share
the resources jointly. It is like people living in joint families and sharing certain resources
among all of them. The ability of a language to support multithreads is referred to as
concurrency. Since threads in Java are subprograms of a main application program and share
the same memory space, they are known as lightweight threads or lightweight processes.
CREATING THREADS
Creating threads in Java is simple. Threads are implemented in the form of objects that
contain a method called run( ).
The run( ) method is the heart and soul of any thread. It makes up the entire body of a
thread and is the only method in which the thread's behavior can be implemented. A typical
run( ) would appear as follows:
public void run( )
{
..........
.......... (Statements for implementing thread)
..........
}
The run() method should be invoked by an object of the concerned thread. This can be
achieved by creating the thread and initiating it with the help of another thread method
called start ().
A new thread can be created in two ways.
1. By creating a thread class: Define a class that extends Thread class and override its run( )
method with the code required by the thread.
2. By converting a class to a thread: Define a class that implements Runnable interface.
The Runnable interface has only one method, run(), that is to be defined in the method with
the code to be executed by the thread.
Extending the thread class
We can make our class runnable as thread by extending the class [Link]. This
gives us access to all the thread methods directly. It includes the following steps:
Declare the class as extending the Thread class.
Implement the run( ) method that is responsible for executing the sequence of code that
the thread will execute.
Create a thread object and call the start( ) method to initiate the thread execution.
Declaring the Class
The Thread class can be extended as follows:
class MyThread extends Thread
P a g e 15 | 31
Unit_V Object oriented programming with Java IV-sem | Bcom
{
...............
...............
...............
}
Now we have a new type of thread MyThread.
Implementing the run() Method
The run( ) method has been inherited by the class MyThread. We have to override this
method in order to implement the code to be executed by our thread. The basic
implementation of run() will look like this:
public void run()
{
................
................ // Thread code here
................
}
When we start the new thread, Java calls the thread's run( ) method, so it is the run( ) where
all the action takes place.
Starting New Thread
To actually create and run an instance of our thread class, we must write the following:
MyThread aThread = new MyThread( );
[Link]( ); // invokes run() method
The first line instantiates a new object of class MyThread. Note that this statement just
creates the object. The thread that will run this object is not yet running. The thread is in a
newborn state.
The second line calls the start( ) method causing the thread to move into the runnable state.
Then, the Java runtime will schedule the thread to run by invoking its run( ) method. Now,
the thread is said to be in the running state.
STOPPING AND BLOCKING A THREAD
Stopping a Thread
Whenever we want to stop a thread from running further, we may do so by calling its
stop() method, like:
[Link]( );
Blocking a Thread
P a g e 16 | 31
Unit_V Object oriented programming with Java IV-sem | Bcom
A thread can also be temporarily suspended or blocked from entering into the
runnable and subsequently running state by using either of the following thread methods:
sleep( ) // blocked for a specified time
suspend( ) // blocked until further orders
wait( ) // blocked until certain condition occurs
These methods cause the thread to go into the blocked (or not-runnable) state. The
thread will return to the runnable state when the specified time is elapsed in the case of sleep(
), the resume( ) method is invoked in the case of suspend(), and the notify() method is called
in the case of wait( ).
6) What is the Single and Multi tasking in java? And what is the Use of the thread?
To perform a single and multiple tasks using multiple threads.
Single task:
If we need to perform a single task using multiple threads then we need to use only
one/single run() method.
Example
In this example, we simply extend the thread and perform a single task using multiple
threads.
P a g e 17 | 31
Unit_V Object oriented programming with Java IV-sem | Bcom
Multiple tasks
To perform multiple tasks by multiple threads, we need to use multiple run() methods.
Example :
P a g e 18 | 31
Unit_V Object oriented programming with Java IV-sem | Bcom
Java Threads
Threads allows a program to operate more efficiently by doing multiple things at the same
time.
Threads can be used to perform complicated tasks in the background without interrupting the
main program.
Newborn state
Runnable state
Running state
Blocked state
Dead state
A thread is always in one of these five states. It can move from one state to another via
a variety of ways as shown in Figure.
A thread is always in one of these five states. It can move from one state to another via a
variety of ways as shown in Figure.
P a g e 19 | 31
Unit_V Object oriented programming with Java IV-sem | Bcom
Newborn State
When we create a thread object, the thread is born and is said to be in newborn state.
The thread is not yet scheduled for running. At this state, we can do only one of the following
things with it:
Schedule it for running using start( ) method. Scheduling a newborn
Kill it using stop( ) method.
Runnable State
The runnable state means that the thread is ready for execution and is waiting for the
availability of the processor. That is, the thread has joined the queue of threads that are
waiting for execution.
If all threads have equal priority, then they are given time slots for execution in round robin
fashion, i.e., first come, first-serve manner.
if we want a thread to relinquish control to another thread to equal priority before its turn
comes, we can do so by using the yield() method Figure.
P a g e 20 | 31
Unit_V Object oriented programming with Java IV-sem | Bcom
Running State
Running means that the processor has given its time to the thread for its execution.
The thread runs until it relinquishes(surrender) control on its own or it is preempted by a
higher priority thread. A running thread may relinquish its control in one of the following
situations:
It has been suspended using suspend( ) method. A suspended thread can be revived by
using the resume( ) method. This approach is useful when we want to suspend a thread for
some time due to certain reason, but do not want to kill it.
It has been made to sleep. We can put a thread to sleep for a specified time period using the
method sleep(time) where time is in milliseconds. This means that the thread is out of the
queue during this time period. The thread re-enters the runnable state as soon as this time
period is elapsed.
It has been told to wait until some event occurs. This is done using the wait( ) method. The
thread can be scheduled to run again using the notify( ) method.
P a g e 21 | 31
Unit_V Object oriented programming with Java IV-sem | Bcom
Blocked State
A thread is said to be blocked when it is prevented from entering into the runnable state and
subsequently the running state.
This happens when the thread is suspended, sleeping, or waiting in order to satisfy certain
requirements. A blocked thread is considered “not runnable” but not dead and therefore
fully qualified to run again.
Dead State
Every thread has a life cycle. A running thread ends its life when it has completed executing
its run( ) method.
We can kill it by sending the stop message to it at any state thus causing a premature death
to it. A thread can be killed as soon it is born, or while it is running, or even when it is in
“not runnable” (blocked) condition.
Thread class:
Thread class provide constructors and methods to create and perform operations on a
[Link] class extends Object class and implements Runnable interface.
o Thread()
o Thread(String name)
o Thread(Runnable r)
P a g e 22 | 31
Unit_V Object oriented programming with Java IV-sem | Bcom
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to
be executed by a thread. Runnable interface have only one method named run().
Starting a thread:
The start() method of Thread class is used to start a newly created thread. It performs the
following tasks:
FileName: [Link]
Output:
thread is running...
FileName: [Link]
P a g e 23 | 31
Unit_V Object oriented programming with Java IV-sem | Bcom
Output:
thread is running...
If you are not extending the Thread class, your class object would not be treated as a thread
object. So you need to explicitly create the Thread class object. We are passing the object of
your class that implements Runnable so that your class run() method may execute.
Extra questions:
9) How to Terminating the Thread in java?
Java Thread stop() method
The stop() method of thread class terminates the thread execution. Once a thread is stopped, it
cannot be restarted by start() method.
Syntax
1. public final void stop()
2. public final void stop(Throwable obj)
Parameter
Return
P a g e 24 | 31
Unit_V Object oriented programming with Java IV-sem | Bcom
Exception
SecurityException: This exception throws if the current thread cannot modify the thread.
Example
class JavaStopExp extends Thread
{
public void run()
{
for(int i=1; i<5; i++)
{
try
{
// thread to sleep for 500 milliseconds
sleep(500);
[Link]([Link]().getName());
}
catch(InterruptedException e){
[Link](e);
}
[Link](i);
}
}
}
public class Testing {
Thread-0
1
Thread-1
2
Thread-0
2
Thread-1
3
Thread-0
3
Thread-1
4
Thread-0
4
The Java Thread class provides the two variant of the sleep() method.
The method sleep() is being used to halt the working of a thread for a given amount of time.
The time up to which the thread remains in the sleeping state is known as the sleeping time of
the thread.
After the sleeping time is over, the thread starts its execution from where it has left.
Whenever the [Link]() methods execute, it always halts the execution of the current
thread.
Whenever another thread does interruption while the current thread is already in the sleep
mode, then the InterruptedException is thrown.
P a g e 26 | 31
Unit_V Object oriented programming with Java IV-sem | Bcom
The following example shows how one can use the sleep() method on the custom thread.
FileName: [Link]
class TestSleepMethod1 extends Thread{
public void run(){
for(int i=1;i<5;i++){
// the thread will sleep for the 500 milli seconds
try{
[Link](500);
}catch(InterruptedException e){
[Link](e);
}
[Link](i);
}
}
public static void main(String args[]){
TestSleepMethod1 t1=new TestSleepMethod1();
TestSleepMethod1 t2=new TestSleepMethod1();
[Link]();
[Link]();
}
}
Output:
1
1
2
2
3
3
4
4
As you know well that at a time only one thread is executed. If you sleep a thread for the
specified time, the thread scheduler picks up another thread and so on.
11) Explain Thread Priorities?
• In the Java programming language, every thread has a priority. By default, a thread
inherits the priority of the thread that constructed it.
P a g e 27 | 31
Unit_V Object oriented programming with Java IV-sem | Bcom
• You can increase or decrease the priority of any thread with the setPriority( ) method.
[Link](intNumber);
MIN_PRIORITY= 1
MAX_PRIORITY=10
NORM_PRIORITY=5
• Whenever multiple threads are ready for execution, the java system choose the
highest priority thread and executes.
Example:
class ThreadA extends Thread
{
public void run()
{
for( int i = 1; i <=5; i ++) {
[Link](" Executing ThreadA");
}
[Link](" ThreadA Quitting");
}
}
class ThreadB extends Thread
{
public void run()
{
for( int i = 1; i <= 5; i ++) {
[Link](" Executing threadB");
}
[Link](" ThreadB Quitting");
}
}
class ThreadC extends Thread
{
public void run()
{
for( int i = 1; i<=5; i ++) {
[Link](" Executing threadC");
}
[Link]("ThreadC Quitting");
}
}
class Testing
{
P a g e 28 | 31
Unit_V Object oriented programming with Java IV-sem | Bcom
Output:
ThreadA started
ThreadB started
ThreadC started
Executing threadB
Executing threadB
Executing threadB
Executing threadB
Executing threadB
ThreadB Quitting
Executing threadC
Executing threadC
Executing threadC
Executing threadC
Executing threadC
ThreadC Quitting
Executing ThreadA
Executing ThreadA
Executing ThreadA
Executing ThreadA
Executing ThreadA
ThreadA Quitting
Java Provides Thread class to achieve thread programming Thread class provides
constructors and methods to create and perform operations on a thread.
P a g e 29 | 31
Unit_V Object oriented programming with Java IV-sem | Bcom
When two or more threads access to a shared (common) resource, they need some
P a g e 30 | 31
Unit_V Object oriented programming with Java IV-sem | Bcom
way to ensure that the resource will be used by only one thread at a time. The process by
which this is achieved is called synchronization. We can synchronize our code in two ways.
Both involve the use of synchronized keyword.
1. Synchronized methods
2. Synchronized code blocks
Synchronized methods:
We can serialize the access to the methods to only one thread at a time. To do this
you simply need to precede the method’s definition with the keyword synchronized.
When we declare a method synchronized, java creates a ―monitor and hands it over
the thread that calls method first time. As long as the thread holds the monitor, no other thread
can enter the synchronized section of code.
We use the keyword synchronized indicating the object you want to restrict access
to. The general form is
synchronized (obj)
//statements to be synchronized
P a g e 31 | 31