Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

22cs3251 Oops Using Java

The document provides an overview of Object-Oriented Programming (OOP) principles and the Java programming language, detailing concepts such as classes, objects, inheritance, polymorphism, and encapsulation. It explains the Java Virtual Machine (JVM) architecture, including the roles of the Class Loader and memory areas, as well as the differences between JDK, JRE, and JVM. Additionally, it highlights the benefits of OOP and features of Java, emphasizing its simplicity, security, robustness, and portability.

Uploaded by

anakinalt9
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

22cs3251 Oops Using Java

The document provides an overview of Object-Oriented Programming (OOP) principles and the Java programming language, detailing concepts such as classes, objects, inheritance, polymorphism, and encapsulation. It explains the Java Virtual Machine (JVM) architecture, including the roles of the Class Loader and memory areas, as well as the differences between JDK, JRE, and JVM. Additionally, it highlights the benefits of OOP and features of Java, emphasizing its simplicity, security, robustness, and portability.

Uploaded by

anakinalt9
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 208

Hindusthan College of Engineering and Technology

Hindusthan College of Engineering and Technology


An Autonomous InstitutionInstitution,
(An Autonomous Affiliated toAffiliated
Anna University | ApprovedChennai)
to Anna University, by AICTE, New Delhi
Valley
Accredited with Campus,
‘A’ Grade by NAAC | Accredited
Pollachi Highway, Coimbatore – 641032
by NBA (ECE, MECH, EEE, IT & CSE)
Valley Campus, Pollachi Highway, Coimbatore 641 032.| www.hicet.ac.in
22CS3251 / OBJECT ORIENTED PROGRAMMING
USING JAVA

UNIT 1 - INTRODUCTION TO JAVA and OOP


Object Oriented Programming - First java program Hello World - JVM architecture - JDK – JRE -
identifiers – variables – comments - command line arguments - operators in java - control structures -
Series and patterns - strings - immutable string - string operations - String Buffer class - StringBuilder
class - String Joiner - String Tokenizer.

1.1 Object Oriented Programming


Object-oriented programming (OOP) is the core of Java. OOP allows decomposition of a problem
into several entities called objects and then builds data and function around these objects. The data of
an object can be accessed only by the function associated with that object. However, function of one
object can access the function of other objects.
Object A Object B

DATA DATA

Communication
FUNCTION FUNCTION

Object C

DATA

FUNCTION

Organization of data and function in OOP


Basic Concepts of Object-Oriented Programming:
The basic Concepts used extensively in Object Oriented Programming are,
 Objects
 Classes
 Data abstraction and encapsulation
 Inheritance
 Polymorphism
 Dynamic binding
 Message passing
1. Objects :
An object is an instance of a class. Objects are variables of the type class and it is a real
time entity. Every object is associated with data and functions which define meaningful
operations on that object. An Object is a collection of data members and associated member
functions.
2.Classes:
Class is a collection of data members and member functions. Objects with similar
properties and methods are grouped together to form a Class. A Class is a collection of objects of
similar type. Characteristics of an object are represented in a class as Properties. The actions that
can be performed by objects becomes functions of the class and is referred to as Methods. No
memory is allocated when a class is created. Memory is allocated only when an object is created.
Example:
Car Santro
Class : Car
Car Alto Attributes:
Car Etios Name
Model //data members
Year of Manufacture
Colour Engine
Power
Class Object Operations:
Start( ) // member functions
Stop( )
Accelerate( )
3. Data Abstraction:
Data Abstraction increases the power of programming language by creating user defined
data types called Abstract Data Types (ADTs). Data Abstraction also represents only the essential
features and hides the implementation details.
4. Data Encapsulation:
The wrapping up of data and functions into a single unit called class is known as
Encapsulation. When using Data Encapsulation, data is not accessed directly by the program; it
is only accessible through the functions present inside the class. Data Encapsulation enables the
important concept of data hiding or information hiding.
5. Inheritance:
Inheritance is the process of deriving the properties (data members and member
functions) of one class (base class) to another class (derived class). The base class is also known
as parent class or super class, the new class that is formed will have the combined features of
both the classes and is called as derived class. Derived class is also known as a child class or sub
class. Inheritance helps in reducing the overall code size of the program, and helps in reusability
of the code.

Inheritance
6. Polymorphism:
Polymorphism means ability to take many forms. It allows a single name/operator to be
associated with different operations depending on the type of data passed to it. Examples of
polymorphism are function overloading, operator overloading and dynamic binding (virtual
functions).

Polymorphism
7. Dynamic Binding
Binding refers to the linking of a procedure call to the code to be executed in response to
the call. Dynamic binding or late binding means that the code associated with a given procedure
call is not known until the time of the call at run time.
8. Message Passing
OOPs consist of a set of objects that communicate with each other. Message passing
involves following steps-
1. Creating classes that define objects and their behavior
2. Creating objects from class definitions and
3. Establishing communication among objects through message passing.
Message passing involves specifying the name of the object, the name of the function i.e.
message and the information to be sent.
Example:
customer. balance(account no)

object message information

BENEFITS OF OOPs
OOP offers several benefits to both the program designer and the user. The advantages are:
 Through inheritance, we can eliminate redundant code and extend the use of existing
classes
 We can build program from the standard working module that communicate with one
another, rather than having to start writing the code from scratch. This leads to saving
of development time and higher productivity.
 The principle of data hiding helps the programmer to build secure programs that
cannot be invaded by code in other part of the program.
 It is possible to have multiple instances of an object to co-exist without any interference
 It is easy to partition the work in a project, based on objects.
 Object oriented systems can be easily upgraded from small to large systems.
 Message passing techniques for communication between objects makes the interface
description with external systems much simpler.
 Software complexity can be easily managed.

Difference Between Structured Programming and Object-Oriented Programming


S. No. Structured Programming Object Oriented Programming
1. The data and functions are considered The data and functions are considered as
as separate entities. single entities.
2. The abstraction is based on Algorithms. The abstraction is based on Classes and
Objects.
It does not support the concept of It supports the concept of inheritance,
3. inheritance, polymorphism, data polymorphism, data encapsulation.
encapsulation.
4. Example: C, COBOL C++, Java

Features of Java (Java buzz words):

1. Simple
Java language is simple because:
 syntax is based on C++.
 removed many confusing and/or rarely-used features e.g., explicit pointers, operator
overloading etc.
 No need to remove unreferenced objects because there is Automatic Garbage Collection
in java.

2. Object-oriented
Like C++, java uses all the OOP concepts like encapsulation, inheritance, and polymorphism etc.
Java is called a purely object-oriented language as everything we write inside class in a java
program.
3. Architecture-Neutral

Java code can be run on multiple platforms e.g., 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 run on any machine with any processor and with any OS. i.e.,
Write Once and Run Anywhere (WORA).

4. Security
When we use a Java-compatible Web browser, we can safely download Java applets
without fear of viral infection or malicious intent. Java achieves this protection by confining a
Java program to the Java execution environment and not allowing it access to other parts of the
computer. This control is exercised by JVM.

5. Robust (Strong/ Powerful):


Java programs will not crash because of its exception handling and its memory management
features. Java uses strong memory management. There is a lack of pointers that avoids security
problem. There is automatic garbage collection in java. There is exception handling and type
checking mechanism in java. All these points make java robust.

6. Portability:
Java does not have implementation dependent aspects and it yields or gives same result on any
machine. We may carry the java bytecode to any platform.

7. Distributed:
Java is designed for use on network; it has an extensive library which works in agreement with
Transmission Control Protocol (TCP) and the Internet Protocol (IP) .
We can create distributed applications in java. RMI (Remote Method Invocation) and EJB
(Enterprise JavaBeans) are used for creating distributed applications. We may access files by
calling the methods from any machine on the internet.

8. Multithreaded:
Java was designed to meet the real-world requirement of creating interactive, networked
programs. To accomplish this, Java supports multithreaded programming, which allows us to
write programs that do many things simultaneously. The Java run-time system comes with an
elegant yet sophisticated solution for multiprocess synchronization that enables us to construct
smoothly running interactive systems.

9. Dynamic
Java programs carry with them substantial amounts of run-time type information that is used to
verify and resolve accesses to objects at run time. This makes it possible to dynamically link
code in a safe and expedient manner. This is crucial to the robustness of the applet environment,
in which small fragments of byte code may be dynamically updated on a running system.

1.2 JVM
Java Virtual Machine (JVM) is the engine that drives the Java code. Mostly in other Programming
Languages, compiler produce code for a particular systembut Java compiler produce Bytecode for a Java
Virtual Machine. When we compile a Java program, then bytecode is generated. Bytecode is the source
code that can be used to run on any platform. Bytecode is an intermediary language between Java source
and the host system. It is the medium which compiles Java code to bytecode which gets interpreted on a
different machine and hence it makes it Platform/Operating system independent.

JVM generates a .class(Bytecode) file, and that file can be run in any OS, but JVM should have in OS
because JVM is platform dependent.

The Java Architecture


Java Virtual Machine acts as a run-time engine to run Java applications. JVM is the one that 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.

Class Loader Subsystem


It is mainly responsible for three activities.
 Loading
 Linking
 Initialization

Loading: The Class loader reads the “.class” file, generate the corresponding binary data and save it in
the method area. For each “.class” file, JVM stores the following information in the method area.
 The fully qualified name of the loaded class and its immediate parent class.
 Whether the “.class” file is related to Class or Interface or Enum.
 Modifier, Variables and Method information etc.
After loading the “.class” file, JVM creates an object of type Class to represent this file in the heap
memory. Please note that this object is of type Class predefined in java.lang package. These Class object
can be used by the programmer for getting class level information like the name of the class, parent
name, methods and variable information etc. To get this object reference we can use getClass() method
of Object class.

Linking: Performs verification, preparation, and (optionally) resolution.


 Verification: It ensures the correctness of the .class file i.e. it checks whether this file is properly
formatted and generated by a valid compiler or not. If verification fails, we get run-time
exception java.lang.VerifyError. This activity is done by the component ByteCodeVerifier.
Once this activity is completed then the class file is ready for compilation.
 Preparation: JVM allocates memory for class static variables and initializing the memory to
default values.
 Resolution: It is the process of replacing symbolic references from the type with direct
references. It is done by searching into the method area to locate the referenced entity.

Initialization: In this phase, all static variables are assigned with their values defined in the code and
static block (if any). This is executed from top to bottom in a class and from parent to child in the class
hierarchy.
In general, there are three class loaders:
 Bootstrap class loader: Every JVM implementation must have a bootstrap class loader, capable
of loading trusted classes. It loads core java API classes present in the “JAVA_HOME/jre/lib”
directory. This path is popularly known as the bootstrap path. It is implemented in native
languages like C, C++.
 Extension class loader: It is a child of the bootstrap class loader. It loads the classes present in
the extensions directories “JAVA_HOME/jre/lib/ext”(Extension path) or any other directory
specified by the java.ext.dirs system property. It is implemented in java by the
sun.misc.Launcher$ExtClassLoader class.
 System/Application class loader: It is a child of the extension class loader. It is responsible to
load classes from the application classpath. It internally uses Environment Variable which
mapped to java.class.path. It is also implemented in Java by the
sun.misc.Launcher$AppClassLoader class.
JVM Memory
1. Method area: In the method area, all class level information like class name, immediate parent
class name, methods and variables information etc. are stored, including static variables. There
is only one method area per JVM, and it is a shared resource. From java 8, static variables are
now stored in Heap area.
2. Heap area: Information of all objects is stored in the heap area. There is also one Heap Area
per JVM. It is also a shared resource.
3. Stack area: For every thread, JVM creates one run-time stack which is stored here. Every block
of this stack is called activation record/stack frame which stores methods calls. All local
variables of that method are stored in their corresponding frame. After a thread terminates, its
run-time stack will be destroyed by JVM. It is not a shared resource.
4. PC Registers: Store address of current execution instruction of a thread. Obviously, each thread
has separate PC Registers.
5. Native method stacks: For every thread, a separate native stack is created. It stores native
method information.

JVM
JVM is the abbreviation for Java virtual machine which is basically specification that provides a
runtime environment in which Java byte code can be executed i.e it is something which is abstract and
its implementation is independent to choose the algorithm and has been provided by Sun and other
companies. It is JVM which is responsible for converting Byte code to the machine specific code. It
can also run those programs which are written in other languages and compiled to Java bytecode.The
JVM performs the mentioned tasks: Loads code, Verifies code, Executes code, Provides runtime
environment.

JRE
JRE is Java runtime environment which is the implementation of JVM i.e the specifications which are
defined in JVM are implemented and creates corresponding environment for the execution of code.JRE
comprises mainly java binaries and other classes to execute the program alike of JVM it physically
exists. Along with Java binaries JRE also consist of various technologies of deployment, user interfaces
to interact with code executed, some base libraries for different functionalities and language and util
based libraries.
JDK
JDK is abbreviation for Java Development Kit which includes all the tools, executable and binaries
required to compile, debug and execute a Java Program.JDK is platform dependent i.e there is separate
installers for Windows, Mac, and Unix systems.JDK includes both JVM and JRE and is entirely
responsible for code execution. It is the version of JDK which represent version of Java.

S.
Key JDK JRE JVM
No.

Definition JDK (Java Development JRE (Java Runtime JVM (Java Virtual Machine) is
Kit) is a software Environment) is the an abstract machine that is
development kit to implementation of platform-dependent and has
develop applications in JVM and is defined as three notions as a specification,
Java. In addition to JRE, a software package a document that describes
JDK also contains that provides Java requirement of JVM
number of development class libraries, along implementation,
1
tools (compilers, with Java Virtual implementation, a computer
JavaDoc, Java Debugger Machine (JVM), and program that meets JVM
etc.). other components to requirements, and instance, an
run applications implementation that executes
written in Java Java byte code provides a
programming. runtime environment for
executing Java byte code.

Prime JDK is primarily used for On other hand JRE is JVM on other hand specifies all
functionality code execution and has majorly responsible for the implementations and
2
prime functionality of creating environment responsible to provide these
development. for code execution. implementations to JRE.

Platform JDK is platform Like of JDK JRE is JVM is platform independent.


Independence dependent i.e for also platform
3
different platforms dependent.
different JDK required.
S.
Key JDK JRE JVM
No.

Tools As JDK is responsible On other hand JRE JVM does not include software
for prime development does not contain tools development tools.
so it contains tools for such as compiler or
developing, debugging debugger etc. Rather it
4
and monitoring java contains class libraries
application. and other supporting
files that JVM requires
to run the program.

Implementation JDK = Java Runtime JRE = Java Virtual JVM = Only Runtime
Environment (JRE) + Machine (JVM) + environment for executing the
5
Development tools Libraries to run the Java byte code.
application

1.3 STRUCTURE OF JAVA PROGRAMMING


The Basic Structure of a Simple Java program
A Java program consists of different sections. Some of them are mandatory but some areoptional. The
optional section can be excluded from the program depending upon the requirements of the programmer.

Documentation Section
It includes the comments that improve the readability of the program. A comment is a non- executable
statement that helps to read and understand a program especially when your programs get more complex.
 Eg:1
// Calculate sum of two numbers
 Eg:2
/*calculate sum of two
numbersand it is a multiline
comment */

Package Statement
A package is a collection of classes, interfaces and sub-packages. A sub package contains
collection of classes, interfaces and sub-sub packages etc.
java.lang.*; package is imported by default and this package is known as default package. It must
appear as the first statement in the source code file before any class or interface declaration. This
statement is optional.

Import statements
An import statement is used for referring classes that are declared in other packages. The import
statement is written after a package statement but before any class definition. You can import a
specific class or all the classes of the package.
Example If you want to import Date class of java.util package using import statement then write.
import java.util.Date;

Interface Section
In the interface section, we specify the interfaces. An interface is similar to a class but contains
only constants and method declarations.

Class Definition:
Java program may contain multiple class definition. Classes are primary feature of Java program.
The classes are used to map real world problems.

Main Method Class Section:


Every program in Java consists of at least one class, the one that contains the main method. The
main () method which is from where the execution of program actually starts and follow the
statements in the order specified. The class section is mandatory.
First Java Program
WAP to print a message “Welcome to Java World”
class Example
{
public static void main (String args[])
{
System.out.println ("Welcome to Java World");
}
}

Output:
Welcome to Java World

How to compile the above program:


To compile the Example program, execute the compiler, javac, specifying the name of the source
file on the command line, as shown here:
C:\>javac Example.java
The javac compiler creates a file called Example.class that contains the byte code version of the
program. As discussed earlier, the Java byte code is the intermediate representation of our
program that contains instructions the Java interpreter will execute. Thus, the output of javac is
not code that can be directly executed. To run the program, we must use the Java interpreter,
called java. To do so, pass the class name Example as a command-line argument, as shown here:
C:\>java Example
When the program is run, the following output is displayed:
Welcome to Java World

Explanation of above program


public static void main(String args[])
All Java applications begin execution from main ( ) function. (This is just like C/C++.)
 The public keyword is an access specifier, which allows the programmer to control the
visibility of class members. When a class member is preceded by public, then that
member may be accessed by code outside the class in which it is declared. It also tells
thecompiler to access the class.
 The keyword static is reserved keyword which means that a method is accessible and
usable even though no objects of the class exist
 The keyword void simply tells the compiler that main ( ) does not return a value.
 main ( ) is the method called when a Java application begins. Keep in mind that Java is
case-sensitive. Thus, Main is different from main.
 String args[ ] declares a parameter named args, which is an array of instances of the
class String. (Arrays are collections of similar objects.) Objects of type String store
character strings. In this case, args receives any command-line arguments present when
the program is executed.
System.out.println ("This is a simple Java program.");
This line outputs the string “This is a simple Java program.” followed by a new line on
the screen. Output is actually accomplished by the built-in println( ) method. In this
case, println( ) displays the string which is passed to it.

1.4 Identifiers
Identifiers in Java are symbolic names used for identification. They can be a class name, variable name,
method name, package name, constant name, and more. There are some reserved words that cannot be
used as an identifier.
Example:
public class HelloJava {
public static void main(String[] args) {
System.out.println("Hello JavaTpoint");
}
}
From the above example, we have the following Java identifiers:
1. HelloJava (Class name)
2. main (main method)
3. String (Predefined Class name)
4. args (String variables)
5. System (Predefined class)
6. out (Variable name)
7. println (method)

Rules for Identifiers in Java


There are some rules and conventions for declaring the identifiers in Java. If the identifiers are not
properly declared, we may get a compile-time error. Following are some rules and conventions for
declaring identifiers:
 A valid identifier must have characters [A-Z] or [a-z] or numbers [0-9], and underscore(_) or a
dollar sign ($). for example, @javatpoint is not a valid identifier because it contains a special
character which is @.
 There should not be any space in an identifier. For example, java point is an invalid identifier.
 An identifier should not contain a number at the starting. For example, 123javatpoint is an invalid
identifier.
 An identifier should be of length 4-15 letters only. However, there is no limit on its length. But
it is good to follow the standard conventions.
 We cannot use the Java reserved keywords as an identifier such as int, float, double, char, etc.
For example, int double is an invalid identifier in Java.
 An identifier should not be any query language keywords such as SELECT, FROM, COUNT,
DELETE, etc.

Java Reserved Keywords


Java reserved keywords are predefined words, which are reserved for any functionality or meaning. We
cannot use these keywords as our identifier names, such as class name or method name. These keywords
are used by the syntax of Java for some functionality. If we use a reserved word as our variable name, it
will throw an error. In Java, every reserved word has a unique meaning and functionality. Some of the
reserved keywords in Java are:
abstract continue for protected transient
assert default goto public try
boolean do if static throws
break double implements strictfp package
byte else import super private
case enum interface short switch
catch extends instanceof return void
char final int synchronized volatile
class finally long throw date
const float native this while

Example of Valid and Invalid Identifiers


Valid identifiers: Following are some examples of valid identifiers in Java:
TestVariable
testvariable
a
i
Test_Variable
_testvariable
$testvariable
sum_of_array
TESTVARIABLE
num123
NumBer12
Invalid identifiers: Below are some examples of invalid identifiers:
Test Variable ( We cannot include a space in an identifier)
123java (The identifier should not begin with numbers)
java+point (The plus (+) symbol cannot be used)
a-javatpoint (Hyphen symbol is not allowed)
java_&_Tpoint (ampersand symbol is not allowed)
Java'point (we cannot use an apostrophe symbol in an identifier)

Data types
Data type defines the values that a variable can take. For example, if a variable has int data type, it can
only take integer values.
Primitive Data types:

byte
 This can hold whole number between -128 and 127.
 Mostly used to save memory and when you are certain that the numbers would be in the limit
specified by byte data type.
 Default size of this data type: 1 byte. Default value: 0
Example:
class JavaExample
{
public static void main(String[] args)
{
byte num;
num = 113;
System.out.println(num);
}
}
short & int
 Short: This is greater than byte in terms of size and less than integer. Its range is -32,768 to
32767.
 Default size of this data type: 2 byte short num = 45678;
 int: Used when short is not large enough to hold the number, it has a wider range: -
2,147,483,648 to 2,147,483,647
 Default size: 4 byte Default value: 0
Example
class JavaExample
{
public static void main(String[] args)
{
short num;
num = 150;
System.out.println(num); }
}
}
Output
150

long
 Used when int is not large enough to hold the value, it has wider range than int data type,
ranging from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
 size: 8 bytes
 Default value: 0
Example
class JavaExample
{
public static void main(String[] args)
{
long num = -12332252626L;
System.out.println(num);
}
}
Output
-12332252626

double
 Sufficient for holding 15 decimal digits
 size: 8 bytes
Example
class JavaExample
{
public static void main(String[] args)
{
double num = -42937737.9d;
System.out.println(num);
}
}
Output
-4.29377379E7

float
 Sufficient for holding 6 to 7 decimal digits
 size: 4 bytes
class JavaExample
{
public static void main(String[] args)
{
float num = 19.98f;
System.out.println(num);
}
}
Output
19.98

boolean
 boolean: holds either true of false.
class JavaExample
{
public static void main(String[] args)
{
boolean b = false;
System.out.println(b);
}
}
Output
false

char
 char: holds characters.
 size: 2 bytes
class JavaExample
{
public static void main(String[] args)
{
char ch = 'Z';
System.out.println(ch);
}
}
Output
Z

1.5 Variables
In Java, Variables are the data containers that save the data values during Java program
execution. Every Variable in Java is assigned a data type that designates the type and quantity of value
it can hold. A variable is a memory location name for the data. Java variable is a name given to a memory
location. It is the basic unit of storage in a program. The value stored in a variable can be changed during
program execution. Variables in Java are only a name given to a memory location. All the operations
done on the variable affect that memory location. In Java, all variables must be declared before use.
Syntax:
datatype variablename;
The Scope and Lifetime of Variables:
Java allows variables to be declared within any block. A block is begun with an opening curly
brace and ended by a closing curly brace. A block defines a scope. The scope defined by a method begins
with its opening curly brace. Variables declared inside a scope are not visible (that is, accessible)to code
that is defined outside that scope. Scopes can be nested. When this occurs, the outer scope encloses the
inner scope. This means that objects declared in the outer scope will be visible to code within the inner
scope. However, Objects declared within the inner scope will not be visible outside it. To understand
the effect of nested scopes, consider the following program:
class Scope
{
public static void main(String args[])
{
int x; // known to all code within main x = 10;
if(x == 10)
{ // start new scope
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here. System.out.println("x is " + x);
}
}
As the comments indicate, the variable x is declared at the start of main( )’s scope and is
accessible to all subsequent code within main( ). Within the if block, y is declared. Since a block defines
a scope, y is only visible to other code within its block and lifetime of y is over once it comes out from
the block. Within the f block, x can be used because code within a block (that is, a nested scope) has
access to variables declared by an enclosing scope. Also, a variable declared within a block will lose its
value when the block is left. Thus, the lifetime of a variable is confined to its scope. If a variable
declaration includes an initializer, then that variable will be reinitialized each time the block in which it
is declared is entered. There are three types of variables in Java:
 local variable
 instance variable
 static variable
a) Local Variable
A variable declared inside the body of the method is called local variable. You can use this variable only
within that method and the other methods in the class are not even aware that the variable exists. A local
variable cannot be defined with "static" keyword.
b) Instance Variable
A variable declared inside the class but outside the body of the method, is called instance variable. It is
not declared as static. It is called instance variable because its value is instance specific and is not shared
among instances.
c) Static variable
A variable which is declared as static is called static variable. It cannot be local. You can create a single
copy of static variable and share among all the instances of the class. Memory allocation for static
variable happens only once when the class is loaded in the memory
Example
class A
{
int data=50;//instance variable
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
}//end of class

1.6 Comments
Three types of comments or comment lines are defined by Java i.e. single-line, multiline and
documentation comment line. Comment lines are never executed during program execution. They
included in a program just to convey some message to the programmer or user.
// single line comment: Single line comment is used, when comments consists of a line.
/* multi line
Comment*/: Multiline comment is used, when comments consists of more than one line.
/** documentation Comment */: Documentation comment is used to include documentation part of a
program.

1.7 Command Line Arguments


Java command-line argument is an argument i.e., passed at the time of running the Java program. In
Java, the command line arguments passed from the console can be received in the Java program and
they can be used as input. The users can pass the arguments during the execution bypassing the
command-line arguments inside the main() method.
When command-line arguments are supplied to JVM, JVM wraps these and supplies them to args[]. It
can be confirmed that they are wrapped up in an args array by checking the length of args using
args.length. Internally, JVM wraps up these command-line arguments into the args[ ] array that we pass
into the main() function. We can check these arguments using args.length method. JVM stores the first
command-line argument at args[0], the second at args[1], the third at args[2], and so on.
Example
import java.util.*;
public class Main
{
public static void main(String args[])
{
int a, b, c;
String s = args[0]+args[1];
System.out.println(args[0]);
System.out.println(args[1]);
System.out.println(s);
a = Integer.parseInt(args[0]);
b = Integer.parseInt(args[1]);
c = a + b;
System.out.println("Sum = "+c);
}
}
Output
3
4
34
Sum = 7

1.8 Operators
Operators are the symbols used for performing specific operations. Each operator performs specific
operations. Java provides many types of operators:
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Assignment Operator
 Unary Operators
 Ternary Operator
 Bitwise Operators
 Shift Operators
 instance of operator
1. Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.

Operator Name Description Example

+ Addition Adds together two values x+y

- Subtraction Subtracts one value from another x-y

* Multiplication Multiplies two values x*y

/ Division Divides one value by another x/y

% Modulus Returns the division remainder x%y

++ Increment Increases the value of a variable by 1 ++x

-- Decrement Decreases the value of a variable by 1 --x


Example
class Main
{
public static void main (String[] args)
{
int a = 10;
int b = 3;
System.out.println("a + b = " + (a + b));
System.out.println("a - b = " + (a - b));
System.out.println("a * b = " + (a * b));
System.out.println("a / b = " + (a / b));
System.out.println("a % b = " + (a % b));
}
}
Output
a + b = 13
a-b=7
a * b = 30
a/b=3
a%b=1

2. Relational Operator
These operators are used to check for relations like equality, greater than, and less than. They return
boolean results after the comparison and are extensively used in looping statements as well as
conditional if-else statements.

Operator Name Example

== Equal to x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y


Example
class Main
{
public static void main(String[] args)
{
int a = 10;
int b = 3;
int c = 5;
System.out.println("a > b: " + (a > b));
System.out.println("a < b: " + (a < b));
System.out.println("a >= b: " + (a >= b));
System.out.println("a <= b: " + (a <= b));
System.out.println("a == c: " + (a == c));
System.out.println("a != c: " + (a != c));
}
}
Output
a > b: true
a < b: false
a >= b: true
a <= b: false
a == c: false
a != c: true

3. Logical Operators
These operators are used to perform “logical AND” and “logical OR” operations, i.e., a function like
AND gate and OR gate in digital electronics.

Operator Name Description Example

&& Logical and Returns true if both statements are true x < 5 && x < 10

|| Logical or Returns true if one of the statements is true x < 5 || x < 4

! Logical not Reverse the result, returns false if the result is !(x < 5 && x < 10)
true
Example
class Main
{
public static void main(String[] args)
{
boolean x = true;
boolean y = false;
System.out.println("x && y: " + (x && y));
System.out.println("x || y: " + (x || y));
System.out.println("!x: " + (!x));
}
}
Output
x && y: false
x || y: true
!x: false

4. Assignment Operator
Assignment operator (=) is used to assign a value to any variable. It has right-to-left associativity, i.e.
value given on the right-hand side of the operator is assigned to the variable on the left. The assignment
operator can be combined with other operators to build a shorter version of the statement called a
Compound Statement.
For example, instead of a = a+5, we can write a += 5.
 +=, for adding the left operand with the right operand and then assigning it to the variable on the
left.
 -=, for subtracting the right operand from the left operand and then assigning it to the variable
on the left.
 *=, for multiplying the left operand with the right operand and then assigning it to the variable
on the left.
 /=, for dividing the left operand by the right operand and then assigning it to the variable on the
left.
 %=, for assigning the modulo of the left operand by the right operand and then assigning it to
the variable on the left.
Example
class Main
{
public static void main(String[] args)
{
int f = 7;
System.out.println("f += 3: " + (f += 3));
System.out.println("f -= 2: " + (f -= 2));
System.out.println("f *= 4: " + (f *= 4));
System.out.println("f /= 3: " + (f /= 3));
System.out.println("f %= 2: " + (f %= 2));
System.out.println("f &= 0b1010: " + (f &= 0b1010));
System.out.println("f |= 0b1100: " + (f |= 0b1100));
System.out.println("f ^= 0b1010: " + (f ^= 0b1010));
System.out.println("f <<= 2: " + (f <<= 2));
System.out.println("f >>= 1: " + (f >>= 1));
System.out.println("f >>>= 1: " + (f >>>= 1));
}
}
Output
f += 3: 10
f -= 2: 8
f *= 4: 32
f /= 3: 10
f %= 2: 0
f &= 0b1010: 0
f |= 0b1100: 12
f ^= 0b1010: 6
f <<= 2: 24
f >>= 1: 12
f >>>= 1: 6

5. Unary Operators
Unary operators need only one operand. They are used to increment, decrement, or negate a value.
 Unary minus (-), used for negating the values.
 Unary plus (+) indicates the positive value (numbers are positive without this, however).
 Increment operator (++), used for incrementing the value by 1. There are two varieties of
increment operators.
 Post-Increment: Value is first used for computing the result and then incremented.
 Pre-Increment: Value is incremented first, and then the result is computed.
 Decrement operator (--), used for decrementing the value by 1. There are two varieties of
decrement operators.
 Post-decrement: Value is first used for computing the result and then
decremented.
 Pre-Decrement: The value is decremented first, and then the result is computed.
Example
class Main
{
public static void main(String[] args)
{
int a = 10;
int b = 10;
System.out.println("Postincrement : " + (a++));
System.out.println("Preincrement : " + (++a));
System.out.println("Postdecrement : " + (b--));
System.out.println("Predecrement : " + (--b));
}
}
Output
Postincrement : 10
Preincrement : 12
Postdecrement : 10
Predecrement : 8

6. Ternary Operator
The ternary operator is a shorthand version of the if-else statement. It has three operands and hence the
name Ternary.
Syntax
condition ? if true : if false
Example
class Main
{
public static void main(String[] args)
{
int a = 20, b = 10, result;
result = (a > b) ? a : b;
System.out.println("Max of two numbers = "+ result);
}
}
Output
Max of two numbers = 20

7. Bitwise Operators
These operators are used to perform the manipulation of individual bits of a number. They can be used
with any of the integer types.
 &, Bitwise AND operator: returns bit by bit AND of input values.
 |, Bitwise OR operator: returns bit by bit OR of input values.
 ^, Bitwise XOR operator: returns bit-by-bit XOR of input values.
 ~, Bitwise Complement Operator: This is a unary operator which returns the one’s complement
representation of the input value, i.e., with all bits inverted.
Example
class Main
{
public static void main(String[] args)
{
int d = 0b1010;
int e = 0b1100;
System.out.println("d & e: " + (d & e));
System.out.println("d | e: " + (d | e));
System.out.println("d ^ e: " + (d ^ e));
System.out.println("~d: " + (~d));
System.out.println("d << 2: " + (d << 2));
System.out.println("e >> 1: " + (e >> 1));
System.out.println("e >>> 1: " + (e >>> 1));
}
}
Output
d & e: 8
d | e: 14
d ^ e: 6
~d: -11
d << 2: 40
e >> 1: 6
e >>> 1: 6

8. Shift Operators
These operators are used to shift the bits of a number left or right, thereby multiplying or dividing the
number by two, respectively. They can be used when we have to multiply or divide a number by two.
 <<, Left shift operator: shifts the bits of the number to the left and fills 0 on voids left as a result.
Similar effect as multiplying the number with some power of two.
 >>, Signed Right shift operator: shifts the bits of the number to the right and fills 0 on voids left
as a result. The leftmost bit depends on the sign of the initial number. Similar effect to dividing
the number with some power of two.
Example
class Main
{
public static void main(String[] args)
{
int a = 10;
System.out.println("a<<1 : " + (a << 1));
System.out.println("a>>1 : " + (a >> 1));
}
}
Output
a<<1 : 20
a>>1 : 5

1.9 Control Statements


A programming language uses control statements to control the flow of execution of a program based
on certain conditions. Java’s Selection statements:
 if
 switch-case
 jump
i) If Statements
 Simple if
 If else
 If-else-if Ladder
 Nested if

a) Simple if
It is used to decide whether a certain statement or block of statements will be executed or not. If
a certain condition is true then a block of statements is executed otherwise not.
Syntax
if(condition)
{
// Statements to execute if
// condition is true
}
The statements will be evaluated if the value of the condition is true

Example
import java.util.*;
class Main
{
public static void main(String args[])
{
int n;
Scanner in = new Scanner(System.in);
System.out.println("Enter n: ");
n = in.nextInt();
if(n>0)
System.out.println(n+" is a positive number!");
}
}
Output
Enter n:
3
3 is a positive number!
b) If-else Syntax
Together with if, else statement can be used to execute a block of code when the condition is
false.
Syntax:
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}

Example
import java.util.*;
class Main
{
public static void main(String args[])
{
int n;
Scanner in = new Scanner(System.in);
System.out.println("Enter n: ");
n = in.nextInt();
if(n>=10 && n<100)
System.out.println(n+" is a Two digit number!");
else
System.out.println(n+" is not a Two digit number!");
}
}
Output
Enter n:
86
86 is a Two digit number!
c) Nested if
A nested if is an if statement that is the target of another if or else. Nested if statements mean an
if statement inside an if statement.
Syntax
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}

Example
import java.util.*;
class Main
{
public static void main(String args[])
{
int n1, n2, n3;
Scanner in = new Scanner(System.in);
System.out.println("Enter 3 numbers: ");
n1 = in.nextInt();
n2 = in.nextInt();
n3 = in.nextInt();
if(n1>n2)
{
if(n1>n3)
{
System.out.println(n1+" is greater!");
}
}
else
{
if(n2>n3)
System.out.println(n2+" is greater!");
else
System.out.println(n3+" is greater!");
}
}
}
Output
Enter 3 numbers:
89
125
36
125 is greater!

d) if-else-if ladder
Syntax:
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;

Example
import java.util.*;
class Main
{
public static void main(String args[])
{
int mark;
Scanner in = new Scanner(System.in);
System.out.println("Enter a mark: ");
mark = in.nextInt();
if(mark>90)
{
System.out.println("Grade - O");
}
else if(mark>80)
{
System.out.println("Grade - A");
}
else if(mark>70)
{
System.out.println("Grade - B");
}
else if(mark>60)
{
System.out.println("Grade - C");
}
else if(mark>=50)
{
System.out.println("Grade - D");
}
else
{
System.out.println("Fail");
}
}
}
Output
Enter a mark:
86
Grade – A

ii) switch
The switch statement is a multiway branch statement. It provides an easy way to dispatch execution
to different parts of code based on the value of the expression. Syntax
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
Example
import java.util.*;
class Main
{
public static void main(String args[])
{
int n;
Scanner in = new Scanner(System.in);
System.out.println("Enter n: ");
n = in.nextInt();
switch(n)
{
case 1 :
System.out.println("Monday");
break;
case 2 :
System.out.println("Tuesday");
break;
case 3 :
System.out.println("Wednesday");
break;
case 4 :
System.out.println("Thursday");
break;
case 5 :
System.out.println("Friday");
break;
case 6 :
System.out.println("Saturday");
break;
case 7 :
System.out.println("Sunday");
break;
default:
System.out.println("Invalid");
}
}
}
Output
Enter n:
5
Friday

iii) Jump
jump: Java supports three jump statements: break and continue. These statements transfer control to
another part of the program.
a) break: In Java, a break is majorly used to terminate a sequence in a switch statement.
b) continue: Sometimes it is useful to force an early iteration of a loop.
Example for break
import java.util.*;
class Main
{
public static void main(String args[])
{
int n;
Scanner in = new Scanner(System.in);
System.out.println("Enter n: ");
n = in.nextInt();
for (int i = 1; i < n; i++)
{
if (i == 5)
break;
System.out.print(i + " ");
}
}
}
Output
Enter n:
10
1234

Example for continue


import java.util.*;
class Main
{
public static void main(String args[])
{
int n;
Scanner in = new Scanner(System.in);
System.out.println("Enter n: ");
n = in.nextInt();
for (int i = 0; i < n; i++)
{
if (i % 2 == 0)
continue;
System.out.print(i + " ");
}
}
}
Output
Enter n:
20
1 3 5 7 9 11 13 15 17 19

1.10 String Class


The string is a sequence of characters. In Java, objects of String are immutable which means a constant
and cannot be changed once created. The String class has a set of built-in methods that you can use on
strings.
Method Description
charAt() Returns the character at the specified index (position)

compareTo() Compares two strings lexicographically

compareToIgnoreCase() Compares two strings lexicographically, ignoring case


differences

concat() Appends a string to the end of another string

contains() Checks whether a string contains a sequence of characters

copyValueOf() Returns a String that represents the characters of the character


array

endsWith() Checks whether a string ends with the specified character(s)

equals() Compares two strings. Returns true if the strings are equal, and
false if not

equalsIgnoreCase() Compares two strings, ignoring case considerations

getChars() Copies characters from a string to an array of chars

indexOf() Returns the position of the first found occurrence of specified


characters in a string

isEmpty() Checks whether a string is empty or not

lastIndexOf() Returns the position of the last found occurrence of specified


characters in a string

length() Returns the length of a specified string

replace() Searches a string for a specified value, and returns a new string
where the specified values are replaced

replaceFirst() Replaces the first occurrence of a substring that matches the given
regular expression with the given replacement

replaceAll() Replaces each substring of this string that matches the given
regular expression with the given replacement

split() Splits a string into an array of substrings

startsWith() Checks whether a string starts with specified characters

substring() Returns a new string which is the substring of a specified string

toCharArray() Converts this string to a new character array

toLowerCase() Converts a string to lower case letters


toString() Returns the value of a String object

toUpperCase() Converts a string to upper case letters

trim() Removes whitespace from both ends of a string

valueOf() Returns the string representation of the specified value

Program
class Main
{
public static void main(String args[])
{
String s = "Java programming";
System.out.println("String length = " + s.length());
System.out.println("Character at 3rd position = "+ s.charAt(3));
System.out.println("Substring " + s.substring(3));
System.out.println("Substring = " + s.substring(2,5));
String s1 = "C++";
String s2 = "Programming";
System.out.println("Concatenated string = " +s1.concat(s2));
String s4 = "Python Programming";
System.out.println("Index of on " +s4.indexOf("on"));
System.out.println("Index of a = " +s4.indexOf('a',3));
Boolean out = "Java".equals("Java");
System.out.println("Checking Equality " + out);
out = "java".equals("Java");
System.out.println("Checking Equality " + out);
out = "java".equalsIgnoreCase("Java");
System.out.println("Checking Equality " + out);
int out1 = s1.compareTo(s2);
System.out.println("the difference between ASCII value is="+out1);
String word = "Hello";
System.out.println("Changing to lower Case " +word.toLowerCase());
System.out.println("Changing to UPPER Case " +word.toUpperCase());
String word1 = " Java is easy to learn ";
System.out.println("Trim the word " + word1.trim());
String str1 = "Java programming";
System.out.println("Original String " + str1);
String str2 = str1.replace("Java" ,"C") ;
System.out.println("Replaced Java with C -> " + str2);
}
}
Output
String length = 16
Character at 3rd position = a
Substring a programming
Substring = va
Concatenated string = C++Programming
Index of on 4
Index of a = 12
Checking Equality true
Checking Equality false
Checking Equality true
the difference between ASCII value is=-13
Changing to lower Case hello
Changing to UPPER Case HELLO
Trim the word Java is easy to learn
Original String Java programming
Replaced Java with C -> C programming

StringBuffer class
StringBuffer is a class in Java that represents a mutable sequence of characters. It provides an
alternative to the immutable String class, allowing to modify the contents of a string without
creating a new object every time.
Example
class Main
{
public static void main(String args[])
{
StringBuffer s = new StringBuffer("Java programming");
System.out.println("String length = " + s.length());
System.out.println("String capacity = "+s.capacity());
System.out.println("Character at 3rd position = "+ s.charAt(3));
System.out.println("Substring " + s.substring(3));
System.out.println("Substring = " + s.substring(2,5));
StringBuffer s1 = new StringBuffer("C++");
StringBuffer s2 = new StringBuffer(" Programming");
System.out.println("Concatenated string = " +s1.append(s2));
System.out.println("String1 = " + s1);
System.out.println("String2 = " + s2);
s1.insert(15," is easy to learn");
System.out.println("String1 = " + s1);
s1.replace(0,3, "Java");
System.out.println("String1 = " + s1);
s1.delete(0, 4);
System.out.println("String1 = " + s1);
s1.reverse();
System.out.println("String1 = " + s1);
}
}
Output
String length = 16
String capacity = 32
Character at 3rd position = a
Substring a programming
Substring = va
Concatenated string = C++ Programming
String1 = C++ Programming
String2 = Programming
String1 = C++ Programming is easy to learn
String1 = Java Programming is easy to learn
String1 = Programming is easy to learn
String1 = nrael ot ysae si gnimmargorP

StringBuilder
Java StringBuilder class is used to create mutable (modifiable) String. The Java StringBuilder class is
same as StringBuffer class except that it is non-synchronized.
StringBuilder Constructors
 StringBuilder(): Constructs a string builder with no characters in it and an initial capacity of 16
characters.
 StringBuilder(int capacity): Constructs a string builder with no characters in it and an initial
capacity specified by the capacity argument.
 StringBuilder(CharSequence seq): Constructs a string builder that contains the same
characters as the specified CharSequence.
 StringBuilder(String str): Constructs a string builder initialized to the contents of the specified
string.
Example
import java.util.*;
public class Main
{
public static void main(String args[])
{
StringBuilder str = new StringBuilder();
str.append("StringBuilder");
System.out.println("String = " + str.toString());
StringBuilder str1 = new StringBuilder("Class");
System.out.println("String1 = " + str1.toString());
StringBuilder str2 = new StringBuilder(10);
System.out.println("String2 capacity = "+ str2.capacity());
StringBuilder str3 = new StringBuilder(str1.toString());
System.out.println("String3 = " + str3.toString());
str3.reverse();
System.out.println("Reversed String3 = " + str3.toString());
}
}
Output
String = StringBuilder
String1 = Class
String2 capacity = 10
String3 = Class
Reversed String3 = ssalC

StringJoiner
StringJoiner is a class in java.util package is used to construct a sequence of characters(strings) separated
by a delimiter and optionally starting with a supplied prefix and ending with a given suffix. StringJoiner
provides an easy way to do that without much code to write.
StringJoiner Constructors
• StringJoiner(CharSequence delimiter): It constructs a StringJoiner with no characters, no
prefix or suffix, and a copy of the supplied delimiter.

• StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix): It


constructs a StringJoiner with no characters using copies of the supplied prefix, delimiter, and
suffix. If no characters are added to the StringJoiner and methods accessing the string value are
invoked, it will return the prefix + suffix (or properties thereof) in the result
unless setEmptyValue has first been called.

Method Action Performed

Adds a copy of the given CharSequence value as the next element of the
add()
StringJoiner value. If newElement is null, then “null” is added.

length() Returns the length of the String representation of this StringJoiner.

Adds the contents of the given StringJoiner without prefix and suffix as the next
element if it is non-empty. If the given StringJoiner is empty, the call has no effect.
merge() Suppose the other StringJoiner is using a different delimiter. In that case, elements
from the other StringJoiner are concatenated with that delimiter, and the result is
appended to this StringJoiner as a single element.

toString() Returns the String object of this StringJoiner


Sets the string to be used when determining the string representation of this
setEmptyValue()
StringJoiner, and no elements have been added yet; that is when it is empty

Example
import java.util.*;
public class Main
{
public static void main(String args[])
{
StringJoiner sj1 = new StringJoiner(",");
System.out.println(sj1);
sj1.setEmptyValue("sj1 is empty");
System.out.println(sj1);
sj1.add("Java");
sj1.add("C programming");
sj1.add("Python").add("C++");
System.out.println(sj1);
System.out.println("Length of sj1 : "+ sj1.length());
StringJoiner sj2 = new StringJoiner(":");
sj2.add("Hai");
System.out.println(sj2);
sj2.add("Hello");
System.out.println(sj2);
sj1.merge(sj2);
System.out.println(sj1);
System.out.println(sj1.toString());
}
}
Output
sj1 is empty
Java,C programming,Python,C++
Length of sj1 : 29
Hai
Hai:Hello
Java,C programming,Python,C++,Hai:Hello
Java,C programming,Python,C++,Hai:Hello

StringTokenizer
StringTokenizer class in Java is used to break a string into tokens. A StringTokenizer object
internally maintains a current position within the string to be tokenized. A token is returned by taking a
substring of the string that was used to create the StringTokenizer object. It provides the first step in the
parsing process often called lexer or scanner. The String Tokenizer class allows an application to break
strings into tokens.
StringTokenizer Construtors
• StringTokenizer(String str): default delimiters like newline, space, tab, carriage return, and
form feed.
• StringTokenizer(String str, String delim): delim is a set of delimiters that are used to
tokenize the given string.
• StringTokenizer(String str, String delim, boolean flag): The first two parameters have the
same meaning wherein The flag serves the following purpose.

Method Action Performed

countTokens() Returns the total number of tokens present

hasMoreToken() Tests if tokens are present for the StringTokenizer’s string

nextElement() Returns an Object rather than String

hasMoreElements() Returns the same value as hasMoreToken

nextToken() Returns the next token from the given StringTokenizer.

Example
import java.util.*;

public class Main

{
public static void main(String args[])

StringTokenizer st1 = new StringTokenizer("Hello How are you", " ");

while (st1.hasMoreTokens())

System.out.println(st1.nextToken());

StringTokenizer st2 = new StringTokenizer("JAVA : Code : String", " :");

while (st2.hasMoreTokens())

System.out.println(st2.nextToken());

StringTokenizer st3 = new StringTokenizer("JAVA : Code : String", " :", true);

while (st3.hasMoreTokens())

System.out.println(st3.nextToken());

}
Output
Output

Hello

How

are

you

JAVA

Code

String

JAVA

:
Code

String
Hindusthan College of Engineering and Technology
Hindusthan College of Engineering and Technology
An Autonomous InstitutionInstitution,
(An Autonomous Affiliated toAffiliated
Anna University | ApprovedChennai)
to Anna University, by AICTE, New Delhi
Valley
Accredited with Campus,
‘A’ Grade by NAAC | Accredited
Pollachi Highway, Coimbatore – 641032
by NBA (ECE, MECH, EEE, IT & CSE)
Valley Campus, Pollachi Highway, Coimbatore 641 032.| www.hicet.ac.in
22CS3251 / OBJECT ORIENTED PROGRAMMING
USING JAVA

UNIT 2 - ARRAYS, CLASS AND INHERITANCE


Introduction to Arrays in java-Arrays class-declaration and initialization of an array-2D array declaration
and initialization -multi-dimensional array-Classes and objects-naming convention in java-methods-
access modifiers-constructors- copy constructors -singleton class- object class-inner class-abstract class-
Throwable class- types of inner class- static and non-static nested class-Inheritance-Types of inheritance
Difference between inheritance in C++ and Java.

1.1 Introduction to Arrays


An array is a collection of similar datatypes. All arrays are dynamically allocated. Arrays are
stored in contiguous memory. The variables in the array are ordered, and each has an index beginning
with 0. The size of an array must be specified by int or short value and not long. The size of the array
cannot be altered once initialized.
Types of Array
 One-dimensional Array. Also known as a linear array, the elements are stored in a single row.
 Two-dimensional Array. Two-dimensional arrays store the data in rows and columns.
 Multi-dimensional Array. This is a combination of two or more arrays or nested arrays.

1.2 One-dimensional Array


An array with one dimension is called one-dimensional array or single dimensional array in java. It is a
list of variables containing values that all have the same type. One dimensional array represents one row
or one column of array elements that share a common name and is distinguishable by index values. For
example, marks obtained by a student in five subjects can be represented by single-dimensional array
because these marks can be written as one row or one column.
Syntax to declare an 1D array:
dataType[] arr = new dataType[size]; (OR)
dataType []arr = new dataType[size]; (OR)
dataType arr[] = new dataType[size];
Example
int a = new int[10];
Static Initialization
int number[] = {11, 22, 33, 44, 55, 66, 77, 88, 99, 100};

Memory Representation after Initialization


Example
import java.util.*;
public class Main
{
public static void main(String[] args)
{
int [] a = new int [10];
int temp = 0, n;
Scanner in = new Scanner(System.in);
System.out.println("Enter n: ");
n = in.nextInt();
System.out.println("Enter the elements: ");
for (int i = 0; i <n; i++)
{
a[i] = in.nextInt();
}
for (int i = 0; i <n; i++)
{
for (int j = i+1; j <n; j++)
{
if(a[i] >a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.println("\nArray sorted in ascending order: ");
for (int i = 0; i <n; i++)
{
System.out.print(a[i] + " ");
}
}
}
Output
Enter n:
5
Enter the elements:
10
26
8
36
48

Array sorted in ascending order:


8 10 26 36 48

For-each Loop for Java Array


Syntax
for(data_type variable:array)
{
//body of the loop
}
Example
import java.util.*;
public class Main
{
public static void main(String[] args)
{
char c[] = new char[10];
int n;
Scanner in = new Scanner(System.in);
System.out.println("Enter n: ");
n = in.nextInt();
System.out.println("Enter the characters: ");
for (int i = 0; i <n; i++)
{
c[i] = in.next().charAt(0);
}
System.out.println("Entered characters are: ");
for (char i : c)
{
System.out.println(i);
}
}
}

Passing Array to a Method in Java


import java.util.*;
public class Main
{
public static void main(String[] args)
{
double c[] = new double[5];
Scanner in = new Scanner(System.in);
System.out.println("Enter the numbers: ");
for (int i = 0; i <5; i++)
{
c[i] = in.nextDouble();
}
System.out.println("Entered numbers are: ");
for (double i : c)
{
System.out.print(i+" ");
}
min(c);
}
static void min(double arr[])
{
double min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.print("\nMinimum value is "+min);
}
}

Anonymous Array in Java


public class Main
{
static void printArray(int arr[])
{
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}
public static void main(String args[])
{
printArray(new int[]{10,22,44,66});
}
}

1.3 Two-dimensional Array


In Java, this tabular representation of data is implemented using a two-dimensional array. A two-
dimensional array is used to store data in tabular format. Since a 2D array in Java consists of rows and
columns, we need two indices, one to refer to rows and the other to a particular column in that row.
Hence, the syntax of declaring a two-dimensional array is similar to that of a one-dimensional array with
the exception of having two square brackets instead of one:
DataType[][] ArrayName = new DataType[size][size];
Example
int a[][] = new int[3][3];
Static Initialization
int a[][] = {{1, 2, 3}, {1, 2, 3}, {1, 2, 3}};

Example
import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
int a[][] = new int[3][3];
int b[][] = new int[3][3];
int sum[][] = new int[3][3];
int r,c,i,j;
System.out.println("Enter r & c: ");
r = in.nextInt();
c = in.nextInt();
System.out.println("Enter the elements for A matrix: ");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
a[i][j] = in.nextInt();
}
}
System.out.println("Enter the elements for B matrix: ");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
b[i][j] = in.nextInt();
}
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
sum[i][j] = a[i][j] + b[i][j];
}
}
System.out.println("Sum of A & B matrix: ");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
System.out.print(sum[i][j]+"\t");
}
System.out.println();
}
}
}
Output
Enter r & c:
2
2
Enter the elements for A matrix:
1
2
3
4
Enter the elements for B matrix:
5
6
7
8
Sum of A & B matrix:
6 8
10 12

1.4 Multi-dimensional Array


A multidimensional array is an array of arrays. Each element of a multidimensional array is an
array itself. Data in multi-dimensional arrays are stored in row-major format, i.e., tabular form. To
access array elements in multidimensional arrays, more than one index is used.

1.5 Arrays Class


The Arrays class in java.util package is a part of the Java Collection Framework. This class provides
static methods to dynamically create and access Java arrays. It consists of only static methods and the
methods of Object class.
Methods in Java Array Class

Methods Action Performed

compare(array 1, array 2) Compares two arrays passed as parameters lexicographically.

Searches for the specified element in the array with the help of the
binarySearch()
Binary Search Algorithm

equals(array1, array2) Checks if both the arrays are equal or not.

fill(originalArray,
Assigns this fill value to each index of this arrays.
fillValue)

hashCode(originalArray) Returns an integer hashCode of this array instance.

sort(originalArray) Sorts the complete array in ascending order.


Methods Action Performed

spliterator(originalArray) Returns a Spliterator covering all of the specified Arrays.

Finds and returns the index of the first unmatched element between
mismatch(array1, array2)
the two specified arrays.

It returns a string representation of the contents of this array. The


string representation consists of a list of the array’s elements,
toString(originalArray) enclosed in square brackets (“[]”). Adjacent elements are separated
by the characters a comma followed by a space. Elements are
converted to strings as by String.valueOf() function.

Example
import java.util.*;
class Main
{
public static void main(String args[])
{
int a[] = {5, 78, 45, 92, 10};
int b[] = {89, 8, 65, 44, 17};
int n;
Scanner in = new Scanner(System.in);
System.out.println("Array-A before sorting: ");
for(int i : a)
{
System.out.print(i+" ");
}
Arrays.sort(a);
System.out.println("\nArray-A after sorting: ");
for(int i : a)
{
System.out.print(i+" ");
}
System.out.println("\nEnter the element to search: ");
n = in.nextInt();
System.out.println(n + " found at index = "+ Arrays.binarySearch(a, n));
System.out.println("Array-B: ");
for(int i : b)
{
System.out.print(i+" ");
}
System.out.println("\nComparing A & B: "+ Arrays.compare(a, b));
}
}
1.6 Class & Object
Class is a user-defined datatype that contains data members and Methods. It is a blueprint or prototype
from which objects are created. Class does not occupy memory. A Class in Java can contain:
 Data member
 Method
 Constructor
 Nested Class
Syntax
access_modifier class <class_name>
{
data member;
method;
constructor;
nested class;
}

Object
Object is a real time entity. It is an instance of a class. Objects are created dynamically using the new
keyword. Every object is associated with data and functions which define meaningful operations on
that object.
Syntax
Classname objectname = new Classname();
Example
import java.util.*;
class Student
{
String name;
int marks[] = new int[6];
int total;
double avg;
char grade;
Student()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter name & 6 marks: ");
name = in.nextLine();
for(int i=0;i<6;i++)
{
marks[i] = in.nextInt();
}
}
public void calculate()
{
total = 0;
for(int i=0;i<6;i++)
{
total += marks[i];
}
avg = total / 6;
if(avg >= 80 )
grade = 'A';
else if(avg >=60 )
grade = 'B';
else if(avg >=40 )
grade = 'C';
else
grade = 'D';
}
public void display()
{
System.out.println("Name: "+name);
System.out.println("Total: "+total);
System.out.println("Average :"+avg);
System.out.println("Grade: "+grade);
}
}
class Main
{
public static void main(String[] args)
{
Student obj = new Student();
obj.calculate();;
obj.display();
}
}

1.7 Access Modifiers


Access modifiers help to restrict the scope of a class, constructor, variable, method, or data member. It
provides security, accessibility, etc. to the user depending upon the access modifier used with the
element.
Types of Access Modifiers in Java
There are four types of access modifiers available in Java:
1. Private: The access level of a private modifier is only within the class. It cannot be accessed
from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be accessed
from outside the package. If no access level is specified, 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.
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.

1.8 Constructors
A constructor is a special method having name same as class name. The constructor is
automatically called immediately after the object is created, before the new operator completes. They
have no return type, not even void. Its purpose is to initialize the object of a class. It is of three types:
• Default Constructor: Constructor which takes no argument(s) is called Default Constructor.
• Parameterized constructor: Constructor which takes argument(s) is called
parameterized Constructor.
• Copy Constructor: Constructor which takes object as its argument is called copy constructor.
When a single program contains more than one constructor, then the constructor is said to be overloaded.
Example
class Box
{
double width; double height; double depth;
Box(double w, double h, double d) // Parameterized Constructor
{
width = w; height = h; depth = d;
}
Box() // Default Constructor
{
width = -1;
height = -1;
depth = -1;
}
Box(double len) // Parameterized Constructor
{
width = height = depth = len;
}
double volume()
{
return width * height * depth;
}
}
class Main
{
public static void main(String args[])
{
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol); vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol); vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
Output
Volume of mybox1 is 3000.0 Volume of mybox2 is -1.0 Volume of mycube is 343.0

Java this Keyword


The this keyword refers to the current object in a method or constructor. The most common use
of the this keyword is to eliminate the confusion between data members and parameters with the same
name. this can also be used to:
 Refer current class instance variable.
 Invoke current class method (implicitly)
 Invoke current class constructor.
 this can be passed as an argument in the method call.
 this can be passed as argument in the constructor call.
 this can be used to return the current class instance from the method.
Example
class Box
{
double width, height, depth;
Box(double width, double height, double depth)
{
this.width = width; //refers the instance variable
this.height = height;
this.depth = depth;
this.volume(); //invokes the method
}
public void volume()
{
double vol = width * height * depth;
System.out.println("Volume of box = " + vol);
}
}
class Main
{
public static void main(String args[])
{
Box mybox1 = new Box(10, 20, 15);
}
}

The final Keyword


In Java, the final keyword is used to indicate that a variable, method, or class cannot be modified or
extended. Here are some of its characteristics:
 Final variables: When a variable is declared as final, its value cannot be changed once it has
been initialized. This is useful for declaring constants.
 Final methods: When a method is declared as final, it cannot be overridden by a subclass.
 Final classes: When a class is declared as final, it cannot be extended by a subclass.
Example
import java.util.*;
class Circle
{
final double pai = 3.14;
double r, area;
Circle()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter r: ");
r = in.nextDouble();
}
public void calculate()
{
area = pai * r * r;
System.out.println("Area of Circle = "+area);
}
}
class Main
{
public static void main(String args[])
{
Circle obj = new Circle();
obj.calculate();
}
}

Garbage Collection
In Java destruction of object from memory is done automatically by the JVM. When there is no reference
to an object, then that object is assumed to be no longer needed and the memory occupied by the object
are released. This technique is called Garbage Collection. This is accomplished by the JVM.
Advantages of Garbage Collection
 Programmer does not need to worry about dereferencing an object.
 It is done automatically by JVM.
 Increases memory efficiency and decreases the chances for memory leak.
gc() Method
gc() method is used to call garbage collector explicitly. However gc() method does not guarantee that
JVM will perform the garbage collection. It only request the JVM for garbage collection. This method
is present in System and Runtime class.

The finalize () method


Sometime an object will need to perform some specific tasks before it is destroyed such as closing an
open connection or releasing any resources held. To handle such situation finalize() method is used.
finalize() method is called by garbage collection thread before collecting object. It’s the last chance for
any object to perform cleanup utility. The finalize ( ) method has this general form:
protected void finalize( )
{
// finalization code here
}
Example
class Main
{
public static void main(String[] args)
{
Main obj = new Main();
obj = null;
System.gc();
}
public void finalize()
{
System.out.println("Garbage Collected");
}
}
Output
Garbage Collected

1.9 Copy Constructor


Copy constructor in Java allows creating an exact copy on an existing object of the same class
such that changes made on the existing object do not affect the new copy. To create a copy constructor,
take the existing object as an argument and initialize the values of instance variables with the values
obtained in the object.
Example
import java.util.*;
class Circle
{
private double r, area;
final double pai = 3.14;
public Circle() { r = 10; }
public Circle(int r) { this.r = r; }
public Circle(Circle obj) { r = obj.r; }
public void calc()
{
area = pai * r * r;
System.out.println("Area of Circle = "+area);
}
}
public class Main
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
Circle obj1 = new Circle();
System.out.println("Enter r: ");
int r = in.nextInt();
Circle obj2 = new Circle(r);
Circle obj3 = new Circle(obj2);
obj1.calc();
obj2.calc();
obj3.calc();
}
}

1.10 Private Constructor


A private constructor in Java is used in restricting object creation. If a constructor is declared private,
we are not able to create an object of the class. If a constructor is declared as private, then its objects are
only accessible from within the declared class. You cannot access its objects from outside the constructor
class.
Rules for Private Constructor
 It does not allow a class to be sub-classed.
 It does not allow to create an object outside the class.
 If a class has a private constructor and when we try to extend the class, a compile-time error
occurs.
 We cannot access a private constructor from any other class.
 If all the constant methods are there in our class, we can use a private constructor.
 If all the methods are static then we can use a private constructor.
 We can use a public function to call the private constructor if an object is not initialized.
 We can return only the instance of that object if an object is already initialized.
Example
import java.util.*;
class A
{
int a;
private static A obj;
private A()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a: ");
a = in.nextInt();
}
public static A getInstance()
{
if(obj == null)
{
obj = new A();
}
return obj;
}
public void display()
{
System.out.println("a = "+a);
}
}
public class Main
{
public static void main(String args[])
{
A obj1 = A.getInstance();
A obj2 = A.getInstance();
obj1.display();
obj2.display();
}
}

1.11 Singleton Class


A java singleton class is a class that can have only one object (an instance of the class) at a time.
After the first time, if we try to instantiate the Java Singleton classes, the new variable also points to the
first instance created. There are two forms of singleton design pattern
 Early Instantiation: object creation takes place at the load time.
 Lazy Instantiation: object creation is done according to the requirement.
Rules for creating Singleton class
1. Ensure that only one instance of the class exists.
2. Provide global access to that instance by
 Declaring all constructors of the class to be private.
 Providing a static method that returns a reference to the instance. The lazy initialization
concept is used to write the static methods.
 The instance is stored as a private static variable.
Example
import java.util.*;
class Singleton
{
String s;
private static Singleton obj;
private Singleton()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a string: ");
s = in.nextLine();
}
public static Singleton getInstance()
{
if(obj == null)
{
obj = new Singleton();
}
return obj;
}
public void display()
{
System.out.println(s);
}
}
public class Main
{
public static void main(String args[])
{
Singleton obj = Singleton.getInstance();
obj.display();
}
}

1.12 Object Class


Object class is present in java.lang package. Every class in Java is directly or indirectly derived
from the Object class. If a class does not extend any other class, then it is a direct child class of Object
and if extends another class then it is indirectly derived. Therefore, the Object class methods are
available to all Java classes.
Methods supported by Object class

Program
class Student
{
static int last_roll = 100;
int roll_no;
Student()
{
roll_no = last_roll;
last_roll++;
}
public int hashCode() { return roll_no; }
}
public class Main
{
public static void main(String args[])
{
Student s = new Student();
Object obj = new String("Object class");
Class c = obj.getClass();
System.out.println("Class of Object obj is : "+ c.getName());
System.out.println(s);
System.out.println(s.toString());
}
public void finalize()
{
System.out.println("finalize() method will be executed finally");
}
}

1.13 Inner Class


Inner class refers to the class that is declared inside class or interface. There are basically four types of
inner classes in java:
i. Nested Inner Class
ii. Method Local Inner Classes
iii. Static Nested Classes
iv. Anonymous Inner Classes
i) Nested Inner class
class Outer
{
class Inner
{
public void show()
{
System.out.println("In a nested class method");
}
}
}
class Main
{
public static void main(String[] args)
{
Outer.Inner in = new Outer().new Inner();
in.show();
}
}
ii) Method local inner class
class Outer
{
void outerMethod()
{
System.out.println("inside outerMethod");
class Inner
{
void innerMethod()
{
System.out.println("inside innerMethod");
}
}
Inner y = new Inner();
y.innerMethod();
}
}
class Main
{
public static void main(String[] args)
{
Outer x = new Outer();
x.outerMethod();
}
}
iii) Static nested classes
class Outer {
private static void outerMethod()
{
System.out.println("inside outerMethod");
}
static class Inner {
public static void display()
{
System.out.println("inside inner class Method");
outerMethod();
}
}
}
class Main {
public static void main(String args[])
{
Outer.Inner.display();
}
}
iv) Anonymous Inner class
abstract class Example
{
abstract void display();
}

class Main
{
public static void main(String args[])
{
Example obj=new Example()
{
void display(){System.out.println("Java anonymous inner class");
}
};
obj.display();
}
}

1.14 Abstract Class


A class which is declared with the abstract keyword is known as an abstract class in Java. It can have
abstract and non-abstract methods (method with the body). Java abstract class is a class that can not be
initiated by itself, it needs to be subclassed by another class to use its properties. There are two ways to
achieve abstraction in java:
 Abstract class (0 to 100%)
 Interface (100%)
Syntax
abstract class Classname
{
data members;
non-abstract methods() {}
abstract methods();
}
Example
import java.util.*;
abstract class Shape
{
double area;
abstract public void calc_area();
}
class Square extends Shape
{ int a;
public Square()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a: ");
a = in.nextInt();
}
public void calc_area()
{
area = a * a;
System.out.println("Area of Square = "+area);
}
}
class Circle extends Shape
{ int r;
final double pai = 3.14;
public Circle()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter r: ");
r = in.nextInt();
}
public void calc_area()
{ area = r * pai * pai;
System.out.println("Area of Circle = "+area);
}
}
class Main
{ public static void main(String args[])
{
Square sobj = new Square();
Circle cobj = new Circle();
sobj.calc_area();
cobj.calc_area();
}
}
1.15 Throwable Class
The java.lang.Throwable class is the superclass of all errors and exceptions in the Java language. Only
objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine
or can be thrown by the Java throw statement. Java Throwable class provides several methods like
addSuppressed(), fillInStackTrace(), getMessage(), getStackTrace(), getSuppressed(), toString(),
printStackTrace() etc.
Example
public class Main
{
public static void main(String[] args)throws Throwable
{
try
{
int i=10/0;
}
catch(Throwable t)
{
System.out.println(t.getMessage());
}
}
}

1.16 Inheritance
Inheritance is the mechanism by which one class is allowed to inherit the features (data members and
methods) of another class. A class that inherits from another class can reuse the methods and fields
of that class. The extends keyword is used for inheritance in Java.
Syntax
class derived-class extends base-class
{
data members;
methods;
}
There are five types of inheritance:

i) Single Inheritance
import java.util.*;
class Student{
String name;
int regno;
String branch;
public Student()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter name, branch & regno: ");
name = in.nextLine();
branch = in.nextLine();
regno = in.nextInt();
}
public void display()
{
System.out.println("Name : "+name);
System.out.println("Reg. No : "+regno);
System.out.println("Branch : "+branch);
}
}
class Exam extends Student
{ int m1, m2, m3, m4, total;
double avg;
public Exam()
{ super();
Scanner in = new Scanner(System.in);
System.out.println("Enter four marks: ");
m1 = in.nextInt();
m2 = in.nextInt();
m3 = in.nextInt();
m4 = in.nextInt();
}
public void showMarks()
{ total = m1 + m2 + m3 + m4;
avg = total / 4;
System.out.println("Marks: "+m1+" "+m2+" "+m3+" "+m4);
System.out.println("Total: "+total);
System.out.println("Average: "+avg);
}
}
class Main
{
public static void main(String args[])
{
Exam s1 = new Exam();
s1.display();
s1.showMarks();
}
}
ii) Multilevel
import java.util.*;
class GrandFather
{
String gf_name;
public GrandFather()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter grand father name: ");
gf_name = in.nextLine();
}
}
class Father extends GrandFather
{
String f_name;
public Father()
{
super();
Scanner in = new Scanner(System.in);
System.out.println("Enter father name: ");
f_name = in.nextLine();
}
}
class Son extends Father
{ String s_name;
public Son()
{ super();
Scanner in = new Scanner(System.in);
System.out.println("Enter son name: ");
s_name = in.nextLine();
}
public void display()
{
System.out.println("GrandFather's Name : "+gf_name);
System.out.println("Father's Name : "+f_name);
System.out.println("Son's Name : "+s_name);
}
}
class Main
{
public static void main(String args[])
{ Son obj = new Son();
obj.display();
}
}

iii)Hierarchical
import java.util.*;
class Shape
{ double area;
public void calc_area() {}
}
class Square extends Shape
{ int a;
public Square()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a: ");
a = in.nextInt();
}
public void calc_area()
{
area = a * a;
System.out.println("Area of Square = "+area);
}
}
class Circle extends Shape
{ int r;
final double pai = 3.14;
public Circle()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter r: ");
r = in.nextInt();
}
public void calc_area()
{ area = r * pai * pai;
System.out.println("Area of Circle = "+area);
}
}
class Main
{ public static void main(String args[])
{ Square sobj = new Square();
Circle cobj = new Circle();
sobj.calc_area();
cobj.calc_area();
}
}

1.17 Difference between inheritance in C++ and Java

C++ Java

C++ supports multiple inheritance. Java does not support multiple inheritance through
class. It can be achieved by using interfaces in java.

C++ supports virtual keyword to override Java has no virtual keyword. It is possible to override
a function. all non-static methods by default.

C++ always creates a new inheritance Java always uses a single inheritance tree because all
tree. classes are the child of the Object class in Java. The
Object class is the root of the inheritance tree in java.
Hindusthan
HindusthanCollege
Collegeof
ofEngineering
Engineering and Technology
Technology
An Autonomous Institution Affiliated to Anna University | Approved by AICTE, New Delhi
(An Autonomous
Accredited with ‘A’ GradeInstitution, Affiliated to
by NAAC | Accredited by Anna University,
NBA (ECE, MECH, Chennai)
EEE, IT & CSE)
ValleyValley
Campus,Campus,
PollachiPollachi
Highway,Highway, Coimbatore
Coimbatore 641 032.| –www.hicet.ac.in
641032

22CS3251 / OBJECT ORIENTED PROGRAMMING


USING JAVA

UNIT 3 - ABSTRACTION, POLYMORPHISM AND INTERFACES


Abstraction in java -abstract class-control abstraction-data hiding vs abstraction encapsulation-
Runtime polymorphism-compile time vs run time polymorphism constructor overloading-
constructor chaining-private constructors and singleton class- Methods-different method calls-
method overriding-method overloading method overloading vs method overriding. Interfaces-
interfaces and inheritance-class vs interface-Functional interface-nested interface-Marker
Interface-Comparator interface.

1.1 Abstraction in Java


Data abstraction is the process of hiding the implementation details and showing only essential
information to the user. It provides the ability to simplify complex systems by ignoring irrelevant
details and reducing complexity. It can be achieved by using
 abstract classes (0 to 100% of abstraction),
 interfaces (100% of abstraction)
The abstract keyword is a non-access modifier, used for classes and methods:
 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: can only be used in an abstract class, and it does not have a body. The
body is provided by the subclass (inherited from).

1.2 Abstract class


A class which is declared with the abstract keyword is known as an abstract class in Java. It can
have abstract and non-abstract methods. An abstract method is a method that is declared without
implementation. Abstract class cannot be initiated by itself, it needs to be subclassed by another
class to use its properties.
Syntax
abstract class Classname
{
data members;
non-abstract methods() {}
abstract methods();
}
Example
import java.util.*;
abstract class Shape
{
double area;
abstract public void calc_area();
}
class Square extends Shape
{ int a;
public Square()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a: ");
a = in.nextInt();
}
public void calc_area()
{
area = a * a;
System.out.println("Area of Square = "+area);
}
}
class Circle extends Shape
{ int r;
final double pai = 3.14;
public Circle()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter r: ");
r = in.nextInt();
}
public void calc_area()
{ area = r * pai * pai;
System.out.println("Area of Circle = "+area);
}
}
class Main
{ public static void main(String args[])
{
Square sobj = new Square();
Circle cobj = new Circle();
sobj.calc_area();
cobj.calc_area();
}
}
1.3 Control Abstraction
Control Abstraction refers to the software part of abstraction wherein the program is simplified
and unnecessary execution details are removed. It can be used to build new functionalities and
combines control statements into a single unit. It follows the basic rule of DRY (Don’t Repeat
Yourself) code and using functions in a program is the best example of control abstraction. The
greatest advantage of control abstraction is that it makes code a lot cleaner and more secure.

1.4 Data hiding vs Abstraction

S. No. Abstraction Data Hiding

The process of hiding the implementation The process of hiding important and sensitive
1. details and showing only the functionality of data from any unintended access is known as
program is referred to as abstraction. data hiding.

Abstraction helps in extracting relevant Data hiding helps to increase safety by


2.
information from a larger set of information. preventing outside attacks.

Abstraction focuses on reducing the The purpose of data hiding is to achieve data
3.
complexity of code. encapsulation.

Abstraction solves the design level problems. Data hiding solves the implementation level
4.
problems.

There are three types of data abstractions Data hiding is not divided into subtypes.
5. namely, procedural abstraction, data
abstraction, and control abstraction.

1.5 Polymorphism
Polymorphism means ability to take many forms. It allows a single name/operator to be associated
with different operations depending on the type of data passed to it. Polymorphism in Java has
two types:
 Compile time polymorphism (static binding) and
 Runtime polymorphism (dynamic binding).
Method overloading is an example of static polymorphism, while Method overriding is an example
of dynamic polymorphism.

a) Method Overloading
Method Overloading allows different methods to have the same name, but different signatures
where the signature can differ by the number of input parameters or type of input parameters, or a
mixture of both. Method overloading in Java is also known as Compile-time Polymorphism, Static
Polymorphism, or Early binding. Method overloading increases the readability of the program.
Example
import java.util.*;
public class Main
{
double area;
public void calculate(int x)
{
area = x * x;
System.out.println("Area of square = "+area);
}
public void calculate(double r)
{
area = 3.14 * r * r;
System.out.println("Area of Circle = "+area);
}
public void calculate(double l, double b)
{
area = l * b;
System.out.println("Area of Rectangle = "+area);
}
public static void main(String args[])
{
Main obj = new Main();
obj.calculate(4.6, 3.8);
obj.calculate(12);
obj.calculate(6.5);
}
}
Output
Area of Rectangle = 17.479999999999997
Area of square = 144.0
Area of Circle = 132.665

b) Method Overriding
When a method in a subclass has the same name and type signature as a method in its super class,
then the method in the subclass is said to override the method in the super class. When an
overridden method is called from within a subclass, it will always refer to the version of that
method defined by the subclass. The version of the method defined by the super class will be
hidden.
Note: Method overriding occurs only when the names and the type signatures of the two methods
are identical. If they are not, then the two methods are simply overloaded.
Rules for Java Method Overriding
 The method must have the same name as in the parent class
 The method must have the same parameter as in the parent class.
 There must be an IS-A relationship (inheritance).
Example
import java.util.*;
class Parent
{
String pname;
Scanner in = new Scanner(System.in);
public void show()
{
System.out.print("Enter parent name: ");
pname = in.nextLine();
}
}
class Child extends Parent
{
String cname;
public void show()
{
System.out.print("Enter child name: ");
cname = in.nextLine();
}
}
class Main
{
public static void main(String[] args)
{
Parent obj1 = new Parent();
obj1.show();
Parent obj2 = new Child();
obj2.show();
}
}
Output
Enter parent name: James
Enter child name: Gosling

Dynamic Method Dispatch


Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved
at run time, rather than compile time. Dynamic method dispatch is important because this is how
Java implements run-time polymorphism.
1.6 Constructor Overloading
Constructor overloading refers to the practice of defining multiple constructors within a class, each
with a different set of parameters. These parameters can vary in terms of their number, data types,
and order. The purpose of constructor overloading is to provide multiple ways to initialize objects
in a class, catering to different scenarios and requirements. Overloaded constructor is called based
on the parameters specified when a new is executed.
Example
import java.util.*;
class Complex
{
int r, i;
Scanner in = new Scanner(System.in);
Complex()
{
r = i =0;
}
Complex(int r, int i)
{
this.r = r;
this.i = i;
}
Complex(int x)
{
r = i = x;
}
public void display()
{
System.out.println(r +" +j " +i);
}
}
class Main
{
public static void main(String[] args)
{
Complex obj1 = new Complex();
Complex obj2 = new Complex(5);
Complex obj3 = new Complex(8,12);
obj1.display();
obj2.display();
obj3.display();
}
}
Output
0 +j 0
5 +j 5
8 +j 12

1.7 Constructor Chaining


Constructor chaining is the process of calling one constructor from another constructor with
respect to current object. One of the main uses of constructor chaining is to avoid duplicate codes
while having multiple constructor (by means of constructor overloading) and make code more
readable. Constructor chaining can be done in two ways:
 Within same class: It can be done using this() keyword for constructors in the same class
 From base class: by using super() keyword to call the constructor from the base class.
Rules of Constructor Chaining
 An expression that uses this keyword must be the first line of the constructor.
 Order does not matter in constructor chaining.
 There must exist at least one constructor that does not use this
Example
import java.util.*;
class Complex
{
int r, i;
Scanner in = new Scanner(System.in);
Complex()
{
this(45);
System.out.println("Default constructor");
}
Complex(int r, int i)
{
this.r = r;
this.i = i;
System.out.println("Constructor with two parameters");
}
Complex(int x)
{
this(-5,45);
System.out.println("Constructor with one parameter");
}
public void display()
{
System.out.println(r +" +j " +i);
}
}
class Main
{
public static void main(String[] args)
{
Complex obj1 = new Complex();
obj1.display();
}
}
Output
Constructor with two parameters
Constructor with one parameter
Default constructor
-5 +j 45

1.8 Private Constructor


A private constructor in Java is used in restricting object creation. If a constructor is declared
private, we are not able to create an object of the class. If a constructor is declared as private, then
its objects are only accessible from within the declared class. You cannot access its objects from
outside the constructor class.
Rules for Private Constructor
 It does not allow a class to be sub-classed.
 It does not allow to create an object outside the class.
 If a class has a private constructor and when we try to extend the class, a compile-time
error occurs.
 We cannot access a private constructor from any other class.
 If all the constant methods are there in our class, we can use a private constructor.
 If all the methods are static then we can use a private constructor.
 We can use a public function to call the private constructor if an object is not initialized.
 We can return only the instance of that object if an object is already initialized.
Example
import java.util.*;
class A
{
int a;
private static A obj;
private A()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a: ");
a = in.nextInt();
}
public static A getInstance()
{
if(obj == null)
{
obj = new A();
}
return obj;
}
public void display()
{
System.out.println("a = "+a);
}
}
public class Main
{
public static void main(String args[])
{
A obj1 = A.getInstance();
A obj2 = A.getInstance();
obj1.display();
obj2.display();
}
}

1.9 Singleton Class


A java singleton class is a class that can have only one object (an instance of the class) at
a time.
After the first time, if we try to instantiate the Java Singleton classes, the new variable also points
to the first instance created. There are two forms of singleton design pattern
 Early Instantiation: object creation takes place at the load time.
 Lazy Instantiation: object creation is done according to the requirement.
Rules for creating Singleton class
1. Ensure that only one instance of the class exists.
2. Provide global access to that instance by
 Declaring all constructors of the class to be private.
 Providing a static method that returns a reference to the instance. The lazy
initialization concept is used to write the static methods.
 The instance is stored as a private static variable.
Example
import java.util.*;
class Singleton
{
String s;
private static Singleton obj;
private Singleton()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a string: ");
s = in.nextLine();
}
public static Singleton getInstance()
{
if(obj == null)
{
obj = new Singleton();
}
return obj;
}
public void display()
{
System.out.println(s);
}
}
public class Main
{
public static void main(String args[])
{
Singleton obj = Singleton.getInstance();
obj.display();
}
}

1.10 Methods
A method is a block of code which only runs when it is called. It is possible to pass data, known
as parameters, into a method. Methods are used to perform certain actions, and they are also known
as functions. There are four types of methods
 User-Defined Methods: These are the methods implemented by the user in the class to
perform a particular operation.
 Abstract Methods: These are the methods that do not contain the body of the method and
implements inside the abstract class.
 Predefined Methods: These are the methods that are predefined and available in the java
library to perform operations, for e.g. the hashcode() method.
 static Methods: These are methods that are accessible without any instance of the class.
The memory management of these methods is different from ordinary methods.
A user defined method must be declared within a class. It is defined with the name of the method,
followed by parentheses ().
Syntax for Method Declaration:
access-modifier returntype name(parantheses)
{
//method body
}
 Access modifier: It defines the access type of the method i.e., from where it can be
accessed in your application. In Java, there 4 types of access specifiers.

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


o protected: It is accessible within the class in which it is defined and, in its subclass.
o private: It is accessible only within the class in which it is defined.
o default: It is declared/defined without using any modifier. It is accessible within
the same class and package within which its class is defined.
 The return type: The data type of the value returned by the method or void if does not
return a value. It is Mandatory in syntax.
 Method Name: the rules for field names apply to method names as well, but the
convention is a little different. It is Mandatory in syntax.
 Parameter list: Comma-separated list of the input parameters is defined, preceded by
their data type, within the enclosed parenthesis. If there are no parameters, empty
parentheses () must be given.
 Method body: it is enclosed between braces. The code which is need to be executed to
perform intended operations.
Example

import java.io.*;
class Addition
{
int sum = 0;
public int addTwoInt(int a, int b) //instance method
{
sum = a + b;
return sum;
}
}
class Main
{
public static void main(String[] args) //static method
{
Addition add = new Addition();
int s = add.addTwoInt(10, 22);
System.out.println("Sum of two integer values :"+ s);
}
}
Output
Sum of two integer values :32

1.11 Different Method Calls


a) User defined method: User-Defined nonstatic methods can be called or accessed only with
the help of an instance of the class.
Example
class Main
{
void method()
{
System.out.println("This is the userDefinedMethod");
}
public static void main(String[] args)
{
Main obj = new Main();
obj.method();
}
}
Output
This is the userDefinedMethod

b) Abstract method
These are the methods that are declared inside the abstract class without the implementation. To
create the instance of the abstract class, it must be extended. Abstract Methods are used when we
must use the one-way property of the method in different ways.
Example
abstract class Abstract
{
abstract void display(String name);
}
class Main extends Abstract
{
void display(String name)
{
System.out.println(name);
}
public static void main(String[] args)
{
Main obj = new Main();
obj.display("Calling Abstract Method()");
}
}
Output
Calling Abstract Method()

c) Pre-defined method
These are the methods that are already implemented in the java library or predefined and inherited
by every java class. For example, consider every class in the java inherited object class that has
various methods. hashcode() is one of the methods of the object class that is inherited by every
class in Java.
Example
class Main
{
public static void main(String[] args)
{
Main obj = new Main();
System.out.println(obj.hashCode());
}
}
Output
1608446010

d) Static methods
Static methods are those methods that there is no need for an instance of the class to access.
Basically, these methods are the class methods and every static methods are shared among all the
instances equally.
Example
class Main
{
static void display()
{
System.out.println("Called static method");
}
public static void main(String[] args)
{
display();
}
}
Output
Called static method

1.12 Method Overloading vs Method Overriding

Method Overloading Method Overriding

Method overloading is a compile-time


Method overriding is a run-time polymorphism.
polymorphism.

Method overriding is used to grant the specific


Method overloading helps to increase
implementation of the method which is already
the readability of the program.
provided by its parent class or superclass.

It is performed in two classes with inheritance


It occurs within the class.
relationships.

Method overloading may or may not


Method overriding always needs inheritance.
require inheritance.

In method overloading, methods must


In method overriding, methods must have the
have the same name and different
same name and same signature.
signatures.

In method overloading, the return type


In method overriding, the return type must be the
can or can not be the same, but we just
same or co-variant.
have to change the parameter.

Static binding is being used for Dynamic binding is being used for overriding
overloaded methods. methods.
Method Overloading Method Overriding

It gives better performance. The reason behind


Poor Performance due to compile time
this is that the binding of overridden methods is
polymorphism.
being done at runtime.

Private and final methods can be


Private and final methods can’t be overridden.
overloaded.

The argument list should be different The argument list should be the same in method
while doing method overloading. overriding.

1.13 Interface
An interface is a collection of abstract methods (i.e., methods without having definition). It
contains only behaviors (i.e. methods) that a class implements. It is a mechanism to achieve
abstraction. A class that implements an interface inherits abstract methods of the interface. If a
class (provided it is not abstract) implements an interface, then all the methods of interface need
to be defined in it. There are mainly three reasons to use interface:
 It is used to achieve abstraction.
 By interface, we can support the functionality of multiple inheritance.
 It can be used to achieve loose coupling.
Declaring Interfaces
An interface is declared by using the interface keyword. It provides total abstraction; means all
the methods in an interface are declared with the empty body, and all the fields are public, static
and final by default. A class that implements an interface must implement all the methods declared
in the interface.
Syntax:
public interface NameOfInterface
{
//Any number of final, static variables
//Any number of abstract method declarations (i.e. method without definitions)
}
Interface fields are public, static and final by default, and the methods are public and abstract.
Interfaces have the following properties
 An interface is implicitly (i.e. by default) abstract. We do not need to use the abstract
keyword when declaring an interface.
 Each method in an interface is also implicitly (i.e. by default) abstract, so the abstract
keyword is not needed.
 Methods in an interface are implicitly (i.e. by default) public.
Implementing Interfaces
 A class can implement more than one interface at a time.
 A class can extend only one class, but can implement many interfaces.
 An interface itself can extend another interface.
The general form of a class that includes the implements clause
class classname extends superclass implements interface
{
// class-body
}
Example
import java.util.*;
interface Circle
{
double pai = 3.14;
void calculate();
}
class Area implements Circle
{
double r, area;
Scanner in = new Scanner(System.in);
Area()
{
System.out.print("Enter r: ");
r = in.nextDouble();
}
public void calculate()
{
area = pai * r * r;
System.out.println("Area = "+area);
}
}
class Main
{
public static void main(String[] args)
{
Area obj = new Area();
obj.calculate();
}
}
Output
Enter r: 6
Area = 113.03999999999999

1.14 Multiple Inheritance through Interfaces


Multiple Inheritance inherits the properties of more than one parent class. The problem occurs
when methods with the same signature exist in both the superclasses and subclass. On calling the
method, the compiler cannot determine which class method to be called and even on calling which
class method gets the priority.

An interface is a fully abstract class i.e., it includes a set of abstract methods that specifies what a
class must do and not how to do it. Hence, if a class implements an interface, it inherits all the
abstract methods of the interface and provides an implementation for each of them. Interfaces are
non-instantiable and provide a representation of what a class should implement i.e., interfaces do
not contain detailed instructions for their behaviors. Because of this feature, a class can implement
any number of interfaces without any ambiguity as the implementation is provided by the class
itself.
Example
import java.util.*;
class Father
{
String fname;
Scanner in = new Scanner(System.in);
public void get_fname()
{
System.out.println("Enter Fathers Name: ");
fname = in.nextLine();
}
public void display()
{
System.out.println("Father: "+fname);
}
}
interface Mother
{
String mname = "Seeta";
public void display();
}
class Child extends Father implements Mother
{
String cname;
Scanner in = new Scanner(System.in);
public void get_cname()
{
System.out.println("Enter Child Name: ");
cname = in.nextLine();
}
public void display()
{
super.display();
System.out.println("Mother: "+mname);
System.out.println("Child: "+cname);
}
}
class Main
{
public static void main(String args[])
{
Child obj = new Child();
obj.get_fname();
obj.get_cname();
obj.display();
}
}

1.15 Class vs interface


The relationship between class and interface
Similarities between class and interface
 Both class and interface can contain any number of methods.
 Both class and interface are written in a file with a .java extension, with the name of the
interface matching the name of the file.
 The bytecode of both class and interface appears in a .class file.

Dissimilarities between class and interface


 We cannot instantiate (i.e., create object) an interface but we can instantiate a class.
 An interface does not contain any constructors but a class may contain any constructors.
 All the methods in an interface are abstract (i.e., without definitions) but in a class method
may or may not be abstract.
 An interface cannot contain variables. The only variable that can appear in an interface
must be declared both static and final. But a class can contain any variable.
 An interface is not extended by a class; it is implemented by a class.
 An interface can extend multiple interfaces (i.e., multiple inheritances can be achieved
through it). But a class cannot extend multiple classes (i.e., multiple inheritance cannot be
achieved).

Class Interface

In class, you can instantiate variables In an interface, you can’t instantiate variables
and create an object. and create an object.

A class can contain concrete(with The interface cannot contain concrete(with


implementation) methods implementation) methods

The access specifiers used with classes


In Interface only one specifier is used- Public.
are private, protected, and public.
1.16 Functional interface
A functional interface is an interface that contains only one abstract method. They can have only
one functionality to exhibit. lambda expressions can be used to represent the instance of a
functional interface. A functional interface can have any number of default methods. Runnable,
ActionListener, and Comparable are some of the examples of functional interfaces.

Functional Interface is additionally recognized as Single Abstract Method Interfaces. They are
also known as SAM interfaces. Functional interfaces are interfaces that ensure that they include
precisely only one abstract method. Functional interfaces are used and executed by representing
the interface with an annotation called @FunctionalInterface. They can include any quantity of
default and static methods.

Example
interface Print
{
void display(String msg);
}
public class Main implements Print
{
public void display(String msg)
{
System.out.println(msg);
}
public static void main(String[] args)
{
Main obj = new Main();
obj.display("Example of Functional Interface");
}
}
Output
Example of Functional Interface

Example
Functional Interface with lambda expressions
interface Square
{
int calculate(int x);
}
class Main
{
public static void main(String args[])
{
int a = 5;
Square s = (x) -> x * x;
int ans = s.calculate(a);
System.out.println("Square of "+a+" is "+ans);
}
}
Output
Square of 5 is 25

Built-in Java Functional Interfaces


There are many interfaces that are converted into functional interfaces. All these interfaces are
annotated with @FunctionalInterface. They are
 Runnable –> This interface only contains the run() method.
 Comparable –> This interface only contains the compareTo() method.
 ActionListener –> This interface only contains the actionPerformed() method.
 Callable –> This interface only contains the call() method.

1.17 Nested interface


An interface, i.e., declared within another interface or class, is known as a nested interface. The
nested interfaces are used to group related interfaces so that they can be easy to maintain. The
nested interface must be referred to by the outer interface or class. It cannot be accessed directly.

Rules for declaring nested interface


 A nested interface declared within an interface must be public.
 A nested interface declared within a class can have any access modifier.
 A nested interface is by default static.

Syntax of nested interface which is declared within the interface


interface Interface_name
{
...
interface Nested_interface_name
{
...
}
}
Syntax of nested interface which is declared within the class
class Class_name
{
...
interface Nested_interface_name
{
...
}
}

Example – Interface nested inside another interface


interface Showable
{
void show();
interface Message
{
void msg();
}
}
class Main implements Showable.Message
{
public void msg()
{
System.out.println("Nested interface method");
}
public static void main(String args[])
{
Showable.Message obj = new Main();
obj.msg();
}
}
Output
Nested interface method

Example – Interface nested inside the class


class Outer
{
interface Message
{
void msg();
}
}
class Main implements Outer.Message
{
public void msg()
{
System.out.println("Nested interface");
}
public static void main(String args[])
{
Outer.Message obj = new Main();
obj.msg();
}
}
Output
Nested interface

Uses of Nested Interfaces


 To group related interfaces together
 To create more secure code
 To implement multiple interfaces
 To create callbacks
 To define a contract between classes

1.18 Marker Interface


An interface that does not contain methods, fields, and constants is known as marker interface. It
is an empty interface and known as marker interface or tag interface. It delivers the run-time type
information about an object. It is the reason that the JVM and compiler have additional information
about an object. The Serializable and Cloneable interfaces are the example of marker interface. It
indicates a signal or command to the JVM.
Syntax
public interface MyMarkerInterface
{

}
Examples of Marker Interface which are used in real-time applications:
 Cloneable interface
 Serializable interface
 Remote interface
Example
import java.lang.Cloneable;
class A implements Cloneable
{
int i;
String s;
public A(int i,String s)
{
this.i = i;
this.s = s;
}
protected Object clone() throws CloneNotSupportedException
{
return super.clone();
}
}
class Main
{
public static void main(String[] args) throws CloneNotSupportedException
{
A a = new A(20, "Example for Cloneable");
A b = (A)a.clone();
System.out.println(b.i);
System.out.println(b.s);
}
}
Output
20
Example for Cloneable

1.19 Comparator interface


A comparator interface is used to order the objects of user-defined classes. A comparator object
can compare two objects of the same class. This interface is found in java.util package.
Methods of Java Comparator Interface
 compare(Object obj1,Object obj2) and
 equals(Object element)

Method Description

public int compare(Object obj1, Object obj2) It compares the first object with the second
object.

public boolean equals(Object obj) It is used to compare the current object with the
specified object.

public boolean equals(Object obj) It is used to compare the current object with the
specified object.

Using a comparator, we can sort the elements based on data members. It may sort elements based
on roll no, name, age, etc.
Example
import java.io.*;
import java.util.*;
class Student
{

int rollno;
String name, address;
public Student(int rollno, String name, String address)
{
this.rollno = rollno;
this.name = name;
this.address = address;
}
public String toString()
{
return this.rollno + " " + this.name + " "+ this.address;
}
}
class Sortbyroll implements Comparator<Student>
{
public int compare(Student a, Student b)
{
return a.rollno - b.rollno;
}
}
class Sortbyname implements Comparator<Student>
{
public int compare(Student a, Student b)
{

return a.name.compareTo(b.name);
}
}
class Main
{
public static void main(String[] args)
{
ArrayList<Student> ar = new ArrayList<Student>();
ar.add(new Student(111, "Mayank", "london"));
ar.add(new Student(131, "Anshul", "nyc"));
ar.add(new Student(121, "Solanki", "jaipur"));
ar.add(new Student(101, "Aggarwal", "Hongkong"));
System.out.println("Unsorted");
for (int i = 0; i < ar.size(); i++)
System.out.println(ar.get(i));
Collections.sort(ar, new Sortbyroll());
System.out.println("\nSorted by rollno");
for (int i = 0; i < ar.size(); i++)
System.out.println(ar.get(i));
Collections.sort(ar, new Sortbyname());
System.out.println("\nSorted by name");
for (int i = 0; i < ar.size(); i++)
System.out.println(ar.get(i));
}
}
Output
Unsorted
111 Mayank london
131 Anshul nyc
121 Solanki jaipur
101 Aggarwal Hongkong

Sorted by rollno
101 Aggarwal Hongkong
111 Mayank london
121 Solanki jaipur
131 Anshul nyc

Sorted by name
101 Aggarwal Hongkong
131 Anshul nyc
111 Mayank london
121 Solanki jaipur
Hindusthan
HindusthanCollege
Collegeof
ofEngineering
Engineering and Technology
Technology
An Autonomous Institution Affiliated to Anna University | Approved by AICTE, New Delhi
(An Autonomous
Accredited with ‘A’ GradeInstitution, Affiliated to
by NAAC | Accredited by Anna University,
NBA (ECE, MECH, Chennai)
EEE, IT & CSE)
ValleyValley
Campus,Campus,
PollachiPollachi
Highway,Highway, Coimbatore
Coimbatore 641 032.| –www.hicet.ac.in
641032

22CS3251 / OBJECT ORIENTED PROGRAMMING


USING JAVA

UNIT 4 - MULTITHREADING, PACKAGES AND COLLECTIONS


Threads-lifecycle and stages of a Thread-Thread priority-main Thread-Runnable interface-naming
thread-start () method-Java packages-built in packages-user defined packages-Collections-List
interface-Queue interface-Map interface-Set-Iterator Comparator-JDBC-connectivity with JDBC-
DriverManager-Statement-JDBC Exceptions.

1.1 MULTITHREADING
Multithreading in java is a process of executing multiple threads simultaneously. A multithreaded
program contains two or more parts that can run concurrently. Each part of such a program is called a
thread, and each thread defines a separate path of execution. Thus, multithreading is a specialized form
of multitasking.
Multiprocessing and multithreading, both are used to achieve multitasking. However, we use
multithreading than multiprocessing because threads use a shared memory area. They don't allocate
separate memory area so saves memory, and context-switching between the threads takes less time
than process. Java Multithreading is mostly used in games, animation, etc.

What is a Thread?
A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of
execution. Threads are independent. If there occurs exception in one thread, it doesn't affect other
threads. It uses a shared memory area.

As shown in the above figure, a thread is executed inside the process. There is context-switching
betweenthe threads. There can be multiple processes inside the OS, and one process can have
multiple threads.
Advantages of Java Multithreading
1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single
thread.

Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize
the CPU. Multitasking can be achieved in two ways:
 Process-based Multitasking (Multiprocessing)
 Thread-based Multitasking (Multithreading)
1) Process-based Multitasking (Multiprocessing)
 A process-based multitasking is the feature that allows our computer to run two or more
programs concurrently. For example, process-based multitasking enables us to run the Java
compiler at the same time that we are using a music player.
 Each process has an address in memory. In other words, each process allocates a separate
memoryarea.
 A process is heavyweight.
 Cost of communication between the process is high.
 Switching from one process to another requires some time for saving and loading registers,
memory maps, updating lists, etc.
2) Thread-based Multitasking (Multithreading)
 In a thread-based multitasking environment, the thread is the smallest unit of dispatchable
code. This means that a single program can perform two or more tasks simultaneously.
 Threads share the same address space.
 A thread is lightweight.
 Cost of communication between the thread is low.

1.2 JAVA THREAD MODEL


One thread can pause without stopping other parts of your program. For example, the idle time created
when a thread reads data from a network or waits for user input can be utilized else where. When a
thread blocks in a Java program, only the single thread that is blocked pauses. All other threads
continue to run.
Life Cycle of a Thread
A thread can be in one of the five states. The life cycle of the thread in java is controlled by JVM.
The java thread states are as follows:
1) New
2) Active
3) Blocked / Waiting
4) Timed Waiting
5) Terminated
New: Whenever a new thread is created, it is always in the new state. For a thread in the new state,
the code has not been run yet and thus has not begun its execution.
Active: When a thread invokes the start() method, it moves from the new state to the active state. The
active state contains two states within it: one is runnable, and the other is running.
 Runnable: A thread, that is ready to run is then moved to the runnable state. In the runnable state,
the thread may be running or may be ready to run at any given instant of time. It is the duty of the
thread scheduler to provide the thread time to run, i.e., moving the thread the running state. A
program implementing multithreading acquires a fixed slice of time to each individual thread.
Each thread runs for a short span of time and when that allocated time slice is over, the thread
voluntarily gives up the CPU to the other thread, so that the other threads can also run for their
slice of time. Whenever such a scenario occurs, all those threads that are willing to run, waiting
for their turn to run, lie in the runnable state. In the runnable state, there is a queue where the
threads lie.

 Running: When the thread gets the CPU, it moves from the runnable to the running state.
Generally, the most common change in the state of a thread is from runnable to running and again
back to runnable.
Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently) then, either the
thread is in the blocked state or is in the waiting state.
Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread (its name is A) has
entered the critical section of a code and is not willing to leave that critical section. In such a scenario,
another thread (its name is B) has to wait forever, which leads to starvation. To avoid such scenario, a timed
waiting state is given to thread B. Thus, thread lies in the waiting state for a specific span of time, and not
forever. A real example of timed waiting is when we invoke the sleep() method on a specific thread. The
sleep() method puts the thread in the timed wait state. After the time runs out, the thread wakes up and start
its execution from when it has left earlier.
Terminated: A thread reaches the termination state because of the following reasons:
 When a thread has finished its job, then it exists or terminates normally.
 Abnormal termination: It occurs when some unusual events such as an unhandled exception or
segmentation fault.
A terminated thread means the thread is no more in the system. In other words, the thread is dead, and there
is no way one can respawn (active after kill) the dead thread.
1.3 THREAD PRIORITY
 Java assigns to each thread a priority that determines how that thread should be treated with
respect to the others.
 Priorities are represented by a number between 1 and 10.
 In most cases, thread schedular schedules the threads according to their priority (known as
preemptive scheduling). But it is not guaranteed because it depends on JVM specification that
which scheduling it chooses
 Java priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).
 Threads with higher priority are more important to a program and should be allocated
processor time before lower-priority threads. However, thread priorities cannot guarantee the
order in whichthreads execute and very much platform dependent.
 A thread’s priority is used to decide when to switch from one running thread to the next. This
is called a context switch.
The rules that determine when a context switch takes place are simple:
 A thread can voluntarily relinquish control. This is done by explicitly yielding, sleeping,
or blocking on pending I/O. In this scenario, all other threads are examined, and the highest
priority thread that is ready to run is given the CPU.
 A thread can be preempted by a higher-priority thread. In this case, a lower-priority thread
that does not yield the processor is simply preempted—no matter what it is doing— by a
higher- priority thread. Basically, as soon as a higher-priority thread wants to run, it does. This
is called preemptive multitasking.
To set a thread’s priority, use the setPriority( ) method, which is a member of Thread. This is its
general form:
final void setPriority(int level)
Here, level specifies the new priority setting for the calling thread. The value of level must be within
the range MIN_PRIORITY and MAX_PRIORITY. Currently, these values are 1 and 10, respectively.
To return a thread to default priority, specify NORM_PRIORITY, which is currently 5. These
priorities are defined as static final variables within Thread. You can obtain the current priority setting
by calling the getPriority() method of Thread, shown here:
final int getPriority( )
Program

class Main
{
public static void main(String[] args) throws InterruptedException
{
Thread t1 = new Thread(() -> {
System.out.println("Thread in execution");
System.out.println("Current state of the thread - " + Thread.currentThread().getState());
});
System.out.println("State of the thread - " + t1.getState());
System.out.println("Priority of the thread t1 is : " + t1.getPriority());
t1.setPriority(6);
t1.start();
t1.join();
System.out.println("Priority of the thread t1 is : " + t1.getPriority());
System.out.println("State of the thread - " + t1.getState());
Thread t2 = new Thread(() -> {
System.out.println("Thread in execution");
System.out.println("Current state of the thread - " + Thread.currentThread().getState());
});
System.out.println("State of the thread - " + t2.getState());
System.out.println("Priority of the thread t1 is : " + t2.getPriority());
t2.setPriority(9);
t2.start();
t2.join();
System.out.println("State of the thread - " + t2.getState());
System.out.println("Priority of the thread t2 is : " + t2.getPriority());
}
}
Output
State of the thread - NEW
Priority of the thread t1 is : 5
Thread in execution
Current state of the thread - RUNNABLE
Priority of the thread t1 is : 6
State of the thread - TERMINATED
State of the thread - NEW
Priority of the thread t1 is : 5
Thread in execution
Current state of the thread - RUNNABLE
State of the thread – TERMINATED
Priority of the thread t2 is : 9

1.4 THE THREAD CLASS AND THE RUNNABLE INTERFACE


There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
Creating Thread by extending Thread class:
To create a thread is to create a new class that extends Thread, and then to create an instance of that
class. The extending class must override the run ( ) method, which is the entry point for the new
thread. It must also call start ( ) to begin execution of the new thread.
Thread class provide constructors and methods to create and perform operations on a thread. Thread
class extends Object class and implements Runnable interface.
The Thread class defines several methods that help manage threads.

Method Meaning

getName Obtain a thread’s name.

getPriority Obtain a thread’s priority.

isAlive Determine if a thread is still running.

join Wait for a thread to terminate.

run Entry point for the thread.


sleep Suspend a thread for a period of time.

start Start a thread by calling its run method.

Example:
class Multi extends Thread
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi t1=new
Multi(); t1.start();
}
}
Output: thread is running...

Creating Thread by Implementing Runnable interface


The easiest way to create a thread is to create a class that implements the Runnable interface.

 To implement Runnable, a class need only implement a single method called run( ),
which is declared like this:
public void run( )
We will define the code that constitutes the new thread inside run() method. It is important to
understand that run() can call other methods, use other classes, and declare variables, just like the
main thread can.

 After we create a class that implements Runnable, you will instantiate an object of type Thread
from within that class. Thread defines several constructors. The one that we will use is shown
here:
Thread(Runnable threadOb, String threadName);
Here threadOb is an instance of a class that implements the Runnable interface and the name of the
new thread is specified by threadName.
 After the new thread is created, it will not start running until you call its start( ) method,
which is declared within Thread. The start( ) method is shown here:
void start( );
Here is an example that creates a new thread and starts it running:
Example:
class Multi implements Runnable
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi obj=new Multi();
Thread t1 =new
Thread(obj); t1.start();
}
}
Output: thread is running...

1.5 CREATING MULTIPLE THREADS


We have been using only two threads: the main thread and one child thread. However, our program
canspawn as many threads as it needs. For example, the following program creates three child
threads:
If you have to perform single task by many threads, have only one run() method. For example:
Program for generating four threads to perform following operations:

 Getting N numbers as input


 Printing even numbers
 Printing odd numbers
 Computing average

import java.util.Scanner;
class MyThread1 extends Thread
{
Scanner in = new Scanner(System.in);
public void run()
{
System.out.println("Enter n: ");
int n = in.nextInt();
int nums[] = new int[n];
System.out.println("Enter " + n + " numbers");
for(int i = 0; i < n; i++)
{
nums[i] = in.nextInt();
}
}
}
class MyThread2 extends Thread
{
Scanner in = new Scanner(System.in);
public void run()
{
System.out.println("Enter n: ");
int n = in.nextInt();
System.out.println("Even numbers in the range 1 - " + n);
for(int i = 2; i <= n; i = i + 2)
System.out.println(i + " ");
}
}

class MyThread3 extends Thread


{
Scanner in = new Scanner(System.in);
public void run()
{
System.out.println("Enter n: ");
int n = in.nextInt();
System.out.println("Odd numbers in the range 1 - " + n);
for(int i = 1; i <= n; i = i + 2)
System.out.println(i + " ");
}
}

class MyThread4 extends Thread


{
Scanner in = new Scanner(System.in);
public void run()
{
System.out.println("Enter n: ");
int n = in.nextInt();
int sum = 0;
float avg = 0.0f;
for(int i = 0; i < n; i++)
sum = sum + i;
avg = (float) sum / n;
System.out.println("Average is : " + avg);
}
}
public class Main
{
public static void main(String[] args) throws InterruptedException
{
MyThread1 t1 = new MyThread1();
MyThread2 t2 = new MyThread2();
MyThread3 t3 = new MyThread3();
MyThread4 t4 = new MyThread4();
t1.start();
t2.start();
t3.start();
t4.start();
}
}
If you have to perform multiple tasks by multiple threads,have multiple run() methods.For example:
Program of performing two tasks by two threads
Example:
class A implements Runnable
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("A = "+i);
}
}
}
class B implements Runnable
{
synchronized public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("B = "+i);
}
}
}
class C implements Runnable
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("C = "+i);
}
}
}
class ExampleThread
{
public static void main(String[] args)
{
A obj1 = new A();
B obj2 = new B();
C obj3 = new C();
Thread t1 = new Thread(obj1); Thread t2 = new Thread(obj2);
Thread t3 = new Thread(obj3); t3.setPriority(7);
t2.setPriority(Thread.MAX_PRIORITY);
int n = t3.getPriority();
System.out.println("Priority of Thread t3 is " + n); t1.start();
t2.start();
t3.start();
}
}
OUTPUT:
Priority of Thread t3
is 7 A = 1
B=1
A=2
B=2
B=3
A=3
B=4
C=1
B=5
A=4
C=2
A=5
C=3
C=4
C=5
Using isAlive( ) and join( )
Two ways exist to determine whether a thread has finished. First, we can call isAlive( ) on the thread.
This method is defined by Thread, and its general form is shown here:
final boolean isAlive( )
The isAlive( ) method returns true if the thread upon which it is called is still running. It returns false
otherwise. While isAlive( ) is occasionally useful, the method that you will more commonly use to
wait for a thread to finish is called join( ), shown here:
final void join ( ) throws InterruptedException
This method waits until the thread on which it is called terminates. Its name comes from the concept
of the calling thread waiting until the specified thread joins it. Additional forms of join ( ) allow you
to specify a maximum amount of time that you want to wait for the specified thread to terminate.
Example program
class Customer
{
int amount=10000;
synchronized void withdraw(int amount)
{
System.out.println("going to withdraw...");
if(this.amount<amount)
{
System.out.println("Less balance; waiting for deposit...");
try{wait();}
catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount)
{
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Main
{
public static void main(String args[])
{
final Customer c=new Customer();
new Thread()
{
public void run(){c.withdraw(15000);}
}.start();

new Thread()
{
public void run(){c.deposit(10000);}
}.start();
}
}

1.6 SYNCHRONIZATION
When two or more threads need access to a shared resource, they need some 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.
Key to synchronization is the concept of the monitor (also called a semaphore). A monitor is an object
that is used as a mutually exclusive lock, or mutex. Only one thread can own a monitor at a given
time. When a thread acquires a lock, it is said to have entered the monitor. All other threads attempting
to enter the locked monitor will be suspended until the first thread exits the monitor. These other
threads are said to be waiting for the monitor. A thread that owns a monitor can reenter the same
monitor if it so desires.

Using Synchronized Methods:


Synchronization is easy in Java, because all objects have their own implicit monitor associated
with them. To enter an object’s monitor, just call a method that has been modified with the
synchronizedkeyword. While a thread is inside a synchronized method, all other threads that try to
call it (or any other synchronized method) on the same instance have to wait. To exit the monitor and
relinquish control of the object to the next waiting thread, the owner of the monitor simply returns
from the synchronized method.
Example 1:
class Table
{
synchronized void printTable(int n)
{
for(int i=1;i<=5;i++)
{
System.out.println(n*
i); try
{
Thread.sleep(400);
}
catch(Exception e)
{ System.out.println(e); }
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Tab
le t)
{ this.t=t;
}
public void run()
{
t.printTable(5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Tab
le t)
{ this.t=t;
}
public void run()
{
t.printTable(100);
}
}
public class TestSynchronization2
{
public static void main(String args[])
{
Table obj = new Table();//only one
object MyThread1 t1=new
MyThread1(obj); MyThread2 t2=new
MyThread2(obj); t1.start();
t2.start();

}
}
Output:
5
10
15
20
25
100
200
300
400
500

Using synchronized Statement:


The general form of the synchronized statement:
synchronized (object)
{
// statements to be synchronized
}
Here, object is a reference to the object being synchronized. A synchronized block ensures that a call
to a method that is a member of object occurs only after the current thread has successfully entered
object’s monitor.
class Table
{
void printTable(int n)
{
for(int i=1;i<=5;i++)
{
System.out.println(n*
i); try
{
Thread.sleep(400);
}
catch(Exception e)
{System.out.println(e);}
}
}
}
class MyThread1 extends Thread
{
Table t ; int N; MyThread1(Table t,int n)
{
this.t = t;
N = n;
}
public void run()
{
synchronized(t) //synchronized block
{
t.printTable(n);
}
}
}
public class Test
{
public static void main(String args[])
{
Table obj = new Table();//only one
object MyThread1 t1=new
MyThread1(obj); MyThread1 t2=new
MyThread1(obj); t1.start();
t2.start();
}
}
Output:
5
10
15
20
25
100
200
300
400
500
1.7 INTER THREAD COMMUNICATION USING wait, notify and notifyAll
Inter-thread communication or Co-operation is all about allowing synchronized threads to
communicate with each other.
Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its
critical section and another thread is allowed to enter (or lock) in the same critical section to be
executed.It is implemented by following methods of Object class:
 wait()
 notify()
 notifyAll()
wait( ) tells the calling thread to give up the monitor and go to sleep until some other thread enters
the same monitor and calls notify( ). notify( ) wakes up the first thread that called wait( ) on the same
object. notifyAll( ) wakes up all the threads that called wait( ) on the same object. The highest priority
thread will run first. These methods are declared within Object, as shown here:
final void wait( ) throws
InterruptedExceptionfinal void notify( )
final void notifyAll( )
Steps for Inter thread communication:
1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it
releases the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor state of the object.

class Customer
{
int amount=10000;
synchronized void withdraw(int amount)
{
System.out.println("going to withdraw...");
if(this.amount<amount)
{
System.out.println("Less balance; waiting for deposit...");
try
{
wait();
}
catch(Exception e)
{}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}

synchronized void deposit(int amount)


{
System.out.println("going to
deposit..."); this.amount+=amount;
System.out.println("deposit
completed... ");notify();
}
}
class Samp1
{
public static void main(String args[])
{
final Customer c=new
Customer();new Thread()
{
public void run()
{
c.withdraw(15000);
}
}.start();
new Thread()
{
public void run()
{
c.deposit(10000);
}
}.start();
}
}
Output:
going to withdraw...
Less balance; waiting for
deposit...going to deposit...
deposit
completed...
withdraw
completed
1.8 PACKAGE
 A Java package is a set of classes, interfaces, and sub-packages that are similar.
 Packages are divided into two categories:
o Built-in Packages (packages from the Java API)
o User-defined Packages (create your own packages)
 Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces.
Packages are used for:
o Preventing naming conflicts. For example there can be two classes with name Employee
in two packages, college.staff.cse.Employee and college.staff.ee.Employee
o Making searching/locating and usage of classes, interfaces, enumerations and annotations
easier
o Providing controlled access: protected and default have package level access control. A
protected member is accessible by classes in the same package and its subclasses. A
default member (without any access specifier) is accessible by classes in the same
package only.
o Packages can be considered as data encapsulation (or data-hiding).
Built-in Packages
These packages consist of many classes which are a part of Java API. Some of the commonly used built-
in packages are:
1) java.lang: Contains language support classes(e.g classed which defines primitive data types,
math operations). This package is automatically imported.
2) java.io: Contains classed for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like Linked List, Dictionary
and support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for graphical user interfaces (like
button , ;menus etc).
6) java.net: Contain classes for supporting networking operations.

To use a class or a package from the library, you need to use the import keyword:
import package.name.Class; // Import a single class
import package.name.*; // Import the whole package
Import a Class
If a class want to be used from a package, for example, the Scanner class, which is used to get user input,
write the following code:
import java.util.Scanner;

User-defined packages
 To create a package, include a package command as the first statement in a Java source file. Any
classes declared within that file will belong to the specified package.
 The package statement defines a name space in which classes are stored. If the package statement
is omitted, the class names are put into the default package, which has no name.
 While the default package is fine for short, sample programs, it is inadequate for real applications.
 This is the general form of the package statement:
package pkg;
Here, pkg is the name of the package. For example, the following statement creates a package called
MyPackage.
package MyPackage;

Example
package MyPack;
class Balance
{
String name; double bal;
Balance(String n, double b)
{
name = n; bal = b;
}
void show()
{
if(bal<0)
System.out.print("--> "); JAVA LANGUAGE System.out.println(name + ": $" + bal);
}
}
class AccountBalance
{
public static void main(String args[])
{
Balance current[] = new Balance[3]; current[0] = new Balance("Sanjib", 123.23); current[1] = new
Balance("Chandan", 157.02); current[2] = new Balance("Palak", -12.33); for(int i=0; i<3; i++)
current[i].show();
}
}

Call this file AccountBalance.java, and put it in a directory called MyPack. Next, compile the file. Make
sure that the resulting .class file is also in the MyPack directory. Then try executing the AccountBalance
class, using the following command line:
java MyPack.AccountBalance
Remember, you will need to be in the directory above MyPack when you execute this command, or to
have your CLASSPATH environmental variable set appropriately. As explained, AccountBalance is
now part of the package MyPack. This means that it cannot be executed by itself. That is, you cannot
use this command line:
java AccountBalance
AccountBalance must be qualified with its package name.

1.9 ACCESS PROTECTION


In Java, access specifiers are used to defining the visibility and accessibility of class members such as
variables, methods, and inner classes. Java has four access specifiers: public, private, protected, and
default (also known as package-private). The following table shows the scope of each access specifier
in Java
Importing Packages
 Given that packages exist and are a good mechanism for compartmentalizing diverse classes
from each other, it is easy to see why all of the built-in Java classes are stored in packages.
 In a Java source file, import statements occur immediately following the package statement (if
it exists) and before any class definitions. This is the general form of the import statement:
import pkg1 [.pkg2].(classname|*);

package MyPack;
public class Balance
{
String name; double bal;
public Balance(String n, double b)
{
name = n; bal = b;
}
public void show()
{
if(bal<0) System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}
As we can see, the Balance class is now public. Also, its constructor and its show( ) method are public,
too. This means that they can be accessed by any type of code outside the MyPack package. For example,
here TestBalance imports MyPack and is then able to make use of the Balance class:

import MyPack.*; class TestBalance


{
public static void main(String args[])
{
Balance test = new Balance("J. J. Jaspers", 99.88); test.show(); // you may also call show()
}
}

1.10 COLLECTION
In general terms a collection is a “group of objects”

Collection is a container object. It is used for storing homogeneous and heterogeneous, unique and duplicate
objects without size limitation and further it is used for sending objects at a time from one class methods to
other class methods as method arguments and return type with single name across multiple layers of the project.

 Before java 1.2 it is called simply Java.util package


 From java 1.2 onwards its all classes together called as Collections Framework
 From java 5 onwards they have added new concepts called Collections and Generics
Java Collections Framework all classes are divided into following 3 different types of classes:
1. Container Objects classes
2. Cursor Objects classes
3. Utility Objects classes

Container Objects classes:


Following 4 Interfaces are called container objects
1. List <T> HashSet <T>, LinkedHashSet<T>
2. Set <T> Stack <T>, LinkedList<T>, ArrayList<T>, Vector<T>
3. Map <K,V> HashMap <K,V>, Hashtable<K,V>
4. Queue <T> LinkedList <T>
<T> Represents generic type parameter, i.e which type of elements are being stored.

Cursor objects are retrieving objects


5. Enumeration
6. Iterator
7. ListIterator

Utility Objects: it is nothing but a class that is given to perform different operations on container
objects are called utility objects i.e two classes
8. Collections class
9. Arrays

The Collection in Java is a framework that provides architecture to store and manipulate thegroup of objects.
1. Collections are the containers that groups multiple items in a single unit
2. It provides architecture to store and manipulate a group of objects
3. Using collections various operations can be performed on the data like
 searching,
 sorting,
 insertion,
 manipulation,
 deletion etc.
4. Java collection framework provide many Interfaces and classes
Collection Interfaces and class hierarchy

Iterable is the root interface of the Java collection classes. The Collection interface extends
Iterable interface, so all subtypes of Collection implement the Iterable interface. This interface stands
to represent data-structures whose value can be traversed one by one. This is an important property.
Choosing the Right Collection

SETS:
A set represents a group of elements arranged just like an array. The set will grow dynamically when the
elements are stored into it. A set will not allow duplicate elements. If we try to pass for same element that is
already available in the set, then it is not stored into the set.

LIST:
Lists are like sets. They store a group of elements. But lists allow duplicate values to be stored.
QUEUES:
A Queue represents arrangement of elements in FIFO (First In First Out) order. This means that an element
that is stored as a first element into the queue will be removed first from the queue.

MAPS:
Maps store elements in the form of key and value pairs. If the key is provided then
it’scorrespond value can be obtained. Of course, the keys should have unique values.
In the hierarchy we can divided into two groups
1. If your requirement is to group key-value pair, then choose MAP
2. If your requirement (operations are on only values) is to have only the values, then choose
collection interfaces

Retrieving Elements from Collections


Following 4 ways to retrieve any element from a collection object
1. Using for-each loop.
2. Using Iterator interface.
3. Using Listlterator interface.
4. Using Enumeration interface.
1. For-each loop:
This is like for loop which repeatedly executes a group of statements for each element of the collection. The
format is:

for(variable : collection-object)
{
Statements:
}

Here, the variable assumes each element of the collection-object and the loop is executed as many times as there
are number of elements in the collection-object. If collection-object has n elements the loop is executed exactly
n times and the variable stores each element in each step.
Example using for-each loop

class ForEachDemo{
public static void main(String args[]){
int arr[] = {12,13,14,44}; //declaring an array for(int i : arr){
//traversing the array with for-each
loopSystem.out.println(i);

}
}
}
Output: 12

13
14
44

2. Iterator Interface: Iterator is an interface that contains methods to retrieve the elements one by one
from a collection object. It retrieves elements only in forward direction. It has 3 methods:

3. ListIterator Interface: ListIterator is an interface that contains methods to retrieve the elements
from a collection object, both in forward and reverse directions. It can retrieve the elements in forward
and backward direction. It has the following important methods:
4. Enumeration Interface: This interface is useful to retrieve elements one by one like Iterator. It
has 2 methods.

HashSet Class
HashSet Class: HashSet represents a set of elements (objects). It does not guarantee the
order of elements. Also it does not allow the duplicate elements to be stored.
We can write the HashSet class as : class HashSet <T>
We can create the object as : HashSet <String> hs = new HashSet<String> ();

The following constructors are available in HashSet:

HashSet();
HashSet (int capacity); Here capacity represents how many elements can be stored into the HashSet
initially. This capacity may increase automatically when more number of elements is being stored.
Program : Write a program which shows the use of HashSet and Iterator. package
com.myPack;
import java.util.HashSet;
import java.util.Iterator;
public class HashSetDemo
{
public static void main(String[] args)
{
HashSet <String> hs = new HashSet<String> ();
hs.add ("Anil"); hs.add ("Akshara");
hs.add ("Babji");
hs.add ("Charan");
hs.add ("Raman");
// hs.add("India");
System.out.println ("HashSet = " + hs);
Iterator<String> it = hs.iterator ();
//display element by element using Iterator
System.out.println ("Elements Using Iterator: ");
while (it.hasNext() )
{
String s = (String) it.next ();
System.out.println(s);
}
}
}

Output:
HashSet = [Akshara, Raman, Babji, Anil, Charan]Elements Using Iterator: Akshara
Raman Babji
Anil Charan
Program on Hashset

LinkedHashSet Class
LinkedHashSet Class: This is a subclass of HashSet class and does not contain any additional members
on its own. LinkedHashSet internally uses a linked list to store the elements. It is a generic class that has
the declaration:

class LinkedHashSet <T>


Stack Class: A stack represents a group of elements stored in LIFO (Last In First Out) order. This means
that the element which is stored as a last element into the stack will be the first element to be
removed from the stack. Inserting the elements (Objects) into the stack is called push operation and
removing the elements from stack is called pop operation.

Searching for an element in stack is called peep operation. Insertion and deletion of elements
take place only from one side of the stack, called top of the stack.
We can write a Stack class as:
class Stack<E>
e.g.: Stack<Integer> obj = new Stack<Integer> (); Stack
Class Methods:
Program : Write a program to perform different operations on a stack.
import java.util.*;
class Stack1
{
int top = -1, st[]=new int[5];
void push(int el)
{
st[++top]=el;
}
int pop()
{
return(st[top--]);
}
void display()
{
System.out.println("\nStack elements from top to bottom\n"); for(int
i=top;i>=0;i--)

System.out.println(st[i]);
}
boolean isFull()
{
return(top==5-1);
}
boolean isEmpty()
{
return(top==-1);
}
}
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in); Stack1 s
= new Stack1();
int el = 0, ch=1;
while(ch != 4)
{
System.out.println("\n1.PUSH\n2.POP\n3.DISPLAY\n4.EXIT"); System.out.println("ENTER
YOUR CHOICE");
ch=sc.nextInt();
switch(ch)
{
case 1 :
if(s.isFull()) System.out.println("\nstack
is full"); else

{
System.out.println("Enter element");
el=sc.nextInt();
s.push(el);
}
break;
case 2:
if(s.isEmpty()) System.out.println("\nstack is
empty"); else

{
el=s.pop();
System.out.println("\nDeleted element = "+el);
}
break;
case 3:
if(s.isEmpty()) System.out.println("\nstack is
empty"); else
s.display(); break;
case 4:
break;
default:
System.out.println("\nEnter correct choice");
}
}
sc.close();
}
}

OUTPUT:
C:\Users\Anil\Desktop\2018 Java>javac Stack.java
C:\Users\Anil\Desktop\2018 Java>java Stack
1. PUSH
2. POP
3. DISPLAY
4. EXIT
ENTER YOUR CHOICE 1
Enter element
10
1. PUSH
2. POP
3. DISPLAY
4. EXIT
ENTER YOUR CHOICE 1
Enter element
20
1. PUSH
2. POP
3. DISPLAY
4. EXIT
ENTER YOUR CHOICE 1
Enter element
30
1. PUSH
2. POP
3. DISPLAY
4. EXIT
ENTER YOUR CHOICE 3
Stack elements from top to bottom 30
20
10

PUSH
1. POP
2. DISPLAY
4.EXIT
ENTER YOUR CHOICE 1
Enter element
40
1. PUSH
2. POP
3. DISPLAY
4. EXIT
ENTER YOUR CHOICE 3
Stack elements from top to bottom 40
30
20
10

1. PUSH
2. POP
3. DISPLAY
4. EXIT
ENTER YOUR CHOICE 1
Enter element
50
1. PUSH
2. POP
3. DISPLAY
4. EXIT
ENTER YOUR CHOICE 3
Stack elements from top to bottom 50
40
30
20
10

1. PUSH
2. POP
3. DISPLAY
4. EXIT
ENTER YOUR CHOICE 2
Deleted element = 50
1. PUSH
2. POP
3. DISPLAY
4. EXIT
ENTER YOUR CHOICE 4

ArrayList Class

ArrayList Class: An ArrayList is like an array, which can grow in memory dynamically. ArrayList is
not synchronized. This means that when more than one thread acts simultaneously on the ArrayList
object, the results may be incorrect in some cases.

ArrayList class can be written as:


class ArrayList <E>
We can create an object to ArrayList as:
ArrayList <String> arl = new ArrayList<String> ();
Program : Write a program that shows the use of ArrayList class.

package com.myPack;

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListDemo {


public static void main(String[] args) {
ArrayList <String> al = new ArrayList<String>();al.add ("Asia");
al.add ("North America Carona");al.add ("South America"); al.add
("Africa");

al.add ("Europe");

al.add (1,"Australia");
al.add (2, "Antarctica");
al.add (4, "Carona");
System.out.print ("Size of the Array List is: \n" +al.size ()); System.out.print
("\nRetrieving elements inArrayList using Iterator :\n"); Iterator<String> it =
al.iterator ();
while (it.hasNext () ) System.out.print
("\n" +it.next ());
}
}
Output:
Size of the Array List is:
8
Retrieving elements in ArrayList using Iterator : Asia
Australia Antarctica
North Ameria CaronaCarona
South AmericaAfrica Europe
Program on ArrayList

LinkedList Class: A linked list contains a group of elements in the form of nodes. Each node will
have three fields- the data field contatins data and the link fields contain references to previous and
next nodes.A linked list is written in the form of:

class LinkedList<E>
we can create an empty linked list for storing String type elements (objects) as:
LinkedList <String> ll = new LinkedList<String> ();
LinkedList Class methods:

Note: In case of LinkedList counting starts from 0 and we start counting from 1.

Program : Write a program that shows the use of LinkedList class.


import java.util.LinkedList;
public class LinkedListDemo {

public static void main(String[] args) {


LinkedList <String> ll = new LinkedList<String>(); ll.add
("Anil");
ll.add ("Bharathi");
ll.add ("Charan"); ll.add
("Chiranjeevi");
ll.addFirst ("Eega");
ll.add (1,"Abishai");

ll.add (2,"Abhimanyu");
System.out.println ("Elements in Linked List is :\n "+ ll);System.out.println ("Size of the
Linked List is : \n" + ll.size() );
}
}

Output:
Elements in Linked List is:
[Eega, Abishai, Abhimanyu, Anil, Bharathi, Charan,Chiranjeevi]

Size of the Linked List is:7

Program on linked List

Java Database Connectivity (JDBC)


JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the
query with the database. It is a specification from Sun Microsystems that provides a standard
abstraction (API or Protocol) for Java applications to communicate with various databases. It
provides the language with Java database connectivity standards. It is used to write programs
required to access databases. JDBC, along with the database driver, can access databases and
spreadsheets. The enterprise data stored in a relational database(RDB) can be accessed with the
help of JDBC APIs.

Definition of JDBC (Java Database Connectivity)


JDBC is an API (Application programming interface) used in Java programming to interact with
databases. The classes and interfaces of JDBC allow the application to send requests made by
users to the specified database.

Purpose of JDBC
Enterprise applications created using the JAVA EE technology need to interact with databases to
store application-specific information. So, interacting with a database requires efficient database
connectivity, which can be achieved by using the ODBC (Open database connectivity) driver. This
driver is used with JDBC to interact or communicate with various kinds of databases such as
Oracle, MS Access, Mysql, and SQL server database.

Components of JDBC
There are generally four main components of JDBC through which it can interact with a database.
1. JDBC API: It provides various methods and interfaces for easy communication with the
database. It provides two packages as follows, which contain the java SE and Java EE
platforms to exhibit WORA (write once run anywhere) capabilities. The java.sql package
contains interfaces and classes of JDBC API.
2. JDBC Driver manager: It loads a database-specific driver in an application to establish
a connection with a database. It is used to make a database-specific call to the database to
process the user request.
3. JDBC Test suite: It is used to test the operation (such as insertion, deletion, updation)
being performed by JDBC Drivers.
4. JDBC-ODBC Bridge Drivers: It connects database drivers to the database. This bridge
translates the JDBC method call to the ODBC function call. It makes use of the
sun.jdbc.odbc package which includes a native library to access ODBC characteristics.

JDBC Drivers
JDBC drivers are client-side adapters (installed on the client machine, not on the server) that
convert requests from Java programs to a protocol that the DBMS can understand. There are 4
types of JDBC drivers:
Type-1 driver or JDBC-ODBC bridge driver
Type-2 driver or Native-API driver (partially java driver)
Type-3 driver or Network Protocol driver (fully java driver)
Type-4 driver or Thin driver (fully java driver)
a. JDBC CRUD (Create, Read, Update and Delete) example
Step 1: Establish connection with database
Step 2: Create following table in MySQL database server
use test;
create table Emp(
code varchar(10) primary key,
name varchar(40) null,
city varchar(20),
salary int
);
Step3 : Following code to insert record in the above table -
public void insertEmp(String code, String name, String city, int sal) {
try {
ps = con.prepareStatement(“insert into Emp values(?,?,?,?)”);
ps.setString(1, code);
ps.setString(2, name);
ps.setString(3, city);
ps.setInt(4, sal);
int i = ps.executeUpdate();
if (i != 0) {
System.out.println(“Inserted”);
} else {
System.out.println(“not Inserted”);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Step4 : Following source code is to update employee city and salary based on employee code -
public void updateEmp(String code, String city, int salary) {
try {
ps = con.prepareStatement(“update emp set city=?,salary=salary+? where code=?”);
ps.setString(1, city);
ps.setInt(2, salary);
ps.setString(3, code);
int i = ps.executeUpdate();
if (i != 0) {
System.out.println(“updated”);
} else {
System.out.println(“not updated”);
}
} catch (Exception e) {
e.printStackTrace();
}
}

Step5 : Following source code is to delete an employee record based on employee code -
public void deleteEmp(String code) {
try {
ps = con.prepareStatement(“delete from emp where code=?”);
ps.setString(1, code);
int i = ps.executeUpdate();
if (i != 0) {
System.out.println(“deleted”);
} else {
System.out.println(“not deleted”);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Step6 : Following source code is to display an employee record based on employee code -
public void dispAnEmp(String s) {
try {
ps = con.prepareStatement(“select * from Emp where code=?”);
ps.setString(1, s);
ResultSet res = ps.executeQuery();
if (res.next()) {
System.out.print(res.getString(1));
System.out.print(res.getString(2));
System.out.print(res.getString(3));
System.out.println(res.getString(4));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
Step7 : Following source code is to display whole records from employee table -
public void dispAll() {
try {
Statement st = con.createStatement();
ResultSet res = st.executeQuery(“select * from Emp”);
while (res.next()) {
System.out.print(res.getString(1));
System.out.print(res.getString(2));
System.out.print(res.getString(3));
System.out.println(res.getString(4));
}
} catch (SQLException e) {
e.printStackTrace();
}
Hindusthan
HindusthanCollege
Collegeof
ofEngineering
Engineering and Technology
Technology
An Autonomous Institution Affiliated to Anna University | Approved by AICTE, New Delhi
(An Autonomous
Accredited with ‘A’ GradeInstitution, Affiliated to
by NAAC | Accredited by Anna University,
NBA (ECE, MECH, Chennai)
EEE, IT & CSE)
ValleyValley
Campus,Campus,
PollachiPollachi
Highway,Highway, Coimbatore
Coimbatore 641 032.| –www.hicet.ac.in
641032

22CS3251 / OBJECT ORIENTED PROGRAMMING


USING JAVA

UNIT 5 - DATA STRUCTURE IN JAVA


Arrays-Linked list- implementation of linked list-stack-implementation of stack operations-Queue-
implementation of queue operations-Tree-Binary search tree implementation-Graphs-shortest path
algorithm using java.

1. LINKED LIST
A linked list consists of nodes where each node contains a data field and a reference(link) to the next
node in the list.

Node Structure: A node in a linked list typically consists of two components:


Data: It holds the actual value or data associated with the node.
Next Pointer: It stores the memory address (reference) of the next node in the sequence.
Head and Tail: The linked list is accessed through the head node, which points to the first node in the
list.
Types of linked lists:
There are mainly three types of linked lists:

 Single-linked list
 Double linked list
 Circular linked list
Operations on Linked Lists
Insertion: Adding a new node to a linked list involves adjusting the pointers of the existing nodes to
maintain the proper sequence. Insertion can be performed at the beginning, end, or any position within
the list
Deletion: Removing a node from a linked list requires adjusting the pointers of the neighboring nodes to
bridge the gap left by the deleted node. Deletion can be performed at the beginning, end, or any position
within the list.
Searching: Searching for a specific value in a linked list involves traversing the list from the head node
until the value is found or the end of the list is reached.

Linked list implementation


import java.io.*;
public class LinkedList
{
Node head;
static class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
public static LinkedList insert(LinkedList list, int data)
{
Node new_node = new Node(data);
if (list.head == null) {
list.head = new_node;
}
else
{
Node last = list.head;
while (last.next != null)
{
last = last.next;
}
last.next = new_node;
}
return list;
}
public static void printList(LinkedList list)
{
Node currNode = list.head;
System.out.print("LinkedList: ");
while (currNode != null)
{
System.out.print(currNode.data + " ");
currNode = currNode.next;
}
} public static void main(String[] args)
{
LinkedList list = new LinkedList();
list = insert(list, 1);
list = insert(list, 2);
list = insert(list, 3);
list = insert(list, 4);
list = insert(list, 5);
list = insert(list, 6);
list = insert(list, 7);
list = insert(list, 8);
printList(list);
}
}
Advantages of Linked Lists
 Dynamic Size: Linked lists can grow or shrink dynamically, as memory allocation is done at
runtime.
 Insertion and Deletion: Adding or removing elements from a linked list is efficient, especially for
large lists.

 Flexibility: Linked lists can be easily reorganized and modified without requiring a contiguous
block of memory.
Disadvantages of Linked Lists
 Random Access: Unlike arrays, linked lists do not allow direct access to elements by index.
Traversal is required to reach a specific node.
 Extra Memory: Linked lists require additional memory for storing the pointers, compared to
arrays.

Array Linked List

An array is collection of elements having A Linked list is a collection of nodes


same data types. that contains data and address.

The location of array elements is the Location of linked list nodes is not
continuous continuous.

Linked lists are based on dynamic


Arrays are based on static memory which
memory which means the size of the
means the size of the array is fixed.
linked list is dynamic.

Memory is allocated during compile time in Memory is allocated during run-time


arrays in a linked list
Array Linked List

Memory uses is more than array


Memory uses is lesser than linked list
because linked stores data and address
because an array only contains data.
both

In an array, Memory is not utilized in an In a linked list, Memory is utilized in


efficient way because if we create an array of an efficient way as we create new node
size 10 and we only use 5 elements then it only there is required so no memory
will be a waste of memory. will be wasted.

Linked lists are faster compared to an


Arrays are slower compared to the linked
array. It takes less time to perform
list. It takes more time to perform various
various operations like insert and
operations like insert and delete
delete

Insertion (Time Complexity):- i.)At the Insertion (Time Complexity):-i.) At


start:- O(n) ii.)At the end:- O(1) iii.)At mid:- the start:- O(1) ii.) At the end:- O(n)
O(n) iii.) At mid:- O(n)

Deletion (Time Complexity):- i.) At the Deletion (Time Complexity):- i.) At


start:- O(n) ii.) At the end:- O(1) iii.) At the start:- O(1) ii.) At the end:- O(n)
mid:- O(n) iii.) At mid:- o(n)

2. STACK
 A Stack is a linear data structure that follows the LIFO (Last-In-First-Out) principle. Stack has
one end.
 It contains only one pointer top pointer pointing to the topmost element of the stack.
 Whenever an element is added in the stack, it is added on the top of the stack, and the element
can be deleted only from the stack.
 A stack can be defined as a container in which insertion and deletion can be done from the one
end known as the top of the stack.
Operations implemented on the stack:

o push(): When we insert an element in a stack then the operation is known as a push. If the stack
is full then the overflow condition occurs.
o pop(): When we delete an element from the stack, the operation is known as a pop. If the stack
is empty means that no element exists in the stack, this state is known as an underflow state.
o isEmpty(): It determines whether the stack is empty or not.
o isFull(): It determines whether the stack is full or not.'
o peek(): It returns the element at the given position.

PUSH operation

The steps involved in the PUSH operation is given below:

o Before inserting an element in a stack, we check whether the stack is full.


o If we try to insert the element in a stack, and the stack is full, then the overflow condition occurs.
o When we initialize a stack, we set the value of top as -1 to check that the stack is empty.
o When the new element is pushed in a stack, first, the value of the top gets incremented,
i.e., top=top+1, and the element will be placed at the new position of the top.
o The elements will be inserted until we reach the max size of the stack.
POP operation

The steps involved in the POP operation is given below:

o Before deleting the element from the stack, we check whether the stack is empty.
o If we try to delete the element from the empty stack, then the underflow condition occurs.
o If the stack is not empty, we first access the element which is pointed by the top
o Once the pop operation is performed, the top is decremented by 1, i.e., top=top-1.

Stack implementation
class Stack
{
private int arr[];
private int top;
private int capacity;
Stack(int size)
{
arr = new int[size];
capacity = size;
top = -1;
}
public void push(int x)
{
if (isFull())
{
System.out.println("Stack OverFlow");
System.exit(1);
}
System.out.println("Inserting " + x);
arr[++top] = x;
}
public int pop()
{
if (isEmpty())
{
System.out.println("STACK EMPTY");
System.exit(1);
}
return arr[top--];
}
public int getSize()
{
return top + 1;
}
public Boolean isEmpty()
{
return top == -1;
}
public Boolean isFull()
{
return top == capacity - 1;
}
public void printStack()
{
for (int i = 0; i <= top; i++)
{
System.out.print(arr[i] + ", ");
}
}
}
public class Main
{
public static void main(String[] args)
{
Stack stack = new Stack(5);
stack.push(1);
stack.push(2);
stack.push(3);
System.out.print("Stack: ");
stack.printStack();
stack.pop();
System.out.println("\nAfter popping out");
stack.printStack();
}
}
Application of the Stack
 Evaluating postfix expression
 Backtracking
 To check balanced parenthesis
 Function calls and recursion

Java program to evaluate an expression entered in “postfix” form using stack:


import java.util.*;
public class Main
{
static int evaluatePostfix(String exp)
{
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < exp.length(); i++)
{
char c = exp.charAt(i);
if (Character.isDigit(c))
stack.push(c - '0');
else
{
int val1 = stack.pop();
int val2 = stack.pop();
switch (c)
{
case '+':
stack.push(val2 + val1);
break;
case '-':
stack.push(val2 - val1);
break;
case '/':
stack.push(val2 / val1);
break;
case '*':
stack.push(val2 * val1);
break;
}
}
}
return stack.pop();
}
public static void main(String[] args)
{
String exp;
Scanner in = new Scanner(System.in);
System.out.println("Enter the postfix expression: ");
exp = in.nextLine();
System.out.println("postfix evaluation: "+ evaluatePostfix(exp));
}
}

Advantages of Stack
 A Stack helps to manage the data in the ‘Last in First out’ method.
 When the variable is not used outside the function in any program, the Stack can be used.
 It allows you to control and handle memory allocation and deallocation.
 It helps to automatically clean up the objects.
Disadvantages of Stack
 It is difficult in Stack to create many objects as it increases the risk of the Stack overflow.
 It has very limited memory.
 In Stack, random access is not possible.

3. QUEUE
 Queue is referred to be as First In First Out list.
 A queue can be defined as an ordered list which enables insert operations to be performed at one
end called REAR and delete operations to be performed at another end called FRONT.
 For example, people waiting in line for a rail ticket form a queue.

Operations for Queue in Data Structure are:


 enqueue() – Insertion of elements to the queue.
 dequeue() – Removal of elements from the queue.
 peek() or front()- Acquires the data element available at the front node of the queue without
deleting it.
 rear() – This operation returns the element at the rear end without removing it.
 isFull() – Validates if the queue is full.
 isEmpty() – Checks if the queue is empty.
 size(): This operation returns the size of the queue i.e. the total number of elements it contains.
Enqueue()
Inserts an element at the end of the queue i.e. at the rear end.
The following steps should be taken to enqueue (insert) data into a queue:
 Check if the queue is full.
 If the queue is full, return overflow error and exit.
 If the queue is not full, increment the rear pointer to point to the next empty space.
 Add the data element to the queue location, where the rear is pointing.
 return success.

Dequeue()
This operation removes and returns an element that is at the front end of the queue.
The following steps are taken to perform the dequeue operation:
 Check if the queue is empty.
 If the queue is empty, return the underflow error and exit.
 If the queue is not empty, access the data where the front is pointing.
 Increment the front pointer to point to the next available data element.
 The Return success.
Queue implementation
class Queue
{
int SIZE = 5;
int items[] = new int[SIZE];
int front, rear;
Queue()
{
front = -1;
rear = -1;
}
boolean isFull()
{ if (front == 0 && rear == SIZE - 1) {
return true; }
return false;
}
boolean isEmpty()
{
if (front == -1)
return true;
else
return false;
}
void enQueue(int element)
{
if (isFull())
{
System.out.println("Queue is full");
}
else
{
if (front == -1)
{
front = 0;
}
rear++;
items[rear] = element;
System.out.println("Insert " + element);
}
}
int deQueue()
{
int element;
if (isEmpty())
{
System.out.println("Queue is empty");
return (-1);
}
else
{
element = items[front];
if (front >= rear)
{
front = -1;
rear = -1;
}
else
{
front++;
}
System.out.println( element + " Deleted");
return (element);
}
}
void display()
{
int i;
if (isEmpty())
{
System.out.println("Empty Queue");
}
else
{
System.out.println("\nFront index-> " + front);
System.out.println("Items -> ");
for (i = front; i <= rear; i++)
System.out.print(items[i] + " ");
System.out.println("\nRear index-> " + rear);
}
}
}
public class Main

{
public static void main(String[] args)
{
Queue q = new Queue();
q.deQueue();
for(int i = 1; i < 6; i ++)
{
q.enQueue(i);
}
q.enQueue(6);
q.display();
q.deQueue();
q.display();
}
}
4. BINARY SEARCH TREE
Binary Search Tree is a node-based binary tree data structure which has the following properties:

 The left subtree of a node contains only nodes with keys lesser than the node’s key.
 The right subtree of a node contains only nodes with keys greater than the node’s key.
 The left and right subtree each must also be a binary search tree.

Basic Operations:
 Insertion in Binary Search Tree
 Searching in Binary Search Tree
 Deletion in Binary Search Tree
 Binary Search Tree (BST) Traversals – Inorder, Preorder, Post Order
Binary search tree implementation
public class BinarySearchTree
{
public static class Node
{
int data;
Node left;
Node right;
public Node(int data)
{
this.data = data;
this.left = null;
this.right = null;
}
}
public Node root;
public BinarySearchTree()
{
root = null;
}
public void insert(int data) {
Node newNode = new Node(data);
if(root == null){
root = newNode;
return;
}
else {
Node current = root, parent = null;
while(true) {
parent = current;
if(data < current.data) {
current = current.left;
if(current == null) {
parent.left = newNode;
return;
}
}
else {
current = current.right;
if(current == null) {
parent.right = newNode;
return;
}
} } } }
public Node minNode(Node root) {
if (root.left != null)
return minNode(root.left);
else
return root;
}
public Node deleteNode(Node node, int value) {
if(node == null){
return null;
}
else {
if(value < node.data)
node.left = deleteNode(node.left, value);
else if(value > node.data)
node.right = deleteNode(node.right, value);
else {
if(node.left == null && node.right == null)
node = null;
else if(node.left == null) {
node = node.right;
}
else if(node.right == null) {
node = node.left;
}
else {
Node temp = minNode(node.right);
node.data = temp.data;
node.right = deleteNode(node.right, temp.data);
}
}
return node;
}
}
public void inorderTraversal(Node node) {
if(root == null){
System.out.println("Tree is empty");
return;
}
else {

if(node.left!= null)
inorderTraversal(node.left);
System.out.print(node.data + " ");
if(node.right!= null)
inorderTraversal(node.right);

}
}
public static void main(String[] args) {
BinarySearchTree bt = new BinarySearchTree();
bt.insert(50);
bt.insert(30);
bt.insert(70);
bt.insert(60);
bt.insert(10);
bt.insert(90);
System.out.println("Binary search tree after insertion:");
bt.inorderTraversal(bt.root);
Node deletedNode = null;
deletedNode = bt.deleteNode(bt.root, 90);
System.out.println("\nBinary search tree after deleting node 90:");
bt.inorderTraversal(bt.root);
deletedNode = bt.deleteNode(bt.root, 30);
System.out.println("\nBinary search tree after deleting node 30:");
bt.inorderTraversal(bt.root);
deletedNode = bt.deleteNode(bt.root, 50);
System.out.println("\nBinary search tree after deleting node 50:");
bt.inorderTraversal(bt.root);
}
}
5. GRAPH
A Graph is a non-linear data structure consisting of vertices and edges. The vertices are sometimes also
referred to as nodes and the edges are lines or arcs that connect any two nodes in the graph. More
formally a Graph is composed of a set of vertices( V ) and a set of edges( E ). The graph is denoted by
G(E, V).

Components of a Graph
 Vertices: Vertices are the fundamental units of the graph. Sometimes, vertices are also known
as vertex or nodes. Every node/vertex can be labeled or unlabelled.
 Edges: Edges are drawn or used to connect two nodes of the graph. It can be ordered pair of
nodes in a directed graph. Edges can connect any two nodes in any possible way. There are no
rules. Sometimes, edges are also known as arcs. Every edge can be labeled/unlabelled.
Graphs are used to solve many real-life problems. Graphs are used to represent networks. The networks
may include paths in a city or telephone network or circuit network. Graphs are also used in social
networks like linkedIn, Facebook. For example, in Facebook, each person is represented with a
vertex(or node). Each node is a structure and contains information like person id, name, gender, locale
etc.

6. SHORTEST PATH ALGORITHM


 Dijkstra’s algorithm is a popular algorithms for solving many single-source shortest path
problems having non-negative edge weight in the graphs i.e., it is to find the shortest distance
between two vertices on a graph.
 It was developed by Dutch computer scientist Edsger W. Dijkstra in 1956.
Algorithm for Dijkstra’s Algorithm:
1) Mark the source node with a current distance of 0 and the rest with infinity.
2) Set the non-visited node with the smallest current distance as the current node.
3) For each neighbor, N of the current node adds the current distance of the adjacent node with
the weight of the edge connecting 0->1. If it is smaller than the current distance of Node, set it
as the new current distance of N.
4) Mark the current node 1 as visited.
5) Go to step 2 if there are any nodes are unvisited.

Java program to implement Dijkstra’s algorithm


import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
static final int V = 9;
int minDistance(int dist[], Boolean sptSet[])
{
int min = Integer.MAX_VALUE, min_index = -1;
for (int v = 0; v < V; v++)
if (sptSet[v] == false && dist[v] <= min) {
min = dist[v];
min_index = v;
}
return min_index;
}
void printSolution(int dist[], int n)
{
System.out.println("Vertex Distance from Source");
for (int i = 0; i < V; i++)
System.out.println(i + " tt " + dist[i]);
}
void dijkstra(int graph[][], int src)
{
int dist[] = new int[V];
Boolean sptSet[] = new Boolean[V];
for (int i = 0; i < V; i++) {
dist[i] = Integer.MAX_VALUE;
sptSet[i] = false;
}
dist[src] = 0;
for (int count = 0; count < V - 1; count++) {
int u = minDistance(dist, sptSet);
sptSet[u] = true;
for (int v = 0; v < V; v++)
if (!sptSet[v] && graph[u][v] != 0 &&
dist[u] != Integer.MAX_VALUE && dist[u] + graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}
printSolution(dist, V);
}
public static void main(String[] args)
{
int graph[][] = new int[][] { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
{ 4, 0, 8, 0, 0, 0, 0, 11, 0 },
{ 0, 8, 0, 7, 0, 4, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 4, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 11, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 } };
Main t = new Main();
t.dijkstra(graph, 0);
}
}
Part A
1. Compare data hiding and encapsulation
a. Difference between Data encapsulation and Data hiding:
S. No. Data Hiding Data Encapsulation
1 Data hiding focuses on restricting data Encapsulation is wrapping up of
use in a program to assure data security data members and methods into a
single unit.
2 Data hiding uses private access Encapsulation uses private,
modifier. protected, public access
modifiers.

2. Differentiate JVM, JRE, JDK


a. Difference between JVM, JRE, JDK:
S. No. JVM JRE JDK
1 Java Virtual Machine The Java Runtime The JDK (Java
(JVM) is the engine that Environment (JRE) is Development Kit) is a
drives the Java code. an implementation of software development
JVM. kit that develops
applications in Java.
2 JVM generates a It is a type of software JDK also consists of
.class(Bytecode) file, and package that provides various development
that file can be run in any class libraries of Java, tools (Java Debugger,
OS, but JVM should have JVM, and various JavaDoc, compilers,
in OS because JVM is other components for etc.)
platform dependent. running the
applications written in
Java programming.

3. Analyze what can go wrong if you replace && with & in the following code:
String a = Null;
if(a!=Null && a.length()>10)
{ …. }
a. && is logical AND operator (executes short-circuit behavior - the second operand is
evaluated only if needed). & is Bitwise AND operator (The bitwise & operator performs a
bitwise AND operation). Since the string is null, NullPointerException will be thrown.

4. Give the syntax of while statement in Java.


a. Syntax:
initialization;
while (condition)
{
//statements;
Increment / decrement;
}

5. How will you create an instance of class?


a. Syntax for creating an Object
ClassName objectName = new ClassName();
Example
String s = new String();

6. Consider a Loan Processing System in a Bank. Classify and list the classes and objects
for the same.
a. List of classes and objects for Loan Processing System:
Classes:
Bank
Account
Loan
Customer
Objects:
accountNumber
loanNumber

7. List the types of inner class.


a. There are four types of inner class
 Nested Inner Class
 Method Local Inner Classes
 Static Nested Classes
 Anonymous Inner Classes

8. How is multiple inheritance achieved in java?


a. In Java, multiple inheritance is achieved through the concept of interface.

9. What are the 2 types of abstraction in Java?


a. There are two ways to achieve abstraction in java:
 Abstract class (0 to 100%)
 Interface (100%)

10. State the conditions for method overriding in Java.


a. Rules for Java Method Overriding
 The method must have the same name as in the parent class
 The method must have the same parameter as in the parent class.
 There must be an IS-A relationship (inheritance).

11. What is Java Virtual Machine?


a. Java Virtual Machine (JVM) is the engine that drives the Java code. JVM generates a
.class(Bytecode) file, and that file can be run in any OS, but JVM should have in OS
because JVM is platform dependent.

12. Can a Java source file be saved using a name other than the class name? Justify.
a. Yes, it is possible to compile a java source file with different file name but it should not
contain any of the classes defined as public. When compiling, for the source file the
corresponding .class files will be created. When running, the class with main method must
be executed in order to easily identify which class need to interpret by java interpreter.
13. Infer the purpose of short-Circuit operator.
a. The && and || operators are short circuit operators. A short circuit operator is one that does
not necessarily evaluate all its operands. Benefits are
 Improved efficiency
 Reduced execution time
 Simplified code
 Improved readability

14. What is the difference between a String in Java and String in C/C++?
a. Difference between String in Java and String in C++:
S. No. String in Java String in C++
1 String is an object of String Class. String is Object of std::string Class.
2 Strings are immutable. They cannot be Strings are mutable. They can be
changed once initialized. changed after initialization.
3 String in Java is slower when modified C++ string class in STL are slower in
as compared to the StringBuffer class. implementation than Strings declared
using character array.
4 Memory allocation is static as strings Memory allocation is dynamic as we
are immutable. do not have to mention the size of the
string.

15. How will you initialize two-dimensional arrays?


a. Initializing two-dimensional array:
Syntax:
datatype arrayName = {{r1 values}{r2 values},…{rn values}};
Example:
int a[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

16. If objA1 is an object of class A created using new keyword, what does the statement
“A objA2 = objA1;” mean?
a. The statement “A objA2 = objA1;” means both objA1 and objA2 are referring same object.
So, neither duplicate object is created nor it allocates extra memory. Any changes made in
objA1 or objA2 will reflect in other.

17. What are the non-static methods defined in the Object class that are inherited by all
classes?
a. The non-static methods defined in the Object class are:
equals()
finalize()
toString()
hashCode()
getClass()
notify()
notifyall()
wait()
clone()
18. What are the rules for inner class?
a. Rules of Inner class
 The scope of the local inner class is restricted to the block they are defined in.
 A local inner class cannot be instantiated from outside the block where it is created
in.
 A local class has access to the members of its enclosing class.
 Local inner classes can extend an abstract class or implement an interface.

19. Define abstraction.


a. Data abstraction is the process of hiding the implementation details and showing only
essential information to the user. It provides the ability to simplify complex systems by
ignoring irrelevant details and reducing complexity. It can be achieved by using
 abstract classes (0 to 100% of abstraction),
 interfaces (100% of abstraction)

20. Differentiate compile time and run time polymorphism.


a. Difference between compile time and run time polymorphism
S. No. Compile Time Polymorphism Run Time Polymorphism

In Method overloading, more than one In Method overriding, the same method with
methods share the same name with different same parameters or signature but associated
1.
parameters or signature and different return with compared, different classes.
type.

In Compile time Polymorphism, the call is In Run time Polymorphism, the call is not
2.
resolved by the compiler. resolved by the compiler.

It is also known as Static binding, Early It is also known as Dynamic binding, Late
3.
binding and overloading. binding and overriding.

4. Inheritance is not involved. Inheritance is involved.

1. Can you call multiple methods in Java?


a. Method chaining in Java is a common syntax to invoke multiple methods calls in OOPs.
Each method in chaining returns an object. It violates the need for intermediate variables.
Syntax:
obj.method1().method2().method3();

2. What is the purpose of marker interface in Java?


a. A marker interface also called a tagging interface is an interface that does not have any
methods or constants inside it. It provides run-time type information about objects, so the
compiler and JVM have additional information about the object.

3. What is a thread? List out the thread states.


a. A Threads in Java is a lightweight process that allows multiple tasks to be executed
simultaneously within a single program. It enables the application to perform two or more
actions concurrently, thus improving the system's performance. There are five states:
 New,
 Runnable,
 Running, Blocked/Waiting,
 Timed Waiting and
 Terminated

4. What is the importance of thread synchronization?


a. In the Multithreading concept, multiple threads try to access the shared resources at a time
to produce inconsistent results. The main reason for using thread synchronization are
 To prevent interference between threads.
 To prevent the problem of consistency.

5. Is package a class in Java?


a. No, package is not a class. A package in Java is used to group related classes.

6. What is a linked list?


a. The LinkedList class is a collection which can contain many objects of the same type. The
elements in the linked list are stored in containers. The list holds the link to the first
container.

7. Write the routine to push an element into a stack.


a. Routing to push an element into the stack
public void push(int x)
{
if (isFull())
{
System.out.println("Stack OverFlow");
System.exit(1);
}
System.out.println("Inserting " + x);
arr[++top] = x;
}

8. When do you get underflow and overflow in queue?


a. Queue underflow happens when trying to remove an element from an empty queue and
overflow occurs when trying to add an element onto a full queue.

9. Give some applications of Trees.


a. Applications of tree data structure
 Storing naturally hierarchical data
 Databse indexing
 Parsing
 Artificial Intelligence

10. Draw the Collection hierarchy in Java.

11. What is the use of a Comparator?


a. A comparator interface is used to order the objects of user-defined classes. A comparator
object can compare two objects of the same class. If a class implements the Comparable
interface, objects created from that class can be sorted using Java's sorting algorithms.

12. How will you extend one interface by other interface?


a. The extends keyword is used to extend an interface, and the child interface inherits the
methods of the parent interface.
Syntax:
interface ChildInterface extends ParentInterface

13. When a thread is created and started, what is its initial state?
a. A thread is in “Ready” state after it has been created and started. This state signifies that
the thread is ready for execution.

14. How does java support inter-thread communication?


a. In Java, there are two ways to implement inter-thread communication:
 using wait() and notify() methods and
 using the higher-level constructs of the java.util.concurrent package.

15. What are the benefits of using packages?


a. The benefits of using Packages in Java are as follows:
 The packages organize the group of classes into a single API unit.
 It will control the naming conflicts.
 The access protection will be easier.
 Easy to locate the related classes.
 Reuse the existing classes in packages.

16. What are the different types of JDBC connections?


a. different types of drivers available in JDBC:
 Type-1 Driver or JDBC-ODBC bridge
 Type-2 Driver or Native API Partly Java Driver
 Type-3 Driver or Network Protocol Driver
 Type-4 Driver or Thin Driver

17. Differentiate Array and Linked list.


a. Difference between Array and Linked list:
S. No. Array Linked List
1 Arrays are stored in contiguous Linked list are not stored in
location contiguous location.
2 Fixed in size Dynamic in size
3 Memory is allocated at compile time. Memory is allocated at run time.
4 Uses less memory than linked list. Uses more memory because it
stores both data and the address of
the next node.

18. What is meant by underflow and overflow in stack?


a. Underflow happens when we try to pop an item from an empty stack. Overflow happens
when we try to push more items on a stack than it can hold.

19. What are methods to find shortest path algorithm?


a. Methods used to find shortest path algorithm are:
 Dijkstra's Algorithm. ...
 Bellman-Ford Algorithm

20. What are the applications of graph?


a. Applications of graph:
 Airline Scheduling
 Directions in a map
 Solving Sudoku's puzzles
 Search Engine Algorithms
 Social Media Marketing
Part B
1. Explain the methods available under String and String Buffer Class.
a. String class
The string is a sequence of characters. In Java, objects of String are immutable which means a
constant and cannot be changed once created. The String class has a set of built-in methods
that you can use on strings.
Method Description

charAt() Returns the character at the specified index (position)

compareTo() Compares two strings lexicographically

compareToIgnoreCas Compares two strings lexicographically, ignoring case


e() differences

concat() Appends a string to the end of another string

contains() Checks whether a string contains a sequence of characters

copyValueOf() Returns a String that represents the characters of the


character array

endsWith() Checks whether a string ends with the specified


character(s)

equals() Compares two strings. Returns true if the strings are equal,
and false if not

equalsIgnoreCase() Compares two strings, ignoring case considerations

getChars() Copies characters from a string to an array of chars

indexOf() Returns the position of the first found occurrence of


specified characters in a string

isEmpty() Checks whether a string is empty or not

lastIndexOf() Returns the position of the last found occurrence of


specified characters in a string

length() Returns the length of a specified string

replace() Searches a string for a specified value, and returns a new


string where the specified values are replaced

replaceFirst() Replaces the first occurrence of a substring that matches


the given regular expression with the given replacement

replaceAll() Replaces each substring of this string that matches the


given regular expression with the given replacement
split() Splits a string into an array of substrings

startsWith() Checks whether a string starts with specified characters

substring() Returns a new string which is the substring of a specified


string

toCharArray() Converts this string to a new character array

toLowerCase() Converts a string to lower case letters

toString() Returns the value of a String object

toUpperCase() Converts a string to upper case letters

trim() Removes whitespace from both ends of a string

valueOf() Returns the string representation of the specified value

Program
class Main
{
public static void main(String args[])
{
String s = "Java programming";
System.out.println("String length = " + s.length());
System.out.println("Character at 3rd position = "+ s.charAt(3));
System.out.println("Substring " + s.substring(3));
System.out.println("Substring = " + s.substring(2,5));
String s1 = "C++";
String s2 = "Programming";
System.out.println("Concatenated string = " +s1.concat(s2));
String s4 = "Python Programming";
System.out.println("Index of on " +s4.indexOf("on"));
System.out.println("Index of a = " +s4.indexOf('a',3));
Boolean out = "Java".equals("Java");
System.out.println("Checking Equality " + out);
out = "java".equals("Java");
System.out.println("Checking Equality " + out);
out = "java".equalsIgnoreCase("Java");
System.out.println("Checking Equality " + out);
int out1 = s1.compareTo(s2);
System.out.println("the difference between ASCII value is="+out1);
String word = "Hello";
System.out.println("Changing to lower Case " +word.toLowerCase());
System.out.println("Changing to UPPER Case " +word.toUpperCase());
String word1 = " Java is easy to learn ";
System.out.println("Trim the word " + word1.trim());
String str1 = "Java programming";
System.out.println("Original String " + str1);
String str2 = str1.replace("Java" ,"C") ;
System.out.println("Replaced Java with C -> " + str2);
}
}
Output
String length = 16
Character at 3rd position = a
Substring a programming
Substring = va
Concatenated string = C++Programming
Index of on 4
Index of a = 12
Checking Equality true
Checking Equality false
Checking Equality true
the difference between ASCII value is=-13
Changing to lower Case hello
Changing to UPPER Case HELLO
Trim the word Java is easy to learn
Original String Java programming
Replaced Java with C -> C programming

StringBuffer class
StringBuffer is a class in Java that represents a mutable sequence of characters. It provides an
alternative to the immutable String class, allowing to modify the contents of a string without
creating a new object every time.
Program
class Main
{
public static void main(String args[])
{
StringBuffer s = new StringBuffer("Java programming");
System.out.println("String length = " + s.length());
System.out.println("String capacity = "+s.capacity());
System.out.println("Character at 3rd position = "+ s.charAt(3));
System.out.println("Substring " + s.substring(3));
System.out.println("Substring = " + s.substring(2,5));
StringBuffer s1 = new StringBuffer("C++");
StringBuffer s2 = new StringBuffer(" Programming");
System.out.println("Concatenated string = " +s1.append(s2));
System.out.println("String1 = " + s1);
System.out.println("String2 = " + s2);
s1.insert(15," is easy to learn");
System.out.println("String1 = " + s1);
s1.replace(0,3, "Java");
System.out.println("String1 = " + s1);
s1.delete(0, 4);
System.out.println("String1 = " + s1);
s1.reverse();
System.out.println("String1 = " + s1);
}
}
Output
String length = 16
String capacity = 32
Character at 3rd position = a
Substring a programming
Substring = va
Concatenated string = C++ Programming
String1 = C++ Programming
String2 = Programming
String1 = C++ Programming is easy to learn
String1 = Java Programming is easy to learn
String1 = Programming is easy to learn
String1 = nrael ot ysae si gnimmargorP

2. What are the three categories of control statements used in Java? Explain each
category with example.
a. A programming language uses control statements to control the flow of execution of a
program based on certain conditions. Java’s Selection statements:
 if
 switch-case
 jump

i) If Statements
 Simple if
 If else
 If-else-if Ladder
 Nested if

a) Simple if
It is used to decide whether a certain statement or block of statements will be executed
or not. If a certain condition is true then a block of statements is executed otherwise
not.
Syntax
if(condition)
{
// Statements to execute if
// condition is true
}
The statements will be evaluated if the value of the condition is true
Example
import java.util.*;
class Main
{
public static void main(String args[])
{
int n;
Scanner in = new Scanner(System.in);
System.out.println("Enter n: ");
n = in.nextInt();
if(n>0)
System.out.println(n+" is a positive number!");
}
}
Output
Enter n:
3
3 is a positive number!

b) If-else Syntax
Together with if, else statement can be used to execute a block of code when the
condition is false.
Syntax:
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Example
import java.util.*;
class Main
{
public static void main(String args[])
{
int n;
Scanner in = new Scanner(System.in);
System.out.println("Enter n: ");
n = in.nextInt();
if(n>=10 && n<100)
System.out.println(n+" is a Two digit number!");
else
System.out.println(n+" is not a Two digit number!");
}
}
Output
Enter n:
86
86 is a Two digit number!

c) Nested if
A nested if is an if statement that is the target of another if or else. Nested if statements
mean an if statement inside an if statement.
Syntax
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
Example
import java.util.*;
class Main
{
public static void main(String args[])
{
int n1, n2, n3;
Scanner in = new Scanner(System.in);
System.out.println("Enter 3 numbers: ");
n1 = in.nextInt();
n2 = in.nextInt();
n3 = in.nextInt();
if(n1>n2)
{
if(n1>n3)
{
System.out.println(n1+" is greater!");
}
}
else
{
if(n2>n3)
System.out.println(n2+" is greater!");
else
System.out.println(n3+" is greater!");
}
}
}
Output
Enter 3 numbers:
89
125
36
125 is greater!

d) if-else-if ladder
Syntax:
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;

Example
import java.util.*;
class Main
{
public static void main(String args[])
{
int mark;
Scanner in = new Scanner(System.in);
System.out.println("Enter a mark: ");
mark = in.nextInt();
if(mark>90)
{
System.out.println("Grade - O");
}
else if(mark>80)
{
System.out.println("Grade - A");
}
else if(mark>70)
{
System.out.println("Grade - B");
}
else if(mark>60)
{
System.out.println("Grade - C");
}
else if(mark>=50)
{
System.out.println("Grade - D");
}
else
{
System.out.println("Fail");
}
}
}
Output
Enter a mark:
86
Grade – A

ii) switch
The switch statement is a multiway branch statement. It provides an easy way to
dispatch execution to different parts of code based on the value of the expression.
Syntax
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
Example
import java.util.*;
class Main
{
public static void main(String args[])
{
int n;
Scanner in = new Scanner(System.in);
System.out.println("Enter n: ");
n = in.nextInt();
switch(n)
{
case 1 :
System.out.println("Monday");
break;
case 2 :
System.out.println("Tuesday");
break;
case 3 :
System.out.println("Wednesday");
break;
case 4 :
System.out.println("Thursday");
break;
case 5 :
System.out.println("Friday");
break;
case 6 :
System.out.println("Saturday");
break;
case 7 :
System.out.println("Sunday");
break;
default:
System.out.println("Invalid");
}
}
}
Output
Enter n:
5
Friday
iii) Jump
jump: Java supports three jump statements: break and continue. These statements transfer
control to another part of the program.
a) break: In Java, a break is majorly used to terminate a sequence in a switch statement.
b) continue: Sometimes it is useful to force an early iteration of a loop.
Example for break
import java.util.*;
class Main
{
public static void main(String args[])
{
int n;
Scanner in = new Scanner(System.in);
System.out.println("Enter n: ");
n = in.nextInt();
for (int i = 1; i < n; i++)
{
if (i == 5)
break;
System.out.print(i + " ");
}
}
}
Output
Enter n:
10
1234

Example for continue


import java.util.*;
class Main
{
public static void main(String args[])
{
int n;
Scanner in = new Scanner(System.in);
System.out.println("Enter n: ");
n = in.nextInt();
for (int i = 0; i < n; i++)
{
if (i % 2 == 0)
continue;
System.out.print(i + " ");
}
}
}
Output
Enter n:
20
1 3 5 7 9 11 13 15 17 19
3. Write a Java program to evaluate the following series 1-2+3-4+…+n
Program
import java.util.*;
class Main
{
public static void main(String[] args)
{
int i, num, sum = 0;
Scanner in = new Scanner(System.in);
System.out.println("Enter num: ");
num = in.nextInt();
for(i = 1;i <= num;i++)
{
if(i%2==0)
sum-=i;
else
sum+=i;
}
System.out.println("Sum of series 1-2+3-4+…+n = " + sum);
}
}
Output
Enter num:
5
Sum of natural Numbers is = 3

4. Write a Java program to print the prime numbers between the given two limits
a. Program
import java.util.*;
class Main
{
public static void main(String[] args)
{
int n1, n2;
Scanner in = new Scanner(System.in);
System.out.print("Enter the range: ");
n1 = in.nextInt();
n2 = in.nextInt();
while (n1 < n2)
{
boolean flag = false;
for(int i = 2; i <= n1/2; ++i)
{
if(n1 % i == 0)
{
flag = true;
break;
}
}
if (!flag && n1 != 0 && n1 != 1)
System.out.print(n1 + " ");
++n1;
}
}
}
Output
Enter the range: 20
40
23 29 31 37

5. Write a Java program to find a smallest number in the given one-dimensional array
and two-dimensional array using new operator.
a. Program
import java.util.*;
class Main
{
public static void main(String[] args)
{
int a[] = new int[10];
int n, min;
Scanner in = new Scanner(System.in);
System.out.print("Enter n: ");
n = in.nextInt();
System.out.print("Enter the array elements: ");
for(int i=0;i<n;i++)
{
a[i] = in.nextInt();
}
min = a[0];
for (int i = 1; i < n; i++)
{
if(a[i] < min)
min = a[i];
}
System.out.println("Smallest element present in given array: " + min);
}
}
Output
Enter n: 5
Enter the array elements: 34
23
89
6
235
Smallest element present in given array: 6
Program
import java.util.*;
class Main
{
public static void main(String[] args)
{
int a[][] = new int[3][3];
int r, c, min;
Scanner in = new Scanner(System.in);
System.out.print("Enter r & c: ");
r = in.nextInt();
c = in.nextInt();
System.out.print("Enter the array elements: ");
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
a[i][j] = in.nextInt();
}
}
min = a[0][0];
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
if (a[i][j] < min)
{
min = a[i][j];
}
}
}
System.out.println("Smallest element present in given array: " + min);
}
}
Output
Enter r & c: 2
2
Enter the array elements: 45
67
12
345
Smallest element present in given array: 12

6. Use the different methods in java.util.Arrays class with example.


a. The Arrays class in java.util package is a part of the Java Collection Framework. This class
provides static methods to dynamically create and access Java arrays. It consists of only
static methods and the methods of Object class.
Methods in Java Array Class
 sort(originalArray) - Sorts the complete array in ascending order.
 compare(array 1, array 2) - Compares two arrays passed as parameters
lexicographically.
 binarySearch() - Searches for the specified element in the array with the help of
the Binary Search Algorithm
 equals(array1, array2) - Checks if both the arrays are equal or not.
 hashCode(originalArray) - Returns an integer hashCode of this array instance.
 fill(originalArray, fillValue) - Assigns this fill value to each index of this arrays.
 toString(originalArray) - It returns a string representation of the contents of this
array.

Example
import java.util.*;
class Main
{
public static void main(String args[])
{
int a[] = {5, 78, 45, 92, 10};
int b[] = {89, 8, 65, 44, 17};
int n;
Scanner in = new Scanner(System.in);
System.out.println("Array-A before sorting: ");
for(int i : a)
{
System.out.print(i+" ");
}
Arrays.sort(a);
System.out.println("\nArray-A after sorting: ");
for(int i : a)
{
System.out.print(i+" ");
}
System.out.println("\nEnter the element to search: ");
n = in.nextInt();
System.out.println(n + " found at index = "+ Arrays.binarySearch(a, n));
System.out.println("Array-B: ");
for(int i : b)
{
System.out.print(i+" ");
}
System.out.println("\nComparing A & B: "+ Arrays.compare(a, b));
}
}

7. Explain about inner classes and its types with examples.


a. Inner class refers to the class that is declared inside class or interface. There are basically
four types of inner classes in java:
i. Nested Inner Class
ii. Method Local Inner Classes
iii. Static Nested Classes
iv. Anonymous Inner Classes
i) Nested Inner class
class Outer
{
class Inner
{
public void show()
{
System.out.println("In a nested class method");
}
}
}
class Main
{
public static void main(String[] args)
{
Outer.Inner in = new Outer().new Inner();
in.show();
}
}
ii) Method local inner class
class Outer
{
void outerMethod()
{
System.out.println("inside outerMethod");
class Inner
{
void innerMethod()
{
System.out.println("inside innerMethod");
}
}
Inner y = new Inner();
y.innerMethod();
}
}
class Main
{
public static void main(String[] args)
{
Outer x = new Outer();
x.outerMethod();
}
}
iii)Static nested classes
class Outer {
private static void outerMethod()
{
System.out.println("inside outerMethod");
}
static class Inner {
public static void display()
{
System.out.println("inside inner class Method");
outerMethod();
}
}
}
class Main {
public static void main(String args[])
{
Outer.Inner.display();
}
}
iv) Anonymous Inner class
abstract class Example
{
abstract void display();
}

class Main
{
public static void main(String args[])
{
Example obj=new Example()
{
void display(){System.out.println("Java anonymous inner class");
}
};
obj.display();
}
}

8. Explain with suitable examples for non-static methods which are defined in the Object
class.
a. Object class is present in java.lang package. Every class in Java is directly or indirectly
derived from the Object class. If a class does not extend any other class, then it is a direct
child class of Object and if extends another class then it is indirectly derived. Therefore, the
Object class methods are available to all Java classes.
Methods supported by Object class

Program
class Student
{
static int last_roll = 100;
int roll_no;
Student()
{
roll_no = last_roll;
last_roll++;
}
public int hashCode() { return roll_no; }
}
public class Main
{
public static void main(String args[])
{
Student s = new Student();
Object obj = new String("Object class");
Class c = obj.getClass();
System.out.println("Class of Object obj is : "+ c.getName());
System.out.println(s);
System.out.println(s.toString());
}
public void finalize()
{
System.out.println("finalize() method will be executed finally");
}
}

9. What is inheritance? Classify the types of Inheritance and explain any three types of
inheritance with suitable examples.
a. Inheritance is the mechanism by which one class is allowed to inherit the features (data
members and methods) of another class. A class that inherits from another class can reuse
the methods and fields of that class. The extends keyword is used for inheritance in Java.
Syntax :
class derived-class extends base-class
{
data members;
methods;
}
There are five types of inheritance:

i) Single Inheritance
import java.util.*;
class Student{
String name;
int regno;
String branch;
public Student()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter name, branch & regno: ");
name = in.nextLine();
branch = in.nextLine();
regno = in.nextInt();
}
public void display()
{
System.out.println("Name : "+name);
System.out.println("Reg. No : "+regno);
System.out.println("Branch : "+branch);
}
}
class Exam extends Student
{ int m1, m2, m3, m4, total;
double avg;
public Exam()
{ super();
Scanner in = new Scanner(System.in);
System.out.println("Enter four marks: ");
m1 = in.nextInt();
m2 = in.nextInt();
m3 = in.nextInt();
m4 = in.nextInt();
}
public void showMarks()
{ total = m1 + m2 + m3 + m4;
avg = total / 4;
System.out.println("Marks: "+m1+" "+m2+" "+m3+" "+m4);
System.out.println("Total: "+total);
System.out.println("Average: "+avg);
}
}
class Main
{
public static void main(String args[])
{
Exam s1 = new Exam();
s1.display();
s1.showMarks();
}
}
ii) Multilevel
import java.util.*;
class GrandFather
{
String gf_name;
public GrandFather()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter grand father name: ");
gf_name = in.nextLine();
}
}
class Father extends GrandFather
{
String f_name;
public Father()
{
super();
Scanner in = new Scanner(System.in);
System.out.println("Enter father name: ");
f_name = in.nextLine();
}
}
class Son extends Father
{ String s_name;
public Son()
{ super();
Scanner in = new Scanner(System.in);
System.out.println("Enter son name: ");
s_name = in.nextLine();
}
public void display()
{
System.out.println("GrandFather's Name : "+gf_name);
System.out.println("Father's Name : "+f_name);
System.out.println("Son's Name : "+s_name);
}
}
class Main
{
public static void main(String args[])
{ Son obj = new Son();
obj.display();
}
}

iii)Hierarchical
import java.util.*;
class Shape
{ double area;
public void calc_area() {}
}
class Square extends Shape
{ int a;
public Square()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a: ");
a = in.nextInt();
}
public void calc_area()
{
area = a * a;
System.out.println("Area of Square = "+area);
}
}
class Circle extends Shape
{ int r;
final double pai = 3.14;
public Circle()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter r: ");
r = in.nextInt();
}
public void calc_area()
{ area = r * pai * pai;
System.out.println("Area of Circle = "+area);
}
}
class Main
{ public static void main(String args[])
{ Square sobj = new Square();
Circle cobj = new Circle();
sobj.calc_area();
cobj.calc_area();
}
}

10. Write a Java program that implements the concept of method overriding to find the
area of rectangle and triangle.
import java.util.*;
class Rectangle
{
double area, l, b;
Scanner in = new Scanner(System.in);
public void get()
{
System.out.print("Enter l and b: ");
l = in.nextDouble();
b = in.nextDouble();
}
public void calculate()
{
area = l * b;
System.out.println("Area of Rectangle = "+area);
}
}
class Triangle extends Rectangle
{
double h;
public void get()
{
System.out.print("Enter b and h: ");
b = in.nextDouble();
h = in.nextDouble();
}
public void calculate()
{
area = 0.5 * b * h;
System.out.println("Area of Triangle = "+area);
}
}
class Main
{
public static void main(String args[])
{
Rectangle robj = new Rectangle();
robj.get();
robj.calculate();
Triangle tobj = new Triangle();
tobj.get();
tobj.calculate();
}
}
Output
Enter l and b: 6
3
Area of Rectangle = 18.0
Enter b and h: 6
3
Area of Triangle = 9.0

11. Write a Java program that implements the concept of method overloading to find the
volume of cube and rectangular prism.
class Main
{
static double cube, prism;
public static void calculate(double a)
{
cube = a * a * a;
System.out.println("Volume of cube = "+cube);
}
public static void calculate(double w, double h, double l)
{
prism = w* h * l;
System.out.println("Volume of prism = "+prism);
}
public static void main(String args[])
{
double a, w, h, l;
calculate(20.5);
calculate(12.5, 15.25, 23.68);
}
}

12. Write a Java program to create a student examination database system that prints
the mark sheet of students. Input student name, marks in 6 subjects. This mark
should be between and 100. If the average of marks is >= 80 then prints Grade ’A’,
If the average is <80 and >=60 then prints Grade ‘B’. If the average is <60 and >= 40
then prints Grade ‘C’ else prints Grade ‘D’.
import java.util.*;
class Student
{
String name;
int marks[] = new int[6];
int total;
double avg;
char grade;
Student()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter name & 6 marks: ");
name = in.nextLine();
for(int i=0;i<6;i++)
{
marks[i] = in.nextInt();
}
}
public void calculate()
{
total = 0;
for(int i=0;i<6;i++)
{
total += marks[i];
}
avg = total / 6;
if(avg >= 80 )
grade = 'A';
else if(avg >=60 )
grade = 'B';
else if(avg >=40 )
grade = 'C';
else
grade = 'D';
}
public void display()
{
System.out.println("Name: "+name);
System.out.println("Total: "+total);
System.out.println("Average :"+avg);
System.out.println("Grade: "+grade);
}
}
class Main
{
public static void main(String[] args)
{
Student obj = new Student();
obj.calculate();;
obj.display();
}
}

13. Create a class Student. The Student class has data members such as rollno, name and
branch. Create a class Exam that has data members rollno and six subject marks.
Derive the Result class from Student and Exam and it has own data members such
as total and result. Write a Java program to model the relationships.
import java.util.*;
class Student
{
String name, branch;
int rollno;
Scanner in = new Scanner(System.in);
Student()
{
System.out.print("Enter name, rollno & branch: ");
name = in.next();
rollno = in.nextInt();
branch = in.next();
}
}
class Exam extends Student
{
int marks[] = new int[6];
Exam()
{
super();
System.out.print("Enter 6 marks: ");
for(int i=0;i<6;i++)
{
marks[i] = in.nextInt();
}
}
}
class Result extends Exam
{
int total;
double result;
char grade;
Result()
{
super();
}
public void calculate()
{
total = 0;
for(int i=0;i<6;i++)
{
total += marks[i];
}
result = total / 6;
if(result >= 80 )
grade = 'A';
else if(result >=60 )
grade = 'B';
else if(result >=40 )
grade = 'C';
else
grade = 'D';
}
public void display()
{
System.out.println("Name: "+name);
System.out.println("Rollno: "+rollno);
System.out.println("Branch: "+branch);
System.out.println("Total: "+total);
System.out.println("Result :"+result);
System.out.println("Grade: "+grade);
}
}
class Main
{
public static void main(String[] args)
{
Result obj = new Result();
obj.calculate();;
obj.display();
}
}
Output
Enter name, rollno & branch: ram
10
cse
Enter 6 marks: 89
78
23
44
98
65
Name: ram
Rollno: 10
Branch: cse
Total: 397
Result :66.0
Grade: B

1) Explain nested interfaces with an example program.


a. An interface, i.e., declared within another interface or class, is known as a nested interface.
The nested interfaces are used to group related interfaces so that they can be easy to
maintain. The nested interface must be referred to by the outer interface or class. It cannot
be accessed directly.
Rules for declaring nested interface
 A nested interface declared within an interface must be public.
 A nested interface declared within a class can have any access modifier.
 A nested interface is by default static.
Syntax of nested interface which is declared within the interface
interface Interface_name
{
...
interface Nested_interface_name
{
...
}
}
Syntax of nested interface which is declared within the class
class Class_name
{
...
interface Nested_interface_name
{
...
}
}

Example – Interface nested inside another interface


interface Showable
{
void show();
interface Message
{
void msg();
}
}
class Main implements Showable.Message
{
public void msg()
{
System.out.println("Nested interface method");
}
public static void main(String args[])
{
Showable.Message obj = new Main();
obj.msg();
}
}
Output
Nested interface method

Example – Interface nested inside the class


class Outer
{
interface Message
{
void msg();
}
}
class Main implements Outer.Message
{
public void msg()
{
System.out.println("Nested interface");
}
public static void main(String args[])
{
Outer.Message obj = new Main();
obj.msg();
}
}
Output
Nested interface

Uses of Nested Interfaces


 To group related interfaces together
 To create more secure code
 To implement multiple interfaces
 To create callbacks
 To define a contract between classes

2) Write a Java program to demonstrate working of Comparator Interface.


a. A comparator interface is used to order the objects of user-defined classes. A comparator object
can compare two objects of the same class. This interface is found in java.util package.
Methods of Java Comparator Interface
• compare(Object obj1,Object obj2) and
• equals(Object element)

Method Description
public int compare(Object obj1, It compares the first object with the second object.
Object obj2)

public boolean equals(Object obj) It is used to compare the current object with the
specified object.

public boolean equals(Object obj) It is used to compare the current object with the
specified object.
Example
import java.io.*;
import java.util.*;
class Student
{

int rollno;
String name, address;
public Student(int rollno, String name, String address)
{
this.rollno = rollno;
this.name = name;
this.address = address;
}
public String toString()
{
return this.rollno + " " + this.name + " "+ this.address;
}
}
class Sortbyroll implements Comparator<Student>
{
public int compare(Student a, Student b)
{
return a.rollno - b.rollno;
}
}
class Sortbyname implements Comparator<Student>
{
public int compare(Student a, Student b)
{

return a.name.compareTo(b.name);
}
}
class Main
{
public static void main(String[] args)
{
ArrayList<Student> ar = new ArrayList<Student>();
ar.add(new Student(111, "Mayank", "london"));
ar.add(new Student(131, "Anshul", "nyc"));
ar.add(new Student(121, "Solanki", "jaipur"));
ar.add(new Student(101, "Aggarwal", "Hongkong"));
System.out.println("Unsorted");
for (int i = 0; i < ar.size(); i++)
System.out.println(ar.get(i));
Collections.sort(ar, new Sortbyroll());
System.out.println("\nSorted by rollno");
for (int i = 0; i < ar.size(); i++)
System.out.println(ar.get(i));
Collections.sort(ar, new Sortbyname());
System.out.println("\nSorted by name");
for (int i = 0; i < ar.size(); i++)
System.out.println(ar.get(i));
}
}
Output
Unsorted
111 Mayank london
131 Anshul nyc
121 Solanki jaipur
101 Aggarwal Hongkong

Sorted by rollno
101 Aggarwal Hongkong
111 Mayank london
121 Solanki jaipur
131 Anshul nyc

Sorted by name
101 Aggarwal Hongkong
131 Anshul nyc
111 Mayank london
121 Solanki Jaipur

3) Develop a Java program to implement the concept of Inter-thread communication.


Explain life cycle of thread with help of a diagram. How do the wait and Notify All/ Notify
methods enable cooperation between threads?
a. In Java, a thread always exists in any one of the following states. These states are:
 New
 Active
 Blocked / Waiting
 Timed Waiting
 Terminated
 New: Whenever a new thread is created, it is always in the new state. For a thread in the new
state, the code has not been run yet and thus has not begun its execution.
 Active: When a thread invokes the start() method, it moves from the new state to the active state.
The active state contains two states within it: one is runnable, and the other is running.
 Runnable: A thread, that is ready to run is then moved to the runnable state. In the runnable state,
the thread may be running or may be ready to run at any given instant of time. It is the duty of
the thread scheduler to provide the thread time to run, i.e., moving the thread the running state.
 Running: When the thread gets the CPU, it moves from the runnable to the running state.
Generally, the most common change in the state of a thread is from runnable to running and again
back to runnable.
 Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently) then,
either the thread is in the blocked state or is in the waiting state.
 Timed Waiting: Sometimes, waiting for leads to starvation. A real example of timed waiting is
when we invoke the sleep() method on a specific thread. The sleep() method puts the thread in
the timed wait state. After the time runs out, the thread wakes up and start its execution from
when it has left earlier.
 Terminated: A thread reaches the termination state because of the following reasons:
 When a thread has finished its job, then it exists or terminates normally.
 Abnormal termination: It occurs when some unusual events such as an unhandled
exception or segmentation fault.
Example program for inter-thread communication
class Customer
{
int amount=10000;
synchronized void withdraw(int amount)
{
System.out.println("going to withdraw...");
if(this.amount<amount)
{
System.out.println("Less balance; waiting for deposit...");
try{wait();}
catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount)
{
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Main
{
public static void main(String args[])
{
final Customer c=new Customer();
new Thread()
{
public void run(){c.withdraw(15000);}
}.start();
new Thread()
{
public void run(){c.deposit(10000);}
}.start();
}
}

4) Write a Java program to create a simple JDBC application.


Write a Java program to establish a connection with MySQL database and retrieving data
from db using Java Database connectivity.
a. JDBC CRUD (Create, Read, Update and Delete) example
Step 1: Establish connection with database
Step 2: Create following table in MySQL database server
use test;
create table Emp(
code varchar(10) primary key,
name varchar(40) null,
city varchar(20),
salary int
);
Step3 : Following code to insert record in the above table -
public void insertEmp(String code, String name, String city, int sal) {
try {
ps = con.prepareStatement(“insert into Emp values(?,?,?,?)”);
ps.setString(1, code);
ps.setString(2, name);
ps.setString(3, city);
ps.setInt(4, sal);
int i = ps.executeUpdate();
if (i != 0) {
System.out.println(“Inserted”);
} else {
System.out.println(“not Inserted”);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Step4 : Following source code is to update employee city and salary based on employee code
-
public void updateEmp(String code, String city, int salary) {
try {
ps = con.prepareStatement(“update emp set city=?,salary=salary+? where code=?”);
ps.setString(1, city);
ps.setInt(2, salary);
ps.setString(3, code);
int i = ps.executeUpdate();
if (i != 0) {
System.out.println(“updated”);
} else {
System.out.println(“not updated”);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Step5 : Following source code is to delete an employee record based on employee code -
public void deleteEmp(String code) {
try {
ps = con.prepareStatement(“delete from emp where code=?”);
ps.setString(1, code);
int i = ps.executeUpdate();
if (i != 0) {
System.out.println(“deleted”);
} else {
System.out.println(“not deleted”);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Step6 : Following source code is to display an employee record based on employee code -
public void dispAnEmp(String s) {
try {
ps = con.prepareStatement(“select * from Emp where code=?”);
ps.setString(1, s);
ResultSet res = ps.executeQuery();
if (res.next()) {
System.out.print(res.getString(1));
System.out.print(res.getString(2));
System.out.print(res.getString(3));
System.out.println(res.getString(4));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
Step7 : Following source code is to display whole records from employee table -
public void dispAll() {
try {
Statement st = con.createStatement();
ResultSet res = st.executeQuery(“select * from Emp”);
while (res.next()) {
System.out.print(res.getString(1));
System.out.print(res.getString(2));
System.out.print(res.getString(3));
System.out.println(res.getString(4));
}
} catch (SQLException e) {
e.printStackTrace();
}

5) Explain Stack ADT. Write a Java program to implement Stack.


a. Java program to implement Stack ADT
class Stack
{
private int arr[];
private int top;
private int capacity;
Stack(int size)
{
arr = new int[size];
capacity = size;
top = -1;
}
public void push(int x)
{
if (isFull())
{
System.out.println("Stack OverFlow");
System.exit(1);
}
System.out.println("Inserting " + x);
arr[++top] = x;
}
public int pop()
{
if (isEmpty())
{
System.out.println("STACK EMPTY");
System.exit(1);
}
return arr[top--];
}
public int getSize()
{
return top + 1;
}
public Boolean isEmpty()
{
return top == -1;
}
public Boolean isFull()
{
return top == capacity - 1;
}
public void printStack()
{
for (int i = 0; i <= top; i++)
{
System.out.print(arr[i] + ", ");
}
}
}
public class Main
{
public static void main(String[] args)
{
Stack stack = new Stack(5);
stack.push(1);
stack.push(2);
stack.push(3);
System.out.print("Stack: ");
stack.printStack();
stack.pop();
System.out.println("\nAfter popping out");
stack.printStack();
}
}

6) Originate Dijkstra’s algorithm to solve the shortest path problem.


a. Java program to implement Dijkstra’s algorithm
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
static final int V = 9;
int minDistance(int dist[], Boolean sptSet[])
{
int min = Integer.MAX_VALUE, min_index = -1;
for (int v = 0; v < V; v++)
if (sptSet[v] == false && dist[v] <= min) {
min = dist[v];
min_index = v;
}
return min_index;
}
void printSolution(int dist[], int n)
{
System.out.println("Vertex Distance from Source");
for (int i = 0; i < V; i++)
System.out.println(i + " tt " + dist[i]);
}
void dijkstra(int graph[][], int src)
{
int dist[] = new int[V];
Boolean sptSet[] = new Boolean[V];
for (int i = 0; i < V; i++) {
dist[i] = Integer.MAX_VALUE;
sptSet[i] = false;
}
dist[src] = 0;
for (int count = 0; count < V - 1; count++) {
int u = minDistance(dist, sptSet);
sptSet[u] = true;
for (int v = 0; v < V; v++)
if (!sptSet[v] && graph[u][v] != 0 &&
dist[u] != Integer.MAX_VALUE && dist[u] + graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}
printSolution(dist, V);
}
public static void main(String[] args)
{
int graph[][] = new int[][] { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
{ 4, 0, 8, 0, 0, 0, 0, 11, 0 },
{ 0, 8, 0, 7, 0, 4, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 4, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 11, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 } };
Main t = new Main();
t.dijkstra(graph, 0);
}
}

7) Write java application program for generating four threads to perform following
operations:
 Getting N numbers as input
 Printing even numbers
 Printing odd numbers
 Computing average
a. Four threads
import java.util.Scanner;
class MyThread1 extends Thread
{
Scanner in = new Scanner(System.in);
public void run()
{
System.out.println("Enter n: ");
int n = in.nextInt();
int nums[] = new int[n];
System.out.println("Enter " + n + " numbers");
for(int i = 0; i < n; i++)
{
nums[i] = in.nextInt();
}
}
}
class MyThread2 extends Thread
{
Scanner in = new Scanner(System.in);
public void run()
{
System.out.println("Enter n: ");
int n = in.nextInt();
System.out.println("Even numbers in the range 1 - " + n);
for(int i = 2; i <= n; i = i + 2)
System.out.println(i + " ");
}
}

class MyThread3 extends Thread


{
Scanner in = new Scanner(System.in);
public void run()
{
System.out.println("Enter n: ");
int n = in.nextInt();
System.out.println("Odd numbers in the range 1 - " + n);
for(int i = 1; i <= n; i = i + 2)
System.out.println(i + " ");
}
}

class MyThread4 extends Thread


{
Scanner in = new Scanner(System.in);
public void run()
{
System.out.println("Enter n: ");
int n = in.nextInt();
int sum = 0;
float avg = 0.0f;
for(int i = 0; i < n; i++)
sum = sum + i;
avg = (float) sum / n;
System.out.println("Average is : " + avg);
}
}

public class Main


{
public static void main(String[] args) throws InterruptedException
{
MyThread1 t1 = new MyThread1();
MyThread2 t2 = new MyThread2();
MyThread3 t3 = new MyThread3();
MyThread4 t4 = new MyThread4();
t1.start();
t2.start();
t3.start();
t4.start();
}
}

8) Explain multithreading, thread states and thread priority. Write a java program to illustrate
about thread priorities.
a. Each thread has a priority. Priorities are represented by a number between 1 and 10. The thread
scheduler schedules the threads according to their priority (known as pre-emptive scheduling).
The default priority of a thread is 5. Thread class in Java also provides several priority constants
to define the priority of a thread. These are:
 public static int NORM_PRIORITY = 5
 public static int MIN_PRIORITY = 1
 public static int MAX_PRIORITY = 10
These constants are public, final, and static members of the Thread class. Thread scheduler
selects the thread for execution on the first-come, first-serve basis. The threads having equal
priorities share the processor time on the first-come, first-serve basis. When multiple threads
are ready for execution, the highest priority thread is selected and executed by JVM. In case
when a high priority thread stops, yields, or enters the blocked state, a low priority thread starts
executing.
To get and set priority of a thread in java.
 public final int getPriority(): java.lang.Thread.getPriority() method returns priority
of given thread.
 public final void setPriority(int newPriority): java.lang.Thread.setPriority() method
changes the priority of thread to the value newPriority.
Program
class Main
{
public static void main(String[] args) throws InterruptedException
{
Thread t1 = new Thread(() -> {
System.out.println("Thread in execution");
System.out.println("Current state of the thread - " + Thread.currentThread().getState());
});
System.out.println("State of the thread - " + t1.getState());
System.out.println("Priority of the thread t1 is : " + t1.getPriority());
t1.setPriority(6);
t1.start();
t1.join();
System.out.println("Priority of the thread t1 is : " + t1.getPriority());
System.out.println("State of the thread - " + t1.getState());
Thread t2 = new Thread(() -> {
System.out.println("Thread in execution");
System.out.println("Current state of the thread - " + Thread.currentThread().getState());
});
System.out.println("State of the thread - " + t2.getState());
System.out.println("Priority of the thread t1 is : " + t2.getPriority());
t2.setPriority(9);
t2.start();
t2.join();
System.out.println("State of the thread - " + t2.getState());
System.out.println("Priority of the thread t2 is : " + t2.getPriority());
}
}
Output
State of the thread - NEW
Priority of the thread t1 is : 5
Thread in execution
Current state of the thread - RUNNABLE
Priority of the thread t1 is : 6
State of the thread - TERMINATED
State of the thread - NEW
Priority of the thread t1 is : 5
Thread in execution
Current state of the thread - RUNNABLE
State of the thread - TERMINATED
Priority of the thread t2 is : 9

9) Explain Queue ADT. Write a Java program to implement Queue.


a. Queue implementation
class Queue
{
int SIZE = 5;
int items[] = new int[SIZE];
int front, rear;
Queue()
{
front = -1;
rear = -1;
}
boolean isFull()
{ if (front == 0 && rear == SIZE - 1) {
return true; }
return false;
}
boolean isEmpty()
{
if (front == -1)
return true;
else
return false;
}
void enQueue(int element)
{
if (isFull())
{
System.out.println("Queue is full");
}
else
{
if (front == -1)
{
front = 0;
}
rear++;
items[rear] = element;
System.out.println("Insert " + element);
}
}
int deQueue()
{
int element;
if (isEmpty())
{
System.out.println("Queue is empty");
return (-1);
}
else
{
element = items[front];
if (front >= rear)
{
front = -1;
rear = -1;
}
else
{
front++;
}
System.out.println( element + " Deleted");
return (element);
}
}
void display()
{
int i;
if (isEmpty())
{
System.out.println("Empty Queue");
}
else
{
System.out.println("\nFront index-> " + front);
System.out.println("Items -> ");
for (i = front; i <= rear; i++)
System.out.print(items[i] + " ");
System.out.println("\nRear index-> " + rear);
}
}
}
public class Main
{
public static void main(String[] args)
{
Queue q = new Queue();
q.deQueue();
for(int i = 1; i < 6; i ++)
{
q.enQueue(i);
}
q.enQueue(6);
q.display();
q.deQueue();
q.display();
}
}

You might also like