0% found this document useful (0 votes)
3 views122 pages

Java All Units-1

The document provides an overview of Object-Oriented Programming (OOP) concepts in Java, highlighting its features such as classes, objects, inheritance, polymorphism, abstraction, encapsulation, dynamic binding, and message passing. It also discusses the history and characteristics of Java, emphasizing its simplicity, portability, security, robustness, and platform independence. Additionally, it covers Java's naming conventions and data types, including primitive and non-primitive types.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views122 pages

Java All Units-1

The document provides an overview of Object-Oriented Programming (OOP) concepts in Java, highlighting its features such as classes, objects, inheritance, polymorphism, abstraction, encapsulation, dynamic binding, and message passing. It also discusses the history and characteristics of Java, emphasizing its simplicity, portability, security, robustness, and platform independence. Additionally, it covers Java's naming conventions and data types, including primitive and non-primitive types.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Object oriented programming in java |iv Sem B.

com

Unit – I

Introduction to OOPs

Q) What are the Problems in Procedure Oriented Approach?

Problems in Procedure Oriented Approach:

 The program code is harder to write when Procedural Programming is employed


 The Procedural code is often not reusable, which may pose the need to recreate the
code if is needed to use in another application
 Difficult to relate with real-world objects
 The importance is given to the operation rather than the data, which might pose issues
in some data-sensitive cases
 The data is exposed to the whole program, making it not so much security friendly

Q) What are the Features of OOPS in Java? Explain.

Feature of OOP in Java:

Object-Oriented Programming is a paradigm that provides many concepts, such


as inheritance, data binding, polymorphism, etc.

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

Java is the first object-oriented programming


language. The programming paradigm where everything is represented as an object is known
as a truly object-oriented programming language.

1
Object oriented programming in java |iv Sem [Link]

The main aim of object-oriented programming is to implement real-world entities, for


example, object, classes, abstraction, inheritance, polymorphism, etc.

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:

Collection of objects is called class. It is a logical entity.

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:

If one task is performed in different ways, it is known as polymorphism. For example: to


convince the customer differently, to draw something, for example, shape, triangle, rectangle,
etc.

In Java, we use method overloading and method overriding to achieve 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.

In Java, we use abstract class and interface to achieve abstraction.

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:

 Binding refers to a linking procedure called to the code which is to be executed in


response to the call.
 Dynamic binding means that the code associated with a given procedure called is not
known until the time of call at the run time.
 Consider a procedure ‘draw’ shown in a fig by inheritance every object will have this
procedure.
 This ‘draw’ procedure will be redefined in each class that defines the object.
 At the run time, the code matching the object under current reference will be called.

8) Message communication:

 An object-oriented program consists of set of objects that communicate with each


other.

3
Object oriented programming in java |iv Sem [Link]

 The process of programming in an object oriented language involves following basic


steps: –
o Creating classes that define object and their behavior.
o Creating object from class definition.
o Establishing communication among object.
 Objects may communicate with one another by sending and receiving information
through functions.
 A message for an object is a request for execution of a procedure. Therefore it
involves a function in receiving object that generates desired results.

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

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


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

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


and maintenance by providing some rules.

Basic concepts of OOPs are:

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

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]

o Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE)


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

Java language provides these securities by default. Some security can also be provided by an
application developer explicitly through SSL, JAAS, Cryptography, etc.

[Link]

The English mining of Robust is strong. Java is robust because:

o It uses strong memory management.


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

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

Q) What is JVM? And Explain JVM?

The Java Virtual Machine (JVM):


 JVM Stands for Java virtual Machine is an abstract Machine.
 JVM(Java Virtual Machine) acts as a run-time engine to run Java applications.
 JVM is the one that actually calls the main method present in a java code.
 JVM is a part of JRE(Java Runtime Environment).
 Java applications are called WORA (Write Once Run Anywhere).
 This means a programmer can develop Java code on one system and can expect it to
run on any other Java-enabled system without any adjustment. This is all possible
because of JVM.
 When we compile a .java file, .class files(contains byte-code) with the same class
names present in .java file are generated by the Java compiler. This .class file goes
into various steps when we run it. These steps together describe the whole JVM.
 It is mainly responsible for three activities.
i. Loading
ii. Linking
iii. Initialization
The JVM performs the following main tasks
1. Loads code
2. Verifies code
3. Executes code
4. Provides run time environment.

9
Object oriented programming in java |iv Sem [Link]

Q) What are the Naming Conventions in Java?


Java Naming Convention

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.

Naming Conventions of the Different Identifiers

The following table shows the popular conventions used for the different identifiers.

Identifiers Naming Rules Examples


Type

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

Interface It should start with the uppercase letter. interface Printable


It should be an adjective such as Runnable, Remote, {
ActionListener. //code snippet
Use appropriate words, instead of acronyms. }

10
Object oriented programming in java |iv Sem [Link]

Method It should start with lowercase letter. class Employee


It should be a verb such as main(), print(), println(). {
If the name contains multiple words, start it with a // method
lowercase letter followed by an uppercase letter such as void draw()
actionPerformed(). {
//code snippet
}
}

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.

Package It should be a lowercase letter such as java, lang. //package


If the name contains multiple words, it should be package [Link];
separated by dots (.) such as [Link], [Link]. class Employee
{
//code snippet
}

Constant It should be in uppercase letters such as RED, YELLOW. class Employee


If the name contains multiple words, it should be {
separated by an underscore(_) such as MAX_PRIORITY. //constant
It may contain digits but not as the first letter. static final
int MIN_AGE = 18;
//code snippet
}

Q) What are the Data Types in Java? Explain.


Data Types in Java:
Data Types in Java

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

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

11
Object oriented programming in java |iv Sem [Link]

There are 8 types of primitive data types:

Primitive Data Types

A primitive data type specifies the size and type of variable values, and it has no additional
methods.

There are eight primitive data types in Java:

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:

 Java supports four types of integers depending upon size.


 Integers can be accessed like whole numbers.

Data type size Range

Byte 1 byte -128 to +127

Short 2 bytes -215 to +215-1

12
Object oriented programming in java |iv Sem [Link]

Int 4 bytes ` -231 to +231-1

Long 8 bytes -263 to +263-1

Boolean Data Type

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

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

Data Type Size Description

Boolean 1 bit Stores true or false values

Example:

Boolean one = false

Float Data Type

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.

Data Type Size Description

Float 4 bytes Stores fractional numbers. Sufficient for


storing 6 to 7 decimal digits

13
Object oriented programming in java |iv Sem [Link]

Example:

float f1 = 234.5f

Double Data Type

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

Data Type Size Description

Boolean 1 bit Stores true or false values

Char data type:

char
The char data type is a single 16-bit Unicode character.
Syntax:
char charVar;
Size: 2 byte (16 bits)

char 2 bytes Stores a single character/letter or ASCII values

Q) What are the parts in java program?

Parts in Java Program:

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]

A Simple Java Program to Print "Hello Java"


Example:

//Name of this file will be "[Link]"

public class Hello


{

public static void main(String[] args)


{
[Link]("Hello Java");
}
}

Program Output:

Hello Java

Here are the most important points to note about the Java programs:

 You have to keep in mind that, Java code is case sensitive.


 To write a Java program, you must have to define class first.
 The name of the class in Java (which holds the main method) is the name of the Java
program, and the same name will be given in the filename. As mentioned above in the
sample program; The name of the class is "Hello" in which the main method is, then
this file will be named "[Link]".

Let's Look into Various Parts of the Above Java Program
public class Hello:

 This creates a class called Hello.


 All class names must start with a capital letter.
 The public word means that it is accessible from any other classes.

Comments :

Two types of comments are there

1. Single line comment (//)


2. Double line comment(/* some text */)

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.

public static void main:

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

Q) Displaying Output using System. [Link] ()?

//Name of this file will be "[Link]"

public class Hello


{

public static void main(String[] args)


{
[Link]("Hello Java");
}
}

Program Output:

Hello Java

16
Object oriented programming in java |iv Sem [Link]

Q) How to read the input using the scanner class?


Reading input using the Scanner class:

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

Scanner in = new Scanner([Link]);

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:

Scanner in = new Scanner("Hello Viswam college");

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]

Q)Implementing a java program or How to Execute a Java Program?

Implementation of a Java application program involves a series of steps. They include:

Example:

class Example

public static void main (String args[ ])

[Link](“This is a simple Java program”);

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.

Select File | Save As from the notepad menu.

In the ‘File name’ field, type “[Link]” within double quotes.

In the ‘Save as type’ field select All Files (*.*).

Clicks enter to save the file.

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:\>cd javaeg // change to directory javaeg using cd command

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

This is a simple Java program

Q). Explain about various operator and Expressions in Java?

Operators and expressions

 Java supports a rich set of operators.


 An operator is a symbol that is used to perform operations. There can be many types of
operations like arithmetic, logical, bitwise etc.
 Depending on the type of operations they perform, they are classified into the following
types:
 Assignment operator =
 Arithmetic operators +, –, *, /, %
 Relational operators <, <=, >, >=, ==, !=
 Logical operators [ &&, ||, s!
 Increment/Decrement operators ++, – –
 Conditional operator?:
 Bitwise operators &, |, ^, <<, >>
 Special operators
i)Assignment Operator [= ]

 The single equal symbol (=) is referred to as the assignment operator.


 It is used to assign the value of an expression to a variable.
 The statement used for this purpose is called the assignment statement.
Syntax:

Variable =constant;

Examples

(a) int a;

19
Object oriented programming in java |iv Sem [Link]

a = 10;

The variable a is assigned the value 10.

(b) int a, b = 10;

a = b;

The variable a is assigned the value of b.

(c) int a = 5, b = 10, c;

c = a + b;

ii)Arithmetic Operators [Unary +, Unary –, +, –, *, /, %]

 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

iii)Relational Operators [ <, <=, >, >=, ==, != ] or comparison operators

 The relational operators are used to compare two quantities or numbers.


 The value of a relational expression in C++ is one or zero. One indicates that the
condition is true and zero indicates that the condition is false. A relational expression
is also called a conditional expression or a Boolean expression.

20
Object oriented programming in java |iv Sem [Link]

iv) Logical Operators [ &&, ||, ! ]

 These logical operators are used to create compound conditional expressions.


 The operators && and || are used to combine two conditional expressions and ! is used
to negate a conditional expression.
Logical AND (&&):

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.

Logical NOT (!):

C1 !C1
T F
F T
Here c1 is simply negated (Reverse).

21
Object oriented programming in java |iv Sem [Link]

v)Increment/Decrement Operators [ ++, – – ]

 Increment operator ++ is to increment the value of a variable by one and the


decrement operator – – is to decrement the value of a variable by one.
The syntax of using ++ and – is as follows:

operand++; Here, ++ is said to have been suffixed to the operand.

++operand; Here, ++ is said to have been prefixed to the operand.

operand--; Here, – – is said to have been suffixed to the operand.

--operand; Here, – – is said to have been prefixed to the operand.

Figure 1 Increment/Decrement Operators a = 6

vi) Conditional Operator [ ?:] or ternary operator

 The conditional operator is denoted by the symbol ?:,


 It helps in two-way decision making.
Syntax of Conditional Operator:

(Expression1) ? (Expression2): (Expression3);

Example:

a=6, b=8

(a>b)? a: b

vii) Bitwise Operators [ &, |, ^, <<, >> ]

Bitwise AND (&):

 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]

Syntax of the bitwise AND operator:

op1 & op2

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.

Syntax of the bitwise OR operator:

op1 | op2

Bitwise exclusive OR (^):

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

Syntax of the bitwise exclusive OR operator:

op1 ^ op2

Left Shift (<<)

 Left shift operator is used to shift the bits into left side.
Ex:

0000010

0001000

Bitwise AND (&)

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:

10101010 & 01010101 = 00000000

viii) Special Operator:

Java supports some special operators like this:

Instance of operator

member selection 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

public static void main(String args[])

int x = [Link];

24
Object oriented programming in java |iv Sem [Link]

for (int i = 0; i< x; i++)

[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

Q) What is Constant? Explain the Constants in Java?

The constant is fixed value that never changed at execution of program.

Example:

int a=10

Here 10 is the constant.

Constants are broadly classified into three classes.

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:

 Integer constants are whole numbers (i.e., without decimal part).

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 decimal integer constant is following the properties:

(a) It is a sequence of one or more digits [0…9,] the symbols of decimal number
system.

(ii) Octal integer constants.

An octal integer constant is following properties:

(a) It is a sequence of one or more digits [0…7, symbols of octal number system]

(iii) Hexadecimal integer constants.

A hexadecimal integer constant is following properties:

(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

Character constants refers to it consist of one or more characters of the alphabet of


C++. Depending on the number of characters present, character constants are further
classified into two types:

Single character constant:

A single character constant consists of only one character and it is enclosed within a
pair of single quotes. For example,

‘a’ is a single character constant.

‘9’ is a single character constant.

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,

“abc” is a string constant.

“12bn” is a string constant.

Note that “123” and “1” are also string constants.

Backslash Character Constants

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.

Q) What are the Control statements in java?


The control statements in java:

 Java compiler executes the code from top to bottom.


 The statements in the code are executed according to the order in which they appear.
 However, Java provides statements that can be used to control the flow of Java code.
 Such statements are called control flow statements.
 It is one of the fundamental features of Java, which provides a smooth flow of
program.

Java provides three types of control flow statements.


1. Decision Making statements
o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement

Q) Discuss about Decision-Making statements with examples?


As the name suggests, decision-making statements decide which statement to execute and
when.
Decision-making statements evaluate the Boolean expression and control the program flow
depending upon the result of the condition provided.
There are two types of decision-making statements in Java, i.e., If statement and switch
statement.

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

Let's understand the loop statements one by one.

1) Java for loop


In java, for loop is similar to C and C++.

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

The flow chart for the for-loop is given below.

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

2) Java while loop


The while loop is also used to iterate over the number of statements multiple times. However,
if we don't know the number of iterations in advance, it is recommended to use a while loop.
Unlike for loop, the initialization and increment/decrement doesn't take place inside the loop
statement in while loop.
It is also known as the entry-controlled loop since the condition is checked at the start of the
loop. If the condition is true, then the loop body will be executed; otherwise, the statements
after the loop will be executed.
The syntax of the while loop is given below.
while(condition){
//looping statements
}

34
Object oriented programming in java |iv Sem [Link]

The flow chart for the while loop is given in the following image.

Consider the following example.


Calculation .java
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");
while(i<=10) {
[Link](i);
i = i + 2;
}
}
}

Output:
Printing the list of first 10 even numbers

0
2
4
6
8
10

3) Java do-while loop


The do-while loop checks the condition at the end of the loop after executing the loop
statements. When the number of iterations is not known and we have to execute the loop at
least once, we can use do-while loop.

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]

What are the Jump Statements or Branching statements in java? Explain.

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

As the name suggests, the break statement


is used to break the current flow of the program and transfer the control to the next statement
outside a loop or switch statement. However, it breaks only the inner loop in the case of the
nested loop.

The break statement cannot be used independently in the Java program, i.e., it can only be
written inside the loop or switch statement.

The break statement example with for loop

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]

2)Java continue statement

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 {

public static void main(String[] args) {


// It will print the 1 to 10 by using continue statement

for(int i = 1; i<= 10; i++) {


if(i == 4) {
continue;
}
[Link](i);
}
}
}

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.

Java array is an object which contains elements of a similar data type.

Additionally, The elements of an array are stored in a contiguous memory location.

It is a data structure where we store similar elements.

We can store only a fixed set of elements in a Java array.

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

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.

Types of Array in java


There are two types of array.

o Single Dimensional Array


o Multidimensional Array

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

Single Dimensional Array in Java


Syntax to Declare an Array in Java
1. dataType[] arr; (or)
2. dataType []arr; (or)
3. dataType arr[];
Example of Java Array
Let's see the simple example of java array, where we are going to declare, instantiate,
initialize and traverse an array.

//Java Program to illustrate how to declare, instantiate, initialize


//and traverse the Java array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<[Link];i++)//length is the property of array
[Link](a[i]);
}}
Output:
10
20
70
40
50

Multidimensional Array in Java

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]

3. dataType arrayRefVar[][]; (or)


4. dataType []arrayRefVar[];
Example to instantiate Multidimensional Array in Java
1. int[][] arr=new int[3][3];//3 row and 3 column
Example to initialize Multidimensional Array in Java
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;

Example of Multidimensional Java Array


Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional
array.

//Java Program to illustrate the use of multidimensional array


class Testarray3{
public static void main (String args []) {
//declaring and initializing 2D array
int arr [][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for (int i=0; i<3;i++){
for (int j=0;j<3;j++){
[Link](arr[i][j]+" ");
}
[Link]();
}
}
}
Output:
123
245
445

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

of characters works same as Java string. For example:

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.

The [Link] class


implements Serializable, Comparable and CharSequence interfaces.

CharSequence Interface

The CharSequence interface is used to represent the sequence of characters.


String, StringBuffer

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.

What is String in Java?


Generally, String is a sequence of characters. But in Java, string is an object that represents a
sequence of characters. The [Link] class is used to create a string object.

How to create a string object?


There are two ways to create 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".

Why Java uses the concept of String literal?


To make Java more memory efficient (because no new objects are created if it exists already
in the string constant pool).

2) By new keyword
1. String s=new String("Welcome");//creates two objects and one reference variable

In such case, JVM

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

Java String Example


[Link]

public class StringExample{


public static void main(String args[]){
String s1="java";//creating string by Java string literal

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.

Immutable String in Java

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]

Reason Behind Strings are immutable:

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

Java String compare


We can compare String in Java on the basis of content and reference.

It is used in authentication (by equals() method), sorting (by compareTo()


method), reference matching (by == operator) etc.

There are three ways to compare String in Java:

1. By Using equals() Method


2. By Using == Operator
3. By compareTo() Method

1) By Using equals() Method

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

The == operator compares references not values.

[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

3) By Using compareTo() method

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.

Suppose s1 and s2 are two String objects. If:

48
Object oriented programming in java |iv Sem [Link]

o s1 == s2 : The method returns 0.


o s1 > s2 : The method returns a positive value.
o s1 < s2 : The method returns a negative value.

[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

Q) Explain about Classes and Objects?


Class:

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

It is a template or blueprint from which objects are created.

A class in Java can contain:

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

Syntax to declare a class:


class <class_name>{
field;
method;
}

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.

An object has three characteristics:

They are:

1. State
2. Behavior
3. Identity

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


o Behavior: represents the behavior (functionality) of an object such as deposit,
withdraw, etc.

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:

o An object is a real-world entity.


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

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.

3 Ways to initialize object

There are 3 ways to initialize object in Java.

P a g e 2 | 22
IV-sem|JAVA_Unit-3

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

1) Object and Class Example: Initialization through reference

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

File: [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.

3) Object and Class Example: Initialization through a constructor

Object and Class Example: Employee

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

File: [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

Employee e2=new Employee();


Employee e3=new Employee();
[Link](101,"ajeet",45000);
[Link](102,"irfan",25000);
[Link](103,"nakul",55000);
[Link]();
[Link]();
[Link]();
}
}

Q) What is the instance Variable in java? Explain.


Instance Variable in Java

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

Java Instance Variable


o The variables that are declared inside the class but outside the scope of any method are
called instance variables in Java.
o The instance variable is initialized at the time of the class loading or when an object of
the class is created.
o An instance variable can be declared using different access modifiers available in Java
like default, private, public, and protected.
o Instance variables of different types have default values that are specified in the next
point.

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.

Limitations of Instance Variable


1. It cannot be declared static, abstract, striftp, synchronized, and native.
2. It can be declared final and transient.
3. It can be of any of the four access modifiers available in Java (private, public, protected,
and default).

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.

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.

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

Understanding Java Access Modifiers

Let's understand the access modifiers in Java by a simple table.

Access within within outside package by outside


Modifier class package subclass only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

1) Private

The private access modifier is accessible only within the class.

Simple example of private access modifier

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

class A{
private int data=40;
private void msg(){[Link]("Hello java");}
}

P a g e 7 | 22
IV-sem|JAVA_Unit-3

public class Simple{


public static void main(String args[]){
A obj=new A();
[Link]([Link]);//Compile Time Error
[Link]();//Compile Time Error
}
}
Role of Private Constructor

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

class A{
private A(){}//private constructor
void msg(){[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.

Example of default access modifier

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

//save by [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.

It provides more accessibility than the default modifer.

Example of protected access modifier

In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this
package is declared as protected, so it can be accessed from outside the class only through
inheritance.

//save by [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.

Example of public access modifier

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

Q) What is the constructor in java? Explain.


Constructors in Java

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

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

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

It calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.

There are two types of constructors in Java:

[Link]-arg constructor, and

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

Rules for creating Java constructor

There are two rules defined for the constructor.

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


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

P a g e 10 | 22
IV-sem|JAVA_Unit-3

Note: We can use access modifiers


while declaring a constructor. It controls the object creation. In other words, we can have
private, protected, public or default constructor in Java.

Q) what are the Types of Constructors in java?


Types of Java constructors

There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

[Link] Default Constructor

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

Syntax of default constructor:


<class_name>(){}
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the
time of object creation.

//Java Program to create and call a default constructor


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

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

[Link] Parameterized Constructor

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

Why use the parameterized constructor?

The parameterized constructor is used to provide different values to distinct objects. However,
you can provide the same values also.

Example of parameterized constructor

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

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


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

public static void main(String args[]){


//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
[Link]();
[Link]();
}
}
Output:
111 Karan
222 Aryan

P a g e 12 | 22
IV-sem|JAVA_Unit-3

Q) What is the Inheritance in java?

Inheritance in Java

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

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

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


child relationship.

Uses inheritance in java


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

Terms used in Inheritance


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

The syntax of Java Inheritance


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

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

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

P a g e 13 | 22
IV-sem|JAVA_Unit-3

Java Inheritance Example

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.

Q) What are the types of Inheritance in java?


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

P a g e 14 | 22
IV-sem|JAVA_Unit-3

Types of inheritance in java

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

single, multilevel and hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only. We
will learn about interfaces later.

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

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

Single Inheritance Example

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

File: [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...

Q) Why multiple inheritance is not supported in java?

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

Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes.
If A and B classes have the same method and you call it from child class object, there will be
ambiguity to call the method of A or B class.

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

public static void main(String args[]){


C obj=new C();
[Link]();//Now which msg() method would be invoked?
}
}
Output:
Compile Time Error

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.

There are two types of polymorphism in Java:

 compile-time polymorphism and


 runtime polymorphism.

We can perform polymorphism in java by method overloading and method overriding.

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

Q) What is the Method Overloading?


Method Overloading:
When a class has two or more methods by the same name but different parameters, at the time
of calling based on the parameters passed respective method is [Link] mechanism is
known as method overloading.
If you observe the following example, Here we have created a class named Sample and this
class has two methods with same name (add) and return type, the only difference is the
parameters they accept (one method accepts two integer variables and other accepts three
integer variables).
When you invoke the add() method based on the parameters you pass respective method body
gets executed.
Example:
public class Sample{
public static void add(int a, int b){
[Link](a+b);
}
public static void add(int a, int b, int c){
[Link](a+b+c);
}
public static void main(String args[]){
Sample obj = new Sample();
[Link](20, 40);
[Link](40, 50, 60);
}
}

Output:
60
150

Q)Why is operator overloading not supported by java? OR Explain about the


Operator overloading.
When a class has two or more methods by the same name but different parameters, at the time
of calling based on the parameters passed respective method is called .This mechanism is
known as method overloading.

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 −

 Makes code complex − In case of operator overloading the compiler and


interpreter (JVM) in Java need to put an extra effort to know the actual
functionality of the operator used in a statement.
 Programming error − Custom definition for the operators creates confusion
for the programmers especially the new developers. Moreover, while working
with programming languages that support operator overloading the program
error rate is high compared to others.
 Easy to develop tools like IDEs − Removal of operator overloading concept
keeps the language simple for handling and process leading to a number of
Integrated development environment in Java.
 Method overloading − The functionality of operator overloading can be
achieved in Java using method overloading in Java in a simple, error free and
clear manner.

Q)What is the Abstract Classes and Methods?

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.

The abstract keyword is a non-access modifier, used for classes and


methods:

 Abstract class:

Abstract class is a restricted class that cannot be used to create


objects (to access it, it must be inherited from another 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

An abstract class can have both abstract and regular methods:

abstract class Animal {

public abstract void animalSound();

public void sleep() {

[Link]("Zzz");

From the example above, it is not possible to create an object of the Animal
class:

Animal myObj = new Animal(); // will generate an error

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

abstract class Animal {

// Abstract method (does not have a body)

public abstract void animalSound();

// Regular method

public void sleep() {

[Link]("Zzz");

// Subclass (inherit from Animal)

class Pig extends Animal {

P a g e 21 | 22
IV-sem|JAVA_Unit-3

public void animalSound() {

// The body of animalSound() is provided here

[Link]("The pig says: wee wee");

class Main {

public static void main(String[] args) {

Pig myPig = new Pig(); // Create a Pig object

[Link]();

[Link]();

Output:

The pig says: wee wee


Zzz

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

1) What is the Package? And its advantages?

Java Package:

A java package is a group of similar types of classes, interfaces and sub-packages.

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

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

2) What is a package? Explain some of Java’s Built-in packages (System packages)?

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 (packages from the Java API)


 User-defined Packages (create your own packages)

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:

 Built-in Packages (packages from the Java API)


 User-defined Packages (create your own packages)

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 [Link]; // Import a single class

import [Link].*; // Import the whole package

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

Using the Scanner class to get user input:

import [Link];

class MyClass {

public static void main(String[] args) {

Scanner myObj = new Scanner([Link]);

[Link]("Enter username");

P a g e 3 | 20
Unit_IV Object oriented programming with Java IV-sem | Bcom

String userName = [Link]();

[Link]("Username is: " + userName);

Output:

Enter username

Bcom

Username is: 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]

To create a package, use the package keyword:

[Link]

package mypack;

class MyPackageClass {

public static void main(String[] args) {

[Link]("This is my package!");

P a g e 4 | 20
Unit_IV Object oriented programming with Java IV-sem | Bcom

Save the file as [Link], and compile it:

C:\Users\Your Name>javac [Link]

Then compile the package:

C:\Users\Your Name>javac -d . [Link]

This forces the compiler to create the "mypack" package.

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

To run the [Link] file, write the following:

C:\Users\Your Name>java [Link]

The output will be:

This is my package!

3)How to access package from another 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

Example of package that import the packagename.*


//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

2) Using [Link]

If you import [Link] then only declared class of this package will be accessible.

Example of package by import [Link]


//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}

//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

3) Using fully qualified name

If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.

It is generally used when two packages have same class name e.g. [Link] and [Link]
packages contain Date class.

Example of package by import fully qualified name


//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
[Link]();
}
}
Output:Hello
Note: If you import a package, subpackages will not be imported.

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

Q) How to 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

Using the Scanner class to get user input:

import [Link];

class MyClass {

public static void main(String[] args) {

Scanner myObj = new Scanner([Link]);

[Link]("Enter username");

String userName = [Link]();

[Link]("Username is: " + userName);

Output:

Enter username

Bcom

Username is: Bcom

P a g e 8 | 20
Unit_IV Object oriented programming with Java IV-sem | Bcom

Q) How to import a Package?

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].*;

Q) Explain Naming convention of java package?


Packages can name using the standard java naming rules. By convention packages
begin with lowercase letters. This makes it easy for users to distinguish package names from
the class names. All class names by convention begin with an upper case.

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

4) What is the Stream classes? Explain?

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.

 InputStream Classes - These classes are subclasses of an abstract class,


InputStream and they are used to read bytes from a source(file, memory or
console).

 OutputStream Classes - These classes are subclasses of an abstract class,


OutputStream and they are used to write bytes to a destination(file, memory or
console).

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.

 Reader classes : Abstract class that define character stream input.

 Writer classes : Abstract class that define character stream output.

5) Explain Output stream and input stream?


Stream

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

1) [Link]: standard output stream

2) [Link]: standard input stream

3) [Link]: standard error stream

Let's see the code to print output and an error message to the console.

1. [Link]("simple message");
2. [Link]("error message");

Let's see the code to get input from console.

1. int i=[Link]();//returns ASCII code of 1st character


2. [Link]((char)i);//will print the character

OutputStream vs InputStream

The explanation of OutputStream and InputStream classes are given below:

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.

Useful methods of OutputStream


Method Description

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.

3) public void flush()throws IOException flushes the current output 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.

Useful methods of InputStream


Method Description

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.

3) public void close()throws is used to close the current input stream.


IOException

InputStream Hierarchy

6) How to create a file by using java FileOutputStream and Reading Data from a File
using File Input Stream?

Java FileOutputStream Class

Java FileOutputStream is an output stream used for writing data to a file.

If you have to write primitive values into a file, use FileOutputStream class. You can write
byte-oriented as well as character-oriented data through FileOutputStream class. But, for
character-oriented data, it is preferred to use FileWriter than FileOutputStream.

FileOutputStream class declaration

Let's see the declaration for [Link] class:

public class FileOutputStream extends OutputStream


P a g e 14 | 20
Unit_IV Object oriented programming with Java IV-sem | Bcom

FileOutputStream class methods


Method Description

protected void finalize() It is used to clean up the connection with the file output stream.

void write(byte[] ary) It is used to write [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.

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

Java FileOutputStream Example 1: write byte


import [Link];
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\[Link]");
[Link](65);
[Link]();
[Link]("success...");
}catch(Exception e){[Link](e);}
}
}

Output:

Success...

P a g e 15 | 20
Unit_IV Object oriented programming with Java IV-sem | Bcom

The content of a text file [Link] is set with the data A.

[Link]

Java FileInputStream Class

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

Java FileInputStream class declaration

Let's see the declaration for [Link] class:

1. public class FileInputStream extends InputStream

Java FileInputStream class methods


Method Description

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

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

int read(byte[] b) It is used to read up to [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.

FileDescriptor getFD() It is used to return the FileDescriptor object.

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.

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

Java FileInputStream example 1: read single character


import [Link];
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\[Link]");
int i=[Link]();
[Link]((char)i);

[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?

Java FileWriter Class

Java FileWriter class is used to write character-oriented data to a file. It is character-oriented


class which is used for file handling in java.

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

Java FileWriter class declaration

Let's see the declaration for [Link] class:

public class FileWriter extends OutputStreamWriter

Constructors of FileWriter class


Constructor Description

FileWriter(String file) Creates a new file. It gets file name in string.

FileWriter(File file) Creates a new file. It gets file name in File object.

Methods of FileWriter class


Method Description

void write(String text) It is used to write the string into FileWriter.

void write(char c) It is used to write the char into FileWriter.

void write(char[] c) It is used to write char array into FileWriter.

void flush() It is used to flushes the data of FileWriter.

void close() It is used to close the FileWriter.

AD

Java FileWriter Example

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

public static void main(String args[]){


try{
FileWriter fw=new FileWriter("D:\\[Link]");
[Link]("Welcome to SVU.");
[Link]();
}catch(Exception e){[Link](e);}
[Link]("Success...");
}
}

Output:

Success...

[Link]:

Welcome to SVU.

Java FileReader Class

Java FileReader class is used to read data from the file. It returns data in byte format
like FileInputStream class.

It is character-oriented class which is used for file handling in java.

Java FileReader class declaration

Let's see the declaration for [Link] class:

public class FileReader extends InputStreamReader

Constructors of FileReader class


Constructor Description

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.

Methods of FileReader class


Method Description

int read() It is used to return a character in ASCII form. It returns -1 at the end of file.

void close() It is used to close the FileReader class.

AD

Java FileReader Example

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

public static void main(String args[])


{ int a = 10;
Int b =0;
Int c = a/b;
[Link](“c = “ + c);
}
}
Syntactically correct and therefore does not cause any problem during compilation.
However, while executing, it displays the following message and stops without executing
further statements.
[Link]: / by zero
At [Link]([Link])
When java run-time tries to execute a division by zero, it generates an error condition, which
causes the program to stop after displaying an appropriate message.

2) What is Throws and Throw clause in java?


Both throw and throws are the concepts of exception handing in which throw is used to
explicitly throw an exception from a method or any block of code while throws are used in the
signature of the method to indicate that this method might throw one of the listed type
exceptions.
The following are the important differences between throw and throws.
Sr. Key throw throws
No.
1 Definition Throw is a keyword which is Throws is a keyword used in the
used to throw an exception method signature used to declare an
explicitly in the program inside exception which might get thrown by
a method or inside a block of the function while executing the code.
code.
2 Internal Internally throw is On other hand we can declare multiple
implementation implemented as it is allowed to exceptions with throws keyword that
throw only single exception at could get thrown by the function
a time i.e we cannot throw where throws keyword is used.
multiple exception with throw
keyword.
3 Type of With throw keyword we can On other hand with throws keyword
exception propagate only unchecked both checked and unchecked

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.

Advantage of Exception Handling

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.

Common java exceptions:

ArithmeticException, ArrayIndexOutOfBoundsException, ArrayStoreException,


FileNotFoundException, IOException, NullPointerException, NumberFormatException,
OutOfMemoryException, SecurityException, StackOverFlowException,
StringIndexOfBoundsException

Java Exception Keywords

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

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.

Java try block must be followed by either catch or finally block.

Syntax of Java try-catch

try{

P a g e 6 | 31
Unit_V Object oriented programming with Java IV-sem | Bcom

//code that may throw an exception


}catch(Exception_class_Name ref){}

Syntax of try-finally block

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.

Problem without exception handling

Let's try to understand the problem if we don't use a try-catch block.

Example 1

[Link]

public class TryCatchExample1 {

public static void main(String[] args) {

int data=50/0; //may throw exception

[Link]("rest of the code");


}
}

Output:

Exception in thread "main" [Link]: / by zero

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.

Solution by exception handling

Let's see the solution of the above problem by a java try-catch block.

Example 2

[Link]

public class TryCatchExample2 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
[Link](e);
}
[Link]("rest of the code");
}

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

4) What are the Types of Exceptions?


Types of Exception in Java

 Exception is a run-time error.

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.

Exceptions can be categorized into two ways:

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:

Exception class Meaning

ArithmeticException Thrown when an exceptional condition has


occurred in an arithmetic operation.

ArrayIndexOutOfBoundsException Thrown to indicate that an array has been


accessed with an illegal index. The index is
either negative or greater than or equal to the
size of the array.

ClassNotFoundException This exception is raised when we try to


access a class whose definition is not
found.

FileNotFoundException Raised when a file is not accessible or does


not open.

IOException Thrown when an input-output operation


failed or interrupted.

InterruptedException Thrown when a thread is waiting, sleeping,


or doing some processing, and it is
interrupted.

NoSuchFieldException Thrown when a class does not contain the


field (or variable) specified.

NoSuchMethodException Thrown when accessing a method which is


not found.

NullPointerException Raised when referring to the members of a


null object. null represents nothing.

P a g e 10 | 31
Unit_V Object oriented programming with Java IV-sem | Bcom

NumberFormatException Raised when a method could not convert a


string into a numeric format.

RuntimeException This represents any exception which occurs


during runtime.

StringIndexOutOfBoundsException Thrown by String class methods to indicate


that an index is either negative or greater
than the size of the string.

User-defined Exception

In Java,

we already have some built-in exception classes like ArrayIndexOutOfBoundsException,


NullPointerException,and ArithmeticException. These exceptions are restricted to trigger
on some predefined conditions. In Java, we can write our own exception class by extends the
Exception class. We can throw our own exception on a particular condition using the throw
keyword. For creating a user-defined exception, we should have basic knowledge of the try-
catch block and throw keyword.

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:

class MyException extends Exception

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)

super(str); //call Exception class constructor and store str there.

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:

MyException me = new MyException(“Exception Details”);

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.

class MultithreadEx1 extends Thread


{
public void run()
{
[Link]("Start task one");
}
public static void main(String args[])
{
MultithreadEx1 th1 = new MultithreadEx1();
MultithreadEx1 th2 = new MultithreadEx1();
MultithreadEx1 th3 = new MultithreadEx1();
[Link]();
[Link]();
[Link]();
}
}
Output

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 :

In this example; we need to extend the thread to perform multiple tasks.

class MultithreadEx3 extends Thread


{
public void run()
{
[Link]("Start task one");
}
}
class MultithreadEx4 extends Thread
{
public void run()
{
[Link]("Start task two");
}
}
class Run
{
public static void main(String args[])
{
MultithreadEx3 th1 = new MultithreadEx3();
MultithreadEx4 th2 = new MultithreadEx4();
[Link]();
[Link]();
}
}
Output

P a g e 18 | 31
Unit_V Object oriented programming with Java IV-sem | Bcom

Uses of Threads in java:

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.

7) Explain about the Life cycle of a Thread?


During the lifetime of a thread, there are many states it can enter. They include:

 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

Figure State transition diagram of a thread

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

Figure 1 Relinquishing control using yield( ) method

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.

Relinquishing control using suspend( ) method

Relinquishing control using sleep( ) method

 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

Relinquishing control using wait( ) method

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.

8) How to Create a Thread and run it?

There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

Thread class:

Thread class provide constructors and methods to create and perform operations on a
[Link] class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:

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

o Thread(Runnable r,String name)

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().

1. public void run(): is used to perform action for a thread.

Starting a thread:

The start() method of Thread class is used to start a newly created thread. It performs the
following tasks:

o A new thread starts(with new callstack).


o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.

1) Java Thread Example by extending Thread class

FileName: [Link]

class Multi extends Thread{


public void run(){
[Link]("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
[Link]();
}
}

Output:

thread is running...

2) Java Thread Example by implementing Runnable interface

FileName: [Link]

P a g e 23 | 31
Unit_V Object oriented programming with Java IV-sem | Bcom

class Multi3 implements Runnable{


public void run(){
[Link]("thread is running...");
}

public static void main(String args[]){


Multi3 m1=new Multi3();
Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
[Link]();
}
}

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

obj : The Throwable object to be thrown.

Return

This method does not return any value.

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 {

public static void main(String args[])


{
// creating three threads
JavaStopExp t1=new JavaStopExp ();
JavaStopExp t2=new JavaStopExp ();
JavaStopExp t3=new JavaStopExp ();
// call run() method
[Link]();
[Link]();
// stop t3 thread
[Link]();
[Link]("Thread t3 is stopped");
}
}
Output:
Thread t3 is stopped
Thread-1
1
P a g e 25 | 31
Unit_V Object oriented programming with Java IV-sem | Bcom

Thread-0
1
Thread-1
2
Thread-0
2
Thread-1
3
Thread-0
3
Thread-1
4
Thread-0
4

10)What is the [Link]() in Java with Examples.

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.

The sleep() Method Syntax:

Following are the syntax of the sleep() method.

1. public static void sleep(long mls) throws InterruptedException


2. public static void sleep(long mls, int n) throws InterruptedException
mls = Milliseconds
n= 0 to 999999

The method does not return anything.

Important Points to Remember About the Sleep() Method

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

Example of the sleep() method in Java : on the custom thread

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

• The thread class defines three levels of Thread prioritys.

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

public static void main( String s[])


{
ThreadA a = new ThreadA();
ThreadB b = new ThreadB();
ThreadC c = new ThreadC();
[Link]( Thread.MIN_PRIORITY);
[Link]( Thread.MAX_PRIORITY);
[Link](5);
[Link]("ThreadA started");
[Link]();
[Link]("ThreadB started");
[Link]();
[Link]("ThreadC started");
[Link]();
}
}

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

7) What are the Methods of Thread class in java?

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

Commonly used methods of Thread class:

1. public void run(): is used to perform action for a thread.


2. public void start(): starts the execution of the [Link] calls the run() method on
the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing thread.
11. public int getId(): returns the id of the thread.
12. public [Link] getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily pause
and allow other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been interrupted.

Q) Write about Thread Synchronization?

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.

synchronized void meth( )

Some thread work;

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.

Synchronized code blocks:

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

You might also like