22cs3251 Oops Using Java
22cs3251 Oops Using Java
DATA DATA
Communication
FUNCTION FUNCTION
Object C
DATA
FUNCTION
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)
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.
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.
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.
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.
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.
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
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.
Output:
Welcome to Java World
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)
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.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.
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.
== Equal to x == y
!= Not equal x != y
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.
&& Logical and Returns true if both statements are true x < 5 && x < 10
! 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
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
equals() Compares two strings. Returns true if the strings are equal, and
false if not
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
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.
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.
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.
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.
Example
import java.util.*;
{
public static void main(String args[])
while (st1.hasMoreTokens())
System.out.println(st1.nextToken());
while (st2.hasMoreTokens())
System.out.println(st2.nextToken());
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
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
Searches for the specified element in the array with the help of the
binarySearch()
Binary Search Algorithm
fill(originalArray,
Assigns this fill value to each index of this arrays.
fillValue)
Finds and returns the index of the first unmatched element between
mismatch(array1, array2)
the two specified arrays.
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.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
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.
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");
}
}
class Main
{
public static void main(String args[])
{
Example obj=new Example()
{
void display(){System.out.println("Java anonymous inner class");
}
};
obj.display();
}
}
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();
}
}
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
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 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
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.
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
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
Static binding is being used for Dynamic binding is being used for overriding
overloaded methods. methods.
Method Overloading Method Overriding
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
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();
}
}
Class Interface
In class, you can instantiate variables In an interface, you can’t instantiate variables
and create an object. and create an object.
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
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
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.
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
Method Meaning
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...
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...
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 + " ");
}
}
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.
}
}
Output:
5
10
15
20
25
100
200
300
400
500
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...");
}
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.
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:
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.
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
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> ();
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:
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.
package com.myPack;
import java.util.ArrayList;
import java.util.Iterator;
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.
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]
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
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.
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.
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.
The location of array elements is the Location of linked list nodes is not
continuous continuous.
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
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
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.
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.
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.
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
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.
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.
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.
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.
equals() Compares two strings. Returns true if the strings are equal,
and false if not
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
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
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));
}
}
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
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
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 + " ");
}
}
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