0% found this document useful (0 votes)
40 views134 pages

Oops Full Notes-R20

Uploaded by

mhys2827
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views134 pages

Oops Full Notes-R20

Uploaded by

mhys2827
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 134

20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

UNIT-1
The Java Language
The Java Language: Importance of Java -Programming Paradigms -The History and Evolution of
Java -Java Byte Code. Introduction of OOP: Abstraction, Encapsulation, Inheritance,
Polymorphism-Understanding static –Var args -Data Types -Type Casting -Java Tokens - Java
Statements -Arrays.

The Java Language -Importance of Java


Java is one of the most popular programming languages used to create Web applications and
platforms. It was designed for flexibility, allowing developers to write code that would run on
any machine, regardless of architecture or platform. According to the Java home page, more than
3 billion computers and 4 billion mobile phones worldwide run Java.
 Programming: Based on a C and C++ based syntax, Java is object-oriented and class-
based. Developers adopt and use Java because code can be run securely on nearly any other
platform, regardless of the operating system or architecture of the device, as long as the device
has a Java Runtime Environment (JRE) installed. The JRE varies depending on the specific type
of device, but essentially, it runs a ―virtual‖ machine, or environment, that translates the code
into an application or program.
 Java and JavaScript: Although their names are quite similar and they are both used to
create dynamic tools and games on a Web page, Java and JavaScript are different languages.
Java is more robust and can be used as the sole programming language for an application, while
JavaScript is a lightweight scripting language that adds functionality like a Java applet onto a
Web page.
 Use: Java is used to build applications and platforms for a number of devices, including
computers, laptops, gaming consoles, Blu-ray players, car navigation systems, medical
monitoring devices, parking meters, lottery terminals and smart phones. It is also a key language
for networking, particularly for data centers that store and transfer Web-based data.
 Applets: Java is also used to create miniature, dynamic programs that run alongside or
are embedded within Web pages. These programs are called applets and can be used to display
maps, weather, games or other interactive widgets or tools on a Web page.

Programming Paradigms
Paradigm can also be termed as method to solve some problem or do some task.
Programming paradigm is an approach to solve problem using some programming language or
also we can say it is a method to solve a problem using tools and techniques that are available
to us. There are lots for programming language that are known but all of them need to follow
some strategy when they are implemented and this methodology/strategy is paradigms. Apart
from varieties of programming language there are lots of paradigms to fulfill each and every
demand. They are discussed below:

Department of CSE / Siddharth Group of Institutions, Puttur 1


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

1. Imperative programming paradigm:


It is one of the oldest programming paradigms. It features close relation to machine
architecture. It is based on Von Neumann architecture. It works by changing the program state
through assignment statements. It performs step by step task by changing state. The main focus
is on how to achieve the goal. The paradigm consists of several statements and after execution
of all the result is stored.
Advantage:
1. Very simple to implement
2. It contains loops, variables etc.
Disadvantage:
1. Complex problem cannot be solved
2. Less efficient and less productive
3. Parallel programming is not possible

i. Procedural programming paradigm – This paradigm emphasizes on procedure in terms of


under lying machine model. There is no difference in between procedural and imperative
approach. It has the ability to reuse the code and it was boon at that time when it was in use
because of its reusability.

Examples of Procedural programming paradigm:

C : developed by Dennis Ritchie and Ken Thompson


C++ : developed by Bjarne Stroustrup
Java : developed by James Gosling at Sun Microsystems
ColdFusion : developed by J J Allaire
Pascal : developed by Niklaus Wirth

ii. Object oriented programming – The program is written as a collection of classes and
object which are meant for communication. The smallest and basic entity is object and all kind
of computation is performed on the objects only. More emphasis is on data rather procedure. It
can handle almost all kind of real life problems which are today in scenario.
1. Encapsulation
2. Polymorphism
3. Inheritance
4. Abstraction
Advantages:
 Data security
 Inheritance
 Code reusability
 Flexible and abstraction is also present
Examples of Object Oriented programming paradigm:
Simula : first OOP language
Java : developed by James Gosling at Sun Microsystems
C++ : developed by Bjarne Stroustrup
Objective-C : designed by Brad Cox
Visual Basic .NET : developed by Microsoft
Python : developed by Guido van Rossum
Department of CSE / Siddharth Group of Institutions, Puttur 2
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

Ruby : developed by Yukihiro Matsumoto


Smalltalk : developed by Alan Kay, Dan Ingalls, Adele Goldberg

iii. Parallel processing approach – Parallel processing is the processing of program


instructions by dividing them among multiple processors. A parallel processing system posses
many numbers of processor with the objective of running a program in less time by dividing
them. This approach seems to be like divide and conquer. Examples are NESL (one of the
oldest one) and C/C++ also supports because of some library function.

2. Declarative programming paradigm: It is divided as Logic, Functional, Database. In


computer science the declarative programming is a style of building programs that expresses
logic of computation without talking about its control flow. It often considers programs as
theories of some logic. It may simplify writing parallel programs. The focus is on what needs
to be done rather how it should be done basically emphasize on what code is actually doing. It
just declares the result we want rather how it has be produced. This is the only difference
between imperative (how to do) and declarative (what to do) programming paradigms.
Getting into deeper we would see logic, functional and database.

I. Logic programming paradigms – It can be termed as abstract model of computation. It


would solve logical problems like puzzles, series etc. In logic programming we have a
knowledge base which we know before and along with the question and knowledge base
which is given to machine, it produces result. In normal programming languages, such concept
of knowledge base is not available but while using the concept of artificial intelligence,
machine learning we have some models like Perception model which is using the same
mechanism.
In logical programming the main emphasize is on knowledge base and the problem. The
execution of the program is very much like proof of mathematical statement, e.g., Prolog

II. Functional programming paradigms – The functional programming paradigm has its roots
in mathematics and it is language independent. The key principal of this paradigms is the
execution of series of mathematical functions. The central model for the abstraction is the
function which are meant for some specific computation and not the data structure. Data are
loosely coupled to functions.The function hide their implementation. Function can be replaced
with their values without changing the meaning of the program. Some of the languages like
perl, javascript mostly uses this paradigm.
Examples of Functional programming paradigm:

I. JavaScript : developed by Brendan Eich


II. Haskwell : developed by Lennart Augustsson, Dave Barton
III. Scala : developed by Martin Odersky
IV. Erlang : developed by Joe Armstrong, Robert Virding
V. Lisp : developed by John Mccarthy
VI. ML : developed by Robin Milner
VII. Clojure : developed by Rich Hickey

Department of CSE / Siddharth Group of Institutions, Puttur 3


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

HISTORY AND EVOLUTION OF JAVA


The history of Java is very interesting. Java was originally designed for interactive television,
but it was too advanced technology for the digital cable television industry at the time. The
history of Java starts with the Green Team. Java team members (also known as Green Team),
initiated this project to develop a language for digital devices such as set-top boxes, televisions,
etc. However, it was suited for internet programming. Later, Java technology was incorporated
by Netscape.
The principles for creating Java programming were "Simple, Robust, Portable, Platform
independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object Oriented,
Interpreted, and Dynamic". Java was developed by James Gosling, who is known as the father of
Java, in 1995. James Gosling and his team members started the project in the early '90s.

Currently, Java is used in internet programming, mobile devices, games, e-business solutions,
etc. There are given significant points that describe the history of Java.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project
in June 1991. The small team of sun engineers called Green Team.
2) Initially designed for small, embedded systems in electronic appliances like set-top boxes.
3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
Why Java named "Oak"?
5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like
the U.S.A., France, Germany, Romania, etc.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.

7) Why had they chosen java name for Java language? The team gathered to choose a new
name. The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA", etc. They

Department of CSE / Siddharth Group of Institutions, Puttur 4


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

wanted something that reflected the essence of the technology: revolutionary, dynamic, lively,
cool, unique, and easy to spell and fun to say.
According to James Gosling, "Java was one of the top choices along with Silk". Since Java was
so unique, most of the team members preferred Java than other names.
8) Java is an island of Indonesia where the first coffee was produced (called java coffee). It is a
kind of espresso bean. Java name was chosen by James Gosling while having coffee near his
office.
9) Notice that Java is just a name, not an acronym.
10) Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary of
Oracle Corporation) and released in 1995.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
12) JDK 1.0 released in(January 23, 1996). After the first release of Java, there have been many
additional features added to the language. Now Java is being used in Windows applications,
Web applications, enterprise applications, mobile applications, cards, etc. Each new version adds
the new features in Java.

Java Version History


Many java versions have been released till now. The current stable release of Java is Java SE 10.
1. JDK Alpha and Beta (1995)
2. JDK 1.0 (23rd Jan 1996)
3. JDK 1.1 (19th Feb 1997)
4. J2SE 1.2 (8th Dec 1998)
5. J2SE 1.3 (8th May 2000)
6. J2SE 1.4 (6th Feb 2002)
7. J2SE 5.0 (30th Sep 2004)
8. Java SE 6 (11th Dec 2006)
9. Java SE 7 (28th July 2011)
10. Java SE 8 (18th Mar 2014)
11. Java SE 9 (21st Sep 2017)
12. Java SE 10 (20th Mar 2018)
13. Java SE 11
14. Java SE 12
15. Java SE 13

JAVA BYTE CODE


Java bytecode is the instruction set for the Java Virtual Machine. As soon as a java program is
compiled, java bytecode is generated. In more apt terms, java bytecode is the machine code in
the form of a .class file. With the help of java bytecode we achieve platform independence in
java.

Department of CSE / Siddharth Group of Institutions, Puttur 5


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

When we write a program in Java, firstly, the compiler compiles that program and a bytecode is
generated for that piece of code. When we wish to run this .class file on any other platform, we
can do so. After the first compilation, the bytecode generated is now run by the Java Virtual
Machine and not the processor in consideration. This essentially means that we only need to
have basic java installation on any platforms that we want to run our code on. Resources
required to run the bytecode are made available by the Java Virtual Machine, which calls the
processor to allocate the required resources. JVM's are stack-based so they stack implementation
to read the codes.

THE JAVA BUZZWORDS


The Java programming language is a high-level language that can be characterized by all of the
following buzzwords:

 Simple
 Object oriented
 Distributed
 Interpreted
 Robust
 Secure
 Architecture neutral
 Portable
 High performance
 Multithreaded
 Dynamic
Simple
 Java was designed to be easy for professional programmer to learn and use effectively.
 It‘s simple and easy to learn if you already know the basic concepts of Object Oriented
Programming.
 C++ programmer can move to JAVA with very little effort to learn.
 In Java, there is small number of clearly defined ways to accomplish a given task.
Object Oriented
 Java is true object oriented language.

Department of CSE / Siddharth Group of Institutions, Puttur 6


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

 Almost ―Everything is an Object‖ paradigm. All program code and data reside within
objects and classes.
 The object model in Java is simple and easy to extend.
 Java comes with an extensive set of classes, arranged in packages that can be used in our
programs through inheritance.
Distributed
 Java is designed for distributed environment of the Internet. Its used for creating
applications on networks.
 Java applications can access remote objects on Internet as easily as they can do in local
system.
 Java enables multiple programmers at multiple remote locations to collaborate and
work together on a single project.
Compiled and Interpreted
 Usually a computer language is either compiled or Interpreted. Java combines both this
approach and makes it a two-stage system.
 Compiled: Java enables creation of a cross platform programs by compiling into an
intermediate representation called Java Bytecode.
 Interpreted: Bytecode is then interpreted, which generates machine code that can be
directly executed by the machine that provides a Java Virtual machine.
Robust
 It provides many features that make the program execute reliably in variety of
environments.
 Java is a strictly typed language. It checks code both at compile time and runtime.
 Java takes care of all memory management problems with garbage-collection.
 Java, with the help of exception handling captures all types of serious errors and
eliminates any risk of crashing the system.
Secure
 Java provides a ―firewall‖ between a networked application and your computer.
 When a Java Compatible Web browser is used, downloading can be done safely 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 to access other parts of the computer.
Architecture Neutral
 Java language and Java Virtual Machine helped in achieving the goal of ―write once; run
anywhere, any time, forever.‖
 Changes and upgrades in operating systems, processors and system resources will not
force any changes in Java Programs.
Portable
 Java Provides a way to download programs dynamically to all the various types of
platforms connected to the Internet.
 It helps in generating Portable executable code.
High Performance
 Java performance is high because of the use of bytecode.
 The bytecode was used, so that it was easily translated into native machine code.
Multithreaded
 Multithreaded Programs handled multiple tasks simultaneously, which was helpful in
creating interactive, networked programs.
Department of CSE / Siddharth Group of Institutions, Puttur 7
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

 Java run-time system comes with tools that support multiprocess synchronization used to
construct smoothly interactive systems.
Dynamic
 Java is capable of linking in new class libraries, methods, and objects.
 It can also link native methods (the functions written in other languages such as C and
C++).

INTRODUCTION OF OOP-ABSTRACTION
Abstraction is the concept of object-oriented programming that "shows" only essential
attributes and "hides" unnecessary information. The main purpose of abstraction is hiding the
unnecessary details from the users. Abstraction is selecting data from a larger pool to show only
relevant details of the object to the user. It helps in reducing programming complexity and
efforts. It is one of the most important concepts of OOPs.
For example, when you login to your Amazon account online, you enter your user_id and
password and press login, what happens when you press login, how the input data sent to
amazon server, how it gets verified is all abstracted away from the you.
Another example of abstraction: A car in itself is a well-defined object, which is composed of
several other smaller objects like a gearing system, steering mechanism, engine, which are again
have their own subsystems. But for humans car is a one single object, which can be managed by
the help of its subsystems, even if their inner details are unknown.

ENCAPSULATION
The process of binding data and corresponding methods (behavior) together into a single unit is
called encapsulation in Java.
In other words, encapsulation is a programming technique that binds the class members
(variables and methods) together and prevents them from being accessed by other classes,
thereby we can keep variables and methods safes from outside interference and misuse.
Every Java class is an example of encapsulation because we write everything within the class
only that binds variables and methods together and hides their complexity from other classes.
Another example of encapsulation is a capsule. Basically, capsule encapsulates several
combinations of medicine.
If combinations of medicine are variables and methods then the capsule will act as a class and
the whole process is called Encapsulation as shown in the below figure.

Department of CSE / Siddharth Group of Institutions, Puttur 8


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

In the encapsulation technique, we declare fields as private in the class to prevent other classes
from accessing them directly. The required encapsulated data can be accessed by using public
Java getter and setter method.
If the field is declared private in the class then it cannot be accessed by anyone from outside the
class and hides the field within the class. Therefore, it is also called data hiding.

Realtime Example
1: School bag is one of the most real examples of Encapsulation. School bag can keep our
books, pens, etc.
2: When you log into your email accounts such as Gmail, Yahoo Mail, or Rediff mail, there is a
lot of internal processes taking place in the backend and you have no control over it.
When you enter the password for logging, they are retrieved in an encrypted form and verified,
and then you are given access to your account.
You do not have control over it that how the password has been verified. Thus, it keeps our
account safe from being misused.

INHERITANCE
 Inheritance is the mechanism by which an object acquires the some/all properties of another
object.
 It supports the concept of hierarchical classification.
For example: Car is a four wheeler vehicle so assume that we have a class FourWheeler and a
sub class of it named Car. Here Car acquires the properties of a class FourWheeler. Other
classifications could be a jeep, tempo, van etc. FourWheeler defines a class of vehicles that have
four wheels, and specific range of engine power, load carrying capacity etc. Car (termed as a
sub-class) acquires these properties from FourWheeler, and has some specific properties, which
are different from other classifications of FourWheeler, such as luxury, comfort, shape, size,
usage etc.
A car can have further classification such as an open car, small car, big car etc, which will
acquire the properties from both Four Wheeler and Car, but will still have some specific
properties. This way the level of hierarchy can be extended to any level.

Department of CSE / Siddharth Group of Institutions, Puttur 9


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

POLYMORPHISM

Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many
and "morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in Java: compile-time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method
overriding.
If you overload a static method in Java, it is the example of compile time polymorphism. Here,
we will focus on runtime polymorphism in java.

Runtime Polymorphism in Java


Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an
overridden method is resolved at runtime rather than compile-time.
In this process, an overridden method is called through the reference variable of a superclass.
The determination of the method to be called is based on the object being referred to by the
reference variable.
Let's first understand the upcasting before Runtime Polymorphism.
If the reference variable of Parent class refers to the object of Child class, it is known as
upcasting. For example:

Department of CSE / Siddharth Group of Institutions, Puttur 10


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

Variable
Variable is a name of memory location. There are three types of variables in java:
 local variable
 instance variable
 static variable
1)Local Variable
A variable which is declared inside the method is called local variable.
2) Instance Variable
A variable which is declared inside the class but outside the method, is called instance variable .
It is not declared as static.
3) Static variable
A variable that is declared as static is called static variable. It cannot be local.

Example to understand the types of variables in java

class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
}
}//end of class

VARARGS
In JDK 5, Java has included a feature that simplifies the creation of methods that need to take a
variable number of arguments. This feature is called varargs and it is short-form for variable-
length arguments. A method that takes a variable number of arguments is a varargs method.
Prior to JDK 5, variable-length arguments could be handled two ways. One using overloaded
method(one for each) and another put the arguments into an array, and then pass this array to
the method. Both of them are potentially error-prone and require more code. The varargs
feature offers a simpler, better option.
Syntax of varargs :
A variable-length argument is specified by three periods(…). For Example,
public static void fun(int ... a)
{
// method body
}
This syntax tells the compiler that fun( ) can be called with zero or more arguments. As a
result, here ‗a‘ is implicitly declared as an array of type int[]. Below is a code snippet for
illustrating the above concept :
// Java program to demonstrate varargs
Department of CSE / Siddharth Group of Institutions, Puttur 11
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

class Test1
{
// A method that takes variable number of integer
// arguments.
static void fun(int ...a)
{
System.out.println("Number of arguments: " + a.length);

// using for each loop to display contents of a


for (int i: a)
System.out.print(i + " ");
System.out.println();
}

// Driver code
public static void main(String… a)
{
// Calling the varargs method with different number
// of parameters
fun(100); // one parameter
fun(1, 2, 3, 4); // four parameters
fun(); // no parameter
}
}

o/p:
Number of arguments: 1
100
Number of arguments: 4
1234
Number of arguments: 0

DATA TYPES
Data types specify the different sizes and values that can be stored in the variable. There are two
types of data types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.
Java Primitive Data Types
In Java language, primitive data types are the building blocks of data manipulation. These are
the most basic data types available in Java language.
There are 8 types of primitive data types:
o boolean data type
o byte data type
o char data type
o short data type

Department of CSE / Siddharth Group of Institutions, Puttur 12


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

o int data type


o long data type
o float data type
o double data type

Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

Boolean Data Type


The Boolean data type is used to store only two possible values: true and false. This data type is
used for simple flags that track true/false conditions.
The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.
Example: Boolean one = false
Byte Data Type
The byte data type is an example of primitive data type. It is an 8-bit signed two's complement
integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and
maximum value is 127. Its default value is 0.
The byte data type is used to save memory in large arrays where the memory savings is most
required. It saves space because a byte is 4 times smaller than an integer. It can also be used in
place of "int" data type.
Example: byte a = 10, byte b = -20

Department of CSE / Siddharth Group of Institutions, Puttur 13


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

Short Data Type


The short data type is a 16-bit signed two's complement integer. Its value-range lies between -
32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its
default value is 0.
The short data type can also be used to save memory just like byte data type. A short data type is
2 times smaller than an integer.
Example: short s = 10000, short r = -5000
Int Data Type
The int data type is a 32-bit signed two's complement integer. Its value-range lies between
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is
2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values unless if there is no
problem about memory.
Example: int a = 100000, int b = -200000

Long Data Type


The long data type is a 64-bit two's complement integer. Its value-range lies between a
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its
minimum value is -9,223,372,036,854,775,808 and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you need a
range of values more than those provided by int.
Example: long a = 100000L, long b = -200000L
Float Data Type
The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is
unlimited. It is recommended to use a float (instead of double) if you need to save memory in
large arrays of floating point numbers. The float data type should never be used for precise
values, such as currency. Its default value is 0.0F.
Example: float f1 = 234.5f
Double Data Type
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is
unlimited. The double data type is generally used for decimal values just like float. The double
data type also should never be used for precise values, such as currency. Its default value is 0.0d.
Example: double d1 = 12.3
Char Data Type
The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or
0) to '\uffff' (or 65,535 inclusive).The char data type is used to store characters.
Example: char letterA = 'A'

TYPE CASTING
In Java, type casting is a method or process that converts a data type into another data type in
both ways manually and automatically. The automatic conversion is done by the compiler and
manual conversion performed by the programmer. In this section, we will discuss type
casting and its types with proper examples.

Department of CSE / Siddharth Group of Institutions, Puttur 14


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

Types of Type Casting


There are two types of type casting:
o Widening Type Casting
o Narrowing Type Casting
Widening Type Casting
Converting a lower data type into a higher one is called widening type casting. It is also known
as implicit conversion or casting down. It is done automatically. It is safe because there is no
chance to lose data. It takes place when:
o Both data types must be compatible with each other.
o The target type must be larger than the source type.
1. byte -> short -> char -> int -> long -> float -> double
For example, the conversion between numeric data type to char or Boolean is not done
automatically. Also, the char and Boolean data types are not compatible with each other. Let's
see an example.

WideningTypeCastingExample.java
public class WideningTypeCastingExample
{
public static void main(String[] args)
{
int x = 7;
//automatically converts the integer type into long type
long y = x;
//automatically converts the long type into float type
float z = y;
System.out.println("Before conversion, int value "+x);
System.out.println("After conversion, long value "+y);
System.out.println("After conversion, float value "+z);
}
}
Output

Before conversion, the value is: 7


After conversion, the long value is: 7
After conversion, the float value is: 7.0

Department of CSE / Siddharth Group of Institutions, Puttur 15


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

Narrowing Type Casting


Converting a higher data type into a lower one is called narrowing type casting. It is also known
as explicit conversion or casting up. It is done manually by the programmer. If we do not
perform casting then the compiler reports a compile-time error.
1. double -> float -> long -> int -> char -> short -> byte
Let's see an example of narrowing type casting.
In the following example, we have performed the narrowing type casting two times. First, we
have converted the double type into long data type after that long data type is converted into int
type.
NarrowingTypeCastingExample.java
public class NarrowingTypeCastingExample
{
public static void main(String args[])
{
double d = 166.66;
//converting double data type into long data type
long l = (long)d;
//converting long data type into int data type
int i = (int)l;
System.out.println("Before conversion: "+d);
//fractional part lost
System.out.println("After conversion into long type: "+l);
//fractional part lost
System.out.println("After conversion into int type: "+i);
}
}
Output:
Before conversion: 166.66
After conversion into long type: 166
After conversion into int type: 166

JAVA TOKENS
The program contains classes and methods. Further, the methods contain the expressions and
statements required to perform a specific operation. These statements and expressions are made
up of tokens. In other words, we can say that the expression and statement is a set of tokens.
The tokens are the small building blocks of a Java program that are meaningful to
the Java compiler. Further, these two components contain variables, constants, and operators. In
this section, we will discuss what is tokens in Java.
What is token in Java?
The Java compiler breaks the line of code into text (words) is called Java tokens. These are the
smallest element of the Java program. The Java compiler identified these words as tokens. These
tokens are separated by the delimiters. It is useful for compilers to detect errors. Remember that
the delimiters are not part of the Java tokens.

Department of CSE / Siddharth Group of Institutions, Puttur 16


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

Keywords: These are the pre-defined reserved words of any programming language.
Each keyword has a special meaning. It is always written in lower case. Java provides the
following keywords:

01. abstract 02. boolean 03. byte 04. break 05. class

06. case 07. catch 08. char 09. continue 10. default

11. do 12. double 13. else 14. extends 15. final

16. finally 17. float 18. for 19. if 20. implements

21. import 22. instanceof 23. int 24. interface 25. long

26. native 27. new 28. package 29. private 30. protected

31. public 32. return 33. short 34. static 35. super

36. switch 37. synchronized 38. this 39. thro 40. throws

41. transient 42. try 43. void 44. volatile 45. while

46. assert 47. const 48. enum 49. goto 50. strictfp
Identifier: Identifiers are used to name a variable, constant, function, class, and array. It usually
defined by the user. It uses letters, underscores, or a dollar sign as the first character. The label is
also known as a special kind of identifier that is used in the goto statement. Remember that the
identifier name must be different from the reserved keywords. There are some rules to declare
identifiers are:
o The first letter of an identifier must be a letter, underscore or a dollar sign. It cannot start
with digits but may contain digits.
o The whitespace cannot be included in the identifier.
o Identifiers are case sensitive.
Some valid identifiers are:
1. PhoneNumber
2. PRICE
3. radius
4. a

Department of CSE / Siddharth Group of Institutions, Puttur 17


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

5. a1
6. _phonenumber
7. $circumference
8. jagged_array
9. 12radius //invalid
Literals: In programming literal is a notation that represents a fixed value (constant) in the
source code. It can be categorized as an integer literal, string literal, Boolean literal, etc. It is
defined by the programmer. Once it has been defined cannot be changed. Java provides five
types of literals are as follows:
o Integer
o Floating Point
o Character
o String
o Boolean

Literal Type

23 int

9.86 double

false, true boolean

'K', '7', '-' char

"javatpoint" String

null any reference type


Operators: In programming, operators are the special symbol that tells the compiler to perform
a special operation. Java provides different types of operators that can be classified according to
the functionality they provide. There are eight types of operators in Java, are as follows:
o Arithmetic Operators
o Assignment Operators
o Relational Operators
o Unary Operators
o Logical Operators
o Ternary Operators
o Bitwise Operators
o Shift Operators

Operator Symbols

Arithmetic +,-,/,*,%

Unary ++ , - - , !

Assignment = , += , -= , *= , /= , %= , ^=

Relational ==, != , < , >, <= , >=

Department of CSE / Siddharth Group of Institutions, Puttur 18


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

Logical && , ||

Ternary (Condition) ? (Statement1) : (Statement2);

Bitwise &,|,^,~

Shift << , >> , >>>


Separators: The separators in Java is also known as punctuators. There are nine separators in
Java, are as follows:
1. separator <= ; | , | . | ( | ) | { | } | [ | ]
o Square Brackets []: It is used to define array elements. A pair of square brackets represents
the single-dimensional array, two pairs of square brackets represent the two-dimensional array.
o Parentheses (): It is used to call the functions and parsing the parameters.
o Curly Braces {}: The curly braces denote the starting and ending of a code block.
o Comma (,): It is used to separate two values, statements, and parameters.
o Assignment Operator (=): It is used to assign a variable and constant.
o Semicolon (;): It is the symbol that can be found at end of the statements. It separates the two
statements.
o Period (.): It separates the package name form the sub-packages and class. It also separates a
variable or method from a reference variable.
Comments: Comments allow us to specify information about the program inside our Java code.
Java compiler recognizes these comments as tokens but excludes it form further processing. The
Java compiler treats comments as whitespaces. Java provides the following two types of
comments:
o Line Oriented: It begins with a pair of forwarding slashes (//).
o Block-Oriented: It begins with /* and continues until it founds */.
JAVA STATEMENTS
A programming language uses control statements to control the flow of execution of program
based on certain conditions. These are used to cause the flow of execution to advance and
branch based on changes to the state of a program.
Java statements can be classified as
1. Selection
2. Iteration
3. Jump control statements
 Decision Making Statements
 Simple if statement
 if-else statement
 Nested if statement
 Switch statement
4. Looping statements
 While
 Do-while
 For
 For-Each
5. Branching statements
 Break
 Continue

Department of CSE / Siddharth Group of Institutions, Puttur 19


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

Every programmer is familiar with the term statement, which can simply be defined as an
instruction given to the computer to perform specific operations. A control statement in java is a
statement that determines whether the other statements will be executed or not. It controls the
flow of a program. An ‗if‘ statement in java determines the sequence of execution between a set
of two statements.

Decision-Making Statements
Statements that determine which statement to execute and when are known as decision-making
statements. The flow of the execution of the program is controlled by the control flow statement.
There are four decision-making statements available in java.

Simple if statement
The if statement determines whether a code should be executed based on the specified condition.
Syntax:

if (condition) {
Statement 1; //executed if condition is true
}
Statement 2; //executed irrespective of the condition

If..else statement
In this statement, if the condition specified is true, the if block is executed. Otherwise, the else
block is executed.

if (condition1)
{
Statement 1; //executed if second condition is true
}
else
{
Statement 2; //executed if second condition is false
}

Example:
public class Main
{
public static void main(String args[])
{

Department of CSE / Siddharth Group of Institutions, Puttur 20


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

int a = 15;
if (a > 20)
System.out.println("a is greater than 10");
else
System.out.println("a is less than 10");
System.out.println("Hello World!");
}
}
}
Output:
a is less than 10
Hello World!

Nested if statement
An if present inside an if block is known as a nested if block. It is similar to an if..else statement,
except they are defined inside another if..else statement.

Syntax:
if (condition1) {
Statement 1; //executed if first condition is true
if (condition2) {
Statement 2; //executed if second condition is true
}
else {
Statement 3; //executed if second condition is false
}
}

Department of CSE / Siddharth Group of Institutions, Puttur 21


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

Example:
public class Main
{
public static void main(String args[])
{
int s = 18;
if (s > 10)
{
if (s%2==0)
System.out.println("s is an even number and greater than 10!");
else
System.out.println("s is a odd number and greater than 10!");
}
else
{
System.out.println("s is less than 10");
}
System.out.println("Hello World!");
}
}
Output:
s is an even number and greater than 10!
Hello World!

Department of CSE / Siddharth Group of Institutions, Puttur 22


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

Switch statement
 A switch statement in java is used to execute a single statement from multiple conditions. The
switch statement can be used with short, byte, int, long, enum types, etc.
 One or N number of case values can be specified for a switch expression.
 Case values that are duplicate are not permissible. A compile-time error is generated by the
compiler if unique values are not used.
 The case value must be literal or constant. Variables are not permissible.
 Usage of break statement is made to terminate the statement sequence. It is optional to use
this statement. If this statement is not specified, the next case is executed.
syntax:
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......

default:
code to be executed if all cases are not matched;
}

Example:
public class Music {
public static void main(String[] args)
{

Department of CSE / Siddharth Group of Institutions, Puttur 23


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

int instrument = 4;
String musicInstrument;
// switch statement with int data type
switch (instrument) {
case 1:
musicInstrument = "Guitar";
break;
case 2:
musicInstrument = "Piano";
break;
case 3:
musicInstrument = "Drums";
break;
case 4:
musicInstrument = "Flute";
break;
case 5:
musicInstrument = "Ukelele";
break;
case 6:
musicInstrument = "Violin";
break;
case 7:
musicInstrument = "Trumpet";
break;
default:
musicInstrument = "Invalid";
break;
}
System.out.println(musicInstrument);
}
}
Output:
Flute

Looping Statements
Statements that execute a block of code repeatedly until a specified condition is met are known
as looping statements. Java provides the user with three types of loops:
while
Known as the most common loop, the while loop evaluates a certain condition. If the condition
is true, the code is executed. This process is continued until the specified condition turns out to
be false.
The condition to be specified in the while loop must be a Boolean expression. An error will be
generated if the type used is int or a string.
Syntax:
while (condition)
{
Department of CSE / Siddharth Group of Institutions, Puttur 24
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

statementOne;
}
Example:
public class whileTest
{
public static void main(String args[])
{
int i = 5;
while (i <= 15)
{
System.out.println(i);
i = i+2;
}
}
}
Output:
5
7
9
11
13
15

Do..while
The do-while loop is similar to the while loop, the only difference being that the condition in the
do-while loop is evaluated after the execution of the loop body. This guarantees that the loop is
executed at least once.
Syntax:
do{
//code to be executed
}while(condition);
Example:
public class Main
{
public static void main(String args[])
{
int i = 20;
do
{
System.out.println(i);
i = i+1;
} while (i <= 20);
}
}

Output:
20
Department of CSE / Siddharth Group of Institutions, Puttur 25
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

For
The for loop in java is used to iterate and evaluate a code multiple times. When the number of
iterations is known by the user, it is recommended to use the for loop.
Syntax:
for (initialization; condition; increment/decrement)
{
statement;
}

Example:
public class forLoop
{
public static void main(String args[])
{
for (int i = 1; i <= 10; i++)
System.out.println(i);
}
}
Output:
5
6
7
8
9
10

For-Each
The traversal of elements in an array can be done by the for-each loop. The elements present in
the array are returned one by one. It must be noted that the user does not have to increment the
value in the for-each loop.
Department of CSE / Siddharth Group of Institutions, Puttur 26
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

Example:
public class foreachLoop{
public static void main(String args[]){
int s[] = {18,25,28,29,30};
for (int i : s) {
System.out.println(i);
}
}
}
Output:
18
25
28
29
30
Branching Statements
Branching statements in java are used to jump from a statement to another statement, thereby the
transferring the flow of execution.
Break
The break statement in java is used to terminate a loop and break the current flow of the
program.

Example:
public class Test
{
public static void main(String args[])
{
for (int i = 5; i < 10; i++)
{
if (i == 8)
break;
System.out.println(i);
}
}
}
Output:
5
6
7
Continue:
To jump to the next iteration of the loop, we make use of the continue statement. This statement
continues the current flow of the program and skips a part of the code at the specified condition.
Example:
public class Main
{
public static void main(String args[])
{
Department of CSE / Siddharth Group of Institutions, Puttur 27
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

for (int k = 5; k < 15; k++)


{
// Odd numbers are skipped
if (k%2 != 0)
continue;
// Even numbers are printed
System.out.print(k + " ");
}
}
}
Output:
6 8 10 12 14

ARRAYS
An array is a group of like-typed variables that are referred to by a common name. Arrays of any
type can be created and may have one or more dimensions. A specific element in an array is
accessed by its index. Arrays offer a convenient means of grouping related information
One-Dimensional Arrays A one-dimensional array is, essentially, a list of like-typed variables.
To create an array, you first must create an array variable of the desired type. The general form
of a one-dimensional array declaration is
type var-name[ ];
Here, type declares the element type (also called the base type) of the array. The element type
determines the data type of each element that comprises the array. Thus, the element type for the
array determines what type of data the array will hold. For example, the following declares an
array named month_days with the type ―array of int‖:
int month_days[];
Although this declaration establishes the fact that month_days is an array variable, no array
actually exists. In fact, the value of month_days is set to null, which represents an array with no
value. To link month_days with an actual, physical array of integers, you must allocate one using
new and assign it to month_days. new is a special operator that allocates memory. The general
form of new as it applies to one-dimensional arrays appears as follows:
array-var = new type [size];
 Since arrays are objects in Java, we can find their length using the object property length.
This is different from C/C++ where we find length using sizeof.
 A Java array variable can also be declared like other variables with [] after the data type.
 The variables in the array are ordered and each have an index beginning from 0.
 Java array can be also be used as a static field, a local variable or a method parameter.
 The size of an array must be specified by an int or short value and not long.
 The direct superclass of an array type is Object
Arrays can have
1. One dimensional 2. Multi dimensional
One-Dimensional Arrays :
The general form of a one-dimensional array declaration is

type var-name[];
OR

Department of CSE / Siddharth Group of Institutions, Puttur 28


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

type[] var-name;

An array declaration has two components: the type and the name. type declares the element type
of the array. The element type determines the data type of each element that comprises the array.
Like an array of integers, we can also create an array of other primitive data types like char,
float, double, etc. or user-defined data types (objects of a class). Thus, the element type for the
array determines what type of data the array will hold.

int intArray[];
or int[] intArray;
How to Initialize Arrays in Java?

In Java, we can initialize arrays during declaration. For example,

//declare and initialize and array


int[] age = {12, 4, 5, 2, 5};
Here, we have created an array named age and initialized it with the values inside the curly
brackets.
Note that we have not provided the size of the array. In this case, the Java compiler
automatically specifies the size by counting the number of elements in the array (i.e. 5).
In the Java array, each memory location is associated with a number. The number is known as an
array index. We can also initialize arrays in Java, using the index number. For example,

// declare an array
int[] age = new int[5];

// initialize array
age[0] = 12;
age[1] = 4;
age[2] = 5;
..

// Java program to illustrate creating an array


// of integers, puts some values in the array,
// and prints each value to standard output.

class OneD
{
public static void main (String[] args)
{
// declares an Array of integers.
int[] arr;

// allocating memory for 5 integers.

Department of CSE / Siddharth Group of Institutions, Puttur 29


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

arr = new int[5];

// initialize the first elements of the array


arr[0] = 10;

// initialize the second elements of the array


arr[1] = 20;

//so on...
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;

// accessing the elements of the specified array


for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i + " : "+ arr[i]);
}
}
Output:

Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50
Multidimensional Arrays

Multidimensional arrays are arrays of arrays with each element of the array holding the reference
of other array. These are also known as Jagged Arrays. A multidimensional array is created by
appending one set of square brackets ([]) per dimension. Examples:

int[][] intArray = new int[10][20]; //a 2D array or matrix


int[][][] intArray = new int[10][20][10]; //a 3D array

class multiDimensional
{
public static void main(String args[])
{
// declaring and initializing 2D array
int arr[][] = { {2,7,9},{3,6,1},{7,4,2} };

// printing 2D array
for (int i=0; i< 3 ; i++)
{
for (int j=0; j < 3 ; j++)
System.out.print(arr[i][j] + " ");
}
Department of CSE / Siddharth Group of Institutions, Puttur 30
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

System.out.println();
}
}

Output:
279
361
742

COMMAND LINE ARGUMENTS

A command-line argument is an information that directly follows the program's name on the
command line when it is executed. To access the command-line arguments inside a Java
program is quite easy. They are stored as strings in the String array passed to main( ).

Example

public class CommandLine {


public static void main(String args[]) {
for(int i = 0; i<args.length; i++) {
System.out.println("args[" + i + "]: " + args[i]);
}
}
}
Output:
compile by > javac CommandLine.java
run by > java CommandLine this is a command line 200 -100

This will produce the following result -

args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100

Department of CSE / Siddharth Group of Institutions, Puttur 31


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

UNIT- II
INTRODUCING CLASSES
Introducing Classes –Class Fundamentals -Declaring Objects -Introducing Methods Introduction
to Constructors -Garbage Collection-Introducing final -Inheritance - Method Overriding -
abstract classes -Packages and Interfaces.

CLASS FUNDAMENTALS
A class is a user defined blueprint or prototype from which objects are created. It represents
the set of properties or methods that are common to all objects of one type. In general, class
declarations can include these components, in order:
1. Modifiers: A class can be public or has default access.
2. class keyword: class keyword is used to create a class.
3. Class name: The name should begin with an initial letter (capitalized by convention).
4. Superclass(if any): The name of the class‘s parent (superclass), if any, preceded by the
keyword extends. A class can only extend (subclass) one parent.
5. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any,
preceded by the keyword implements. A class can implement more than one interface.
6. Body: The class body surrounded by braces, { }.

Constructors are used for initializing new objects. Fields are variables that provides the state
of the class and its objects, and methods are used to implement the behavior of the class and
its objects.
There are various types of classes that are used in real time applications such as nested
classes, anonymous classes, lambda expressions.

OBJECT
It is a basic unit of Object-Oriented Programming and represents the real life entities. A
typical Java program creates many objects, which as you know, interact by invoking methods.
An object consists of :
1. State: It is represented by attributes of an object. It also reflects the properties of an object.
2. Behavior: It is represented by methods of an object. It also reflects the response of an
object with other objects.
3. Identity: It gives a unique name to an object and enables one object to interact with other
objects.

Example of an object: dog

Objects correspond to things found in the real world. For example, a graphics program may
have objects such as ―circle‖, ―square‖, ―menu‖. An online shopping system might have
objects such as ―shopping cart‖, ―customer‖, and ―product‖.

Department of CSE / Siddharth Group of Institutions, Puttur 32


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

DECLARING OBJECTS (ALSO CALLED INSTANTIATING A CLASS)


When an object of a class is created, the class is said to be instantiated. All the instances
share the attributes and the behavior of the class. But the values of those attributes, i.e. the
state are unique for each object. A single class may have any number of instances.

Ways to create object of a class


There are four ways to create objects in java.Strictly speaking there is only one way(by
using new keyword),and the rest internally use new keyword.
 Using new keyword: It is the most common and general way to create object in
java. Example:
// creating object of class Test
Test t = new Test();
 Using Class.forName(String className) method: There is a pre-defined class in java.lang
package with name Class. The forName(String className) method returns the Class object
associated with the class with the given string name.We have to give the fully qualified name for
a class. On calling new Instance() method on this Class object returns new instance of the class
with the given string name.
// creating object of public class Test
// consider class Test present in com.p1 package
Test obj = (Test)Class.forName("com.p1.Test").newInstance();
 Using clone() method: clone() method is present in Object class. It creates and returns a copy
of the object.
// creating object of class Test
Test t1 = new Test();
// creating clone of above object
Test t2 = (Test)t1.clone();
Creating multiple objects by one type only (A good practice)
 In real-time, we need different objects of a class in different methods. Creating a number of
references for storing them is not a good practice and therefore we declare a static reference
variable and use it whenever required. In this case, wastage of memory is less. The objects that
are not referenced anymore will be destroyed by Garbage Collector of java.
 Example:
Test test = new Test();
test = new Test();

Department of CSE / Siddharth Group of Institutions, Puttur 33


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

 In inheritance system, we use parent class reference variable to store a sub-class object. In this
case, we can switch into different subclass objects using same referenced variable.

Example:
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}
public class Test
{
// using Dog object
Animal obj = new Dog();
// using Cat object
obj = new Cat();
}
Anonymous objects
Anonymous objects are the objects that are instantiated but are not stored in a reference
variable.
 They are used for immediate method calling.
 They will be destroyed after method calling.
 They are widely used in different libraries. For example, in AWT libraries, they are used to
perform some action on capturing an event(eg a key press).
 In the example below, when a key is button(referred by the btn) is pressed, we are simply
creating anonymous object of EventHandler class for just calling handle method.

btn.setOnAction(new EventHandler())
{
public void handle(ActionEvent event)
{
System.out.println("Hello World!");
}
});

INTRODUCING METHODS
A method is a collection of statements that perform some specific task and return the result to
the caller. A method can perform some specific task without returning anything. Methods
allow us to reuse the code without retyping the code. In Java, every method must be part of
some class which is different from languages like C, C++, and Python.
Methods are time savers and help us to reuse the code without retyping the code.

Method Declaration
In general, method declarations has six components:
 Modifier-: Defines access type of the method i.e. from where it can be accessed in your
application. In Java, there 4 type of the access specifiers.
 public: accessible in all class in your application.
 protected: accessible within the class in which it is defined and in its subclass(es)
 private: accessible only within the class in which it is defined.

Department of CSE / Siddharth Group of Institutions, Puttur 34


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

 default (declared/defined without using any modifier) : accessible within same class and
package within which its class is defined.
 The return type : The data type of the value returned by the method or void if does not
return a value.
 Method Name : the rules for field names apply to method names as well, but the
convention is a little different.
 Parameter list : Comma separated list of the input parameters are defined, preceded with
their data type, within the enclosed parenthesis. If there are no parameters, you must use empty
parentheses ().
 Exception list : The exceptions you expect by the method can throw, you can specify these
exception(s).
 Method body : it is enclosed between braces. The code you need to be executed to perform
your intended operations.

Method signature: It consists of the method name and a parameter list (number of
parameters, type of the parameters and order of the parameters). The return type and
exceptions are not considered as part of it.
Method Signature of above function:
max(int x, int y)
How to name a Method?: A method name is typically a single word that should be a verb in
lowercase or multi-word, that begins with a verb in lowercase followed by adjective,
noun….. After the first word, first letter of each word should be capitalized.
For example,
findSum,
computeMax, setX and getX
Generally, A method has a unique name within the class in which it is defined but sometime a
method might have the same name as other method names within the same class as method
overloading.
Calling a method
The method needs to be called for using its functionality. There can be three situations when a
method is called:

A method returns to the code that invoked it when:


 It completes all the statements in the method
 It reaches a return statement
 Throws an exception

// Program to illustrate methodsin java

Department of CSE / Siddharth Group of Institutions, Puttur 35


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

import java.io.*;

class Addition {
int sum = 0;

public int addTwoInt(int a, int b){

// adding two integer value.


sum = a + b;

//returning summation of two values.


return sum;
}

class Test {
public static void main (String[] args) {

// creating an instance of Addition class


Addition add = new Addition();

// calling addTwoInt() method to add two integer using instance created


// in above step.
int s = add.addTwoInt(1,2);
System.out.println("Sum of two integer values :"+ s);

}
}
Output :
Sum of two integer values :3

INTRODUCTION TO CONSTRUCTORS
Constructors are used to initialize the object‘s state. Like methods, a constructor also
contains collection of statements(i.e. instructions) that are executed at time of Object
creation.
Need of Constructor
Think of a Box. If we talk about a box class then it will have some class variables (say length,
breadth, and height). But when it comes to creating its object (i.e Box will now exist in
computer‘s memory), then can a box be there with no value defined for its dimensions. The
answer is no.
So constructors are used to assign values to the class variables at the time of object creation,
either explicitly done by the programmer or by Java itself (default constructor).
When is a Constructor called ?
Each time an object is created using new() keyword at least one constructor (it could be
default constructor) is invoked to assign initial values to the data members of the same class.
A constructor is invoked at the time of object or instance creation. For Example:
Department of CSE / Siddharth Group of Institutions, Puttur 36
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

class Geek
{
.......

// A Constructor
new Geek() {}
.......
}
Rules for writing Constructor:
 Constructor(s) of a class must have same name as the class name in which it resides.
 A constructor in Java can not be abstract, final, static and Synchronized.
 Access modifiers can be used in constructor declaration to control its access i.e which other
class can call the constructor.
Types of constructor
There are two type of constructor in Java:
1. No-argument constructor: A constructor that has no parameter is known as default
constructor. If we don‘t define a constructor in a class, then compiler creates default
constructor(with no arguments) for the class. And if we write a constructor with arguments
or no-arguments then the compiler does not create a default constructor.
Default constructor provides the default values to the object like 0, null, etc. depending on the
type.

// Java Program to illustrate calling a


// no-argument constructor
import java.io.*;

class Sam
{
int num;
String name;
// this would be invoked while an object
// of that class is created.
Sam()
{
System.out.println("Constructor called");
}
}
class Hai
{
public static void main (String[] args)
{
// this would invoke default constructor.
Sam s1 = new Sam();

// Default constructor provides the default


// values to the object like 0, null
System.out.println(s1.name);
Department of CSE / Siddharth Group of Institutions, Puttur 37
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

System.out.println(s1.num);
}
}

Output :
Constructor called
null
0
2. Parameterized Constructor: A constructor that has parameters is known as parameterized
constructor. If we want to initialize fields of the class with your own values, then use a
parameterized constructor.
// Java Program to illustrate calling of
// parameterized constructor.
import java.io.*;

class Sam
{
// data members of the class.
String name;
int id;
// constructor would initialize data members
// with the values of passed arguments while
// object of that class created.
Sam (String name, int id)
{
this.name = name;
this.id = id;
}
}

class Sam1
{
public static void main (String[] args)
{
// this would invoke the parameterized constructor.
Sam s1 = new Sam ("sample", 555);
System.out.println("Name :" + s1.name + " and Id :" + s1.id);
}
}
Output:
Name :sample and Id :555

CONSTRUCTOR OVERLOADING
Does constructor return any value?
There are no ―return value‖ statements in constructor, but constructor returns current class
instance. We can write ‗return‘ inside a constructor.

Department of CSE / Siddharth Group of Institutions, Puttur 38


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

In addition to overloading methods, we can also overload constructors in java. Overloaded


constructor is called based upon the parameters specified when new is executed.
When do we need Constructor Overloading?
Sometimes there is a need of initializing an object in different ways. This can be done using
constructor overloading. For example, Thread class has 8 types of constructors. If we do not
want to specify anything about a thread then we can simply use default constructor of Thread
class, however if we need to specify thread name, then we may call the parameterized
constructor of Thread class with a String args like this:
Thread t= new Thread (" MyThread ");
// Java program to illustrate
// Constructor Overloading
class Box
{
double width, height, depth;

// constructor used when all dimensions


// specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}

// constructor used when no dimensions


// specified
Box()
{
width = height = depth = 0;
}

// constructor used when cube is created


Box(double len)
{
width = height = depth = len;
}

// compute and return volume


double volume()
{
return width * height * depth;
}
}

// Driver code
public class Test
{
Department of CSE / Siddharth Group of Institutions, Puttur 39
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

public static void main(String args[])


{
// create boxes using the various
// constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);

double vol;

// get volume of first box


vol = mybox1.volume();
System.out.println(" Volume of mybox1 is " + vol);

// get volume of second box


vol = mybox2.volume();
System.out.println(" Volume of mybox2 is " + vol);

// get volume of cube


vol = mycube.volume();
System.out.println(" Volume of mycube is " + vol);
}
}

OUTPUT:
Volume of mybox1 is 3000.0
Volume of mybox2 is 0.0
Volume of mycube is 343.0

Use of this () in constructor overloading


However, we can use this keyword inside the constructor, which can be used to invoke the other
constructor of the same class.
Consider the following example to understand the use of this keyword in constructor
overloading.

public class Student {


//instance variables of the class
int id,passoutYear;
String name,contactNo,collegeName;
Student(String contactNo, String collegeName, int passoutYear){
this.contactNo = contactNo;
this.collegeName = collegeName;
this.passoutYear = passoutYear;
}
Student(int id, String name){
this("9899234455", "IIT Kanpur", 2018);
this.id = id;
Department of CSE / Siddharth Group of Institutions, Puttur 40
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

this.name = name;
}
}
class test
{
public static void main(String[] args) {
//object creation
Student s = new Student(101, "John");
System.out.println("Printing Student Information: \n");
System.out.println("Name: "+s.name+"\nId: "+s.id+"\nContact No.: "+s.contactNo+"\nCollege
Name: "+s.contactNo+"\nPassing Year: "+s.passoutYear);
}
}

OUTPUT:
Printing Student Information:
Name: John
Id: 101
Contact No.: 9899234455
College Name: 9899234455
Passing Year: 2018

How constructors are different from methods in Java?


 Constructor(s) must have the same name as the class within which it defined while it is not
necessary for the method in java.
 Constructor(s) do not return any type while method(s) have the return type or void if does
not return any value.
 Constructor is called only once at the time of Object creation while method(s) can be called
any numbers of time.

GARBAGE COLLECTION
In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other
words, it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.
Advantage of Garbage Collection
o It makes java memory efficient because garbage collector removes the unreferenced objects
from heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we don't need to make
extra efforts.
How can an object be unreferenced?
There are many ways:
o By nulling the reference
o By assigning a reference to another
o By anonymous object etc.
1) By nulling a reference:
Department of CSE / Siddharth Group of Institutions, Puttur 41
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

Employee e=new Employee();


e=null;
2) By assigning a reference to another:
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage collection
3) By anonymous object:
new Employee();
finalize() method
The finalize() method is invoked each time before the object is garbage collected. This method
can be used to perform cleanup processing. This method is defined in Object class as:
protected void finalize(){}
Note: The Garbage collector of JVM collects only those objects that are created by new
keyword. So if you have created any object without new, you can use finalize method to perform
cleanup processing (destroying remaining objects).
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The
gc() is found in System and Runtime classes.

public static void gc(){}

Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC). This
thread calls the finalize() method before object is garbage collected.

//Simple Example of garbage collection in java

public class TestGarbage1{


public void finalize(){System.out.println("object is garbage collected");}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}
Output:
object is garbage collected
object is garbage collected

INTRODUCING FINAL

1. Final variables
Department of CSE / Siddharth Group of Institutions, Puttur 42
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

When a variable is declared with final keyword, its value can‘t be modified, essentially, a
constant. This also means that you must initialize a final variable. If the final variable is a
reference, this means that the variable cannot be re-bound to reference another object, but
internal state of the object pointed by that reference variable can be changed i.e. you can add or
remove elements from final array or final collection. It is good practice to represent final
variables in all uppercase, using underscore to separate words.
//Java program to demonstrate different
// ways of initializing a final variable

class Gfg
{
// a final variable
// direct initialize
final int THRESHOLD = 5;

// a blank final variable


final int CAPACITY;

// another blank final variable


final int MINIMUM;

// a final static variable PI


// direct initialize
static final double PI = 3.141592653589793;

// a blank final static variable


static final double EULERCONSTANT;

// instance initializer block for


// initializing CAPACITY
{
CAPACITY = 25;
}

// static initializer block for


// initializing EULERCONSTANT
static{
EULERCONSTANT = 2.3;
}

// constructor for initializing MINIMUM


// Note that if there are more than one
// constructor, you must initialize MINIMUM
// in them also
public GFG()
{
MINIMUM = -1;
Department of CSE / Siddharth Group of Institutions, Puttur 43
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

When to use a final variable :


The only difference between a normal variable and a final variable is that we can re-assign value
to a normal variable but we cannot change the value of a final variable once assigned. Hence
final variables must be used only for the values that we want to remain constant throughout the
execution of program.
2. Java final Method

class FinalDemo {
// create a final method
public final void display() {
System.out.println("This is a final method.");
}
}

class Main extends FinalDemo {


// try to override final method
public final void display() {
System.out.println("The final method is overridden.");
}

public static void main(String[] args) {


Main obj = new Main();
obj.display();
}
}

In the above example, we have created a final method named display() inside the FinalDemo
class. Here, the Main class inherits the FinalDemo class.

We have tried to override the final method in the Main class. When we run the program, we will
get a compilation error with the following message.

display() in Main cannot override display() in FinalDemo


public final void display() {
^
overridden method is final
3. Java final Class
In Java, the final class cannot be inherited by another class. For example,

// create a final class


final class FinalClass {
public void display() {
System.out.println("This is a final method.");
}
Department of CSE / Siddharth Group of Institutions, Puttur 44
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

// try to extend the final class


class Main extends FinalClass {
public void display() {
System.out.println("The final method is overridden.");
}

public static void main(String[] args) {


Main obj = new Main();
obj.display();
}
}

In the above example, we have created a final class named FinalClass. Here, we have tried to
inherit the final class by the Main class.

When we run the program, we will get a compilation error with the following message.

cannot inherit from final FinalClass


class Main extends FinalClass {
^

INHERITANCE
Inheritance can be defined as the process where one class acquires the properties (methods and
fields) of another. With the use of inheritance the information is made manageable in a
hierarchical order.

The class which inherits the properties of other is known as subclass (derived class, child class)
and the class whose properties are inherited is known as superclass (base class, parent class).
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

extends Keyword
extends is the keyword used to inherit the properties of a class. Following is the syntax of
extends keyword.

Syntax
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}

Department of CSE / Siddharth Group of Institutions, Puttur 45


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

Why use inheritance in java


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

Terms used in Inheritance


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

File: TestInheritance.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}

Department of CSE / Siddharth Group of Institutions, Puttur 46


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}
}
Output:
barking...
eating...

Multilevel Inheritance Example


When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the
example given below, BabyDog class inherits the Dog class which again inherits the Animal
class, so there is a multilevel inheritance.

File: TestInheritance2.java

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}
}
Output:

weeping...
barking...
eating...

Hierarchical Inheritance Example


When two or more classes inherits a single class, it is known as hierarchical inheritance. In the
example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical
inheritance.

Department of CSE / Siddharth Group of Institutions, Puttur 47


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}

Output:
meowing...
eating...

USING SUPER

The super keyword in Java is a reference variable which is used to refer immediate parent class
object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.

Uses of super keyword


 To call methods of the superclass that is overridden in the subclass.
 To access attributes (fields) of the superclass if both superclass and subclass have attributes
with the same name.
 To explicitly call superclass no-arg (default) or parameterized constructor from the subclass
constructor.
Let‘s understand each of these uses.

1) super is used to refer immediate parent class instance variable.

class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
Department of CSE / Siddharth Group of Institutions, Puttur 48
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}
}
Output:
black
white

In the above example, Animal and Dog both classes have a common property color. If we print
color property, it will print the color of current class by default. To access the parent property,
we need to use super keyword.

2) super can be used to invoke parent class method


The super keyword can also be used to invoke parent class method. It should be used if subclass
contains the same method as parent class. In other words, it is used if method is overridden.

class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void eat()
{
System.out.println("eating bread...");
}
void bark()
{
System.out.println("barking...");
}
void work()
{
super.eat();
bark();
}
}
class TestSuper2
{
public static void main(String args[])
{
Department of CSE / Siddharth Group of Institutions, Puttur 49
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

Dog d=new Dog();


d.work();
}
}
Output:
eating...
barking...
In the above example Animal and Dog both classes have eat() method if we call eat() method
from Dog class, it will call the eat() method of Dog class by default because priority is given to
local.

To call the parent class method, we need to use super keyword.

3) super is used to invoke parent class constructor.


The super keyword can also be used to invoke the parent class constructor. Let's see a simple
example:
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
Output:
animal is created
dog is created

METHOD OVERLOADING

In Java, two or more methods may have the same name if they differ in parameters (different
number of parameters, different types of parameters, or both). These methods are called
overloaded methods and this feature is called method overloading. For example:

void func() { ... }


void func(int a) { ... }
float func(double a) { ... }
float func(int a, float b) { ... }

Advantage of method overloading


Method overloading increases the readability of the program.

Department of CSE / Siddharth Group of Institutions, Puttur 50


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

Different ways to overload the method


There are two ways to overload the method in java

 By changing number of arguments


 By changing the data type
Method Overloading: changing no. of arguments
In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.

In this example, we are creating static methods so that we don't need to create instance for
calling methods.

class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Output:
22
33
Method Overloading: changing data type of arguments
In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments.

class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Output:
22
24.9

METHOD OVERRIDING

If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in Java.
In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.
Department of CSE / Siddharth Group of Institutions, Puttur 51
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

Usage of Java Method Overriding


 Method overriding is used to provide the specific implementation of a method which is
already provided by its superclass.
 Method overriding is used for runtime polymorphism
Rules for Method Overriding
 The argument list should be exactly the same as that of the overridden method.
 The return type should be the same or a subtype of the return type declared in the original
overridden method in the superclass.
 The access level cannot be more restrictive than the overridden method's access level. For
example: If the superclass method is declared public then the overriding method in the sub class
cannot be either private or protected.
 Instance methods can be overridden only if they are inherited by the subclass.
 A method declared final cannot be overridden.
 A method declared static cannot be overridden but can be re-declared.
 If a method cannot be inherited, then it cannot be overridden.
 A subclass within the same package as the instance's superclass can override any superclass
method that is not declared private or final.
 A subclass in a different package can only override the non-final methods declared public or
protected.
 An overriding method can throw any uncheck exceptions, regardless of whether the
overridden method throws exceptions or not. However, the overriding method should not throw
checked exceptions that are new or broader than the ones declared by the overridden method.
The overriding method can throw narrower or fewer exceptions than the overridden method.
 Constructors cannot be overridden.

class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike extends Vehicle{
public static void main(String args[]){
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class instance
obj.run();
}
}

Output:
Vehicle is running

Example of method overriding


In this example, we have defined the run method in the subclass as defined in the parent class
but it has some specific implementation. The name and parameter of the method are the same,
and there is IS-A relationship between the classes, so there is method overriding.

Department of CSE / Siddharth Group of Institutions, Puttur 52


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

class Bank{
int getRateOfInterest(){return 0;}
}
//Creating child classes.
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}

class ICICI extends Bank{


int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
//Test class to create objects and call the methods
class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}

Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

Department of CSE / Siddharth Group of Institutions, Puttur 53


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

The differences between Method Overloading and Method Overriding in Java are:

Method Overloading Method Overriding


S.NO

Method overloading is a compile-time Method overriding is a run-time


1. polymorphism. polymorphism.

It is used to grant the specific


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

It is performed in two classes with


3. It occurs within the class. inheritance relationships.

Method overloading may or may not Method overriding always needs


4. require inheritance. inheritance.

In method overloading, methods must


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

In method overloading, the return type


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

ABSTRACT CLASSES
A class which is declared with the abstract keyword is known as an abstract class in Java. It can
have abstract and non-abstract methods (method with the body).
it shows only essential things to the user and hides the internal details, for example, sending
SMS where you type the text and send the message. You don't know the internal processing
about the message delivery.
There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)
Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the method.

Department of CSE / Siddharth Group of Institutions, Puttur 54


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

Example:
abstract class Bike{
abstract void run();
}
class Honda extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
}
}

//Example of an abstract class that has abstract and non-abstract methods


abstract class Bike{
Bike(){System.out.println("bike is created");}
abstract void run();
void changeGear(){System.out.println("gear changed");}
}
//Creating a Child class which inherits Abstract class
class Honda extends Bike{
void run(){System.out.println("running safely..");}
}
//Creating a Test class which calls abstract and non-abstract methods
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
} }

Output:
bike is created
running safely..
gear changed

PACKAGES AND INTERFACES

PACKAGES
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined
package.There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql
etc.

Department of CSE / Siddharth Group of Institutions, Puttur 55


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

Advantages of Packages
 Packages provide code reusability, because a package has group of classes.
 It helps in resolving naming collision when multiple packages have classes with the same
name.
 Package also provides the hiding of class facility. Thus other programs cannot use the classes
from hidden package.
 Access limitation can be applied with the help of packages.
 One package can be defined in another package.
Types of Packages
There are two types of packages available in Java.

1. Built-in package
Built-in packages are already defined in java API. For example: java.util, java.io, java,lang,
java.awt, java.applet, java.net, etc.
2. User defined packages
The package we create according to our need is called user defined package.
Creating a Package
We can create our own package by creating our own classes and interfaces together. The
package statement should be declared at the beginning of the program.
Syntax:
package <packagename>;
class ClassName
{
……..
……..
}

Example: Creating a Package


// Demo.java
package p1;
class Demo

Department of CSE / Siddharth Group of Institutions, Puttur 56


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

{
public void m1()
{
System.out.println("Method m1..");
}
}
How to compile?
Syntax: javac –d directory javafilename
For Example: javac –d . Demo.java

How to run?
To run: java p1.Demo
Example: Program to create and use a user defined ackage in Java.
// Vehicle.java
package vehicles;
interface Vehicle
{
public void run();
public void speed();
}

//Bike.java
package vehicles;
public class Bike implements Vehicle
{
public void run()
{
System.out.println("Bike is running.");
}
public void speed()
{
System.out.println("Speed of Bike: 50 Km/h");
}
public static void main(String args[])
{
Bike bike = new Bike();
bike.run();
bike.speed();
}
}

Compile:
javac –d . Vehicle.java
javac –d . Bike.java

Run:
java vehicles.Bike
Department of CSE / Siddharth Group of Institutions, Puttur 57
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

Output:
Bike is running
Speed of Bike: 50 Km/h

INTERFACE
 Interface is similar to a class, but it contains only abstract methods.
 By default the variables declared in an interface are public, static and final.
 Interface is a mechanism to achieve full abstraction.
 An interface does not contain any constructor.

Syntax:
interface InterfaceName
{
public void method1();
public void method2();
<type> variableName = value;
}
Example: Sample program to implements multiple inheritance
interface Vehicle
{
void run();
}
interface Bike extends Vehicle
{
void stop();
}
public class Demo implements Bike
{
public void run()
{
System.out.println("Vehicle is running.");
}
public void stop()
{
System.out.println("Bike is stop.");
}
public static void main(String args[])
{
Demo obj = new Demo();
obj.run();
obj.stop();
}
}

Output:
Vehicle is running.
Department of CSE / Siddharth Group of Institutions, Puttur 58
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

Bike is stop.

Marker Interface
An interface which does not contain any fields and methods is known as marker or tag interface.
It is an empty interface.

For example Serializable, EventListener, MouseListner, Remote, Cloneable etc.

Example:
package java.util;
public interface EventListner
{
}

Differences between Abstract class and Interface

Abstract class Interface


It cannot support multiple inheritances. Interface supports multiple inheritances.
It contains both abstract and non abstract It contains only abstract method.
method.
Abstract class is the partially implemented class. Interface is fully unimplemented class.
It can have main method and constructor. It cannot have main method and constructor.
It can have static, non-static, final, non-final It contains only static and final variable.
variables.

Department of CSE / Siddharth Group of Institutions, Puttur 59


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

UNIT- III
EXCEPTION HANDLING
Exception Handling - Exception Fundamentals - Exception Types -Uncaught Exceptions -
Using try and catch - Nested try Statements -throw -throws –finally
Multithreaded Programming - The Java Thread Model -Thread Priorities -The Thread Class
and the Runnable Interface - Creating Multiple Threads -Using is Alive( ) and join( ) – Thread
Priorities - Synchronization - String Handling.

EXCEPTION FUNDAMENTALS
An exception (or exceptional event) is a problem that arises during the execution of a program.
When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore, these
exceptions are to be handled.
 An exception can occur for many different reasons. Following are some scenarios where an
exception occurs.
 A user has entered an invalid data.
 A file that needs to be opened cannot be found.
 A network connection has been lost in the middle of communications or the JVM has run out
of memory.
Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.

Hierarchy of Java Exception classes

Department of CSE / Siddharth Group of Institutions, Puttur 60


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

EXCEPTION TYPES
There are mainly two types of exceptions: checked and unchecked. Here, an error is considered
as the unchecked exception. According to Oracle, there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error

Difference between Checked and Unchecked Exceptions


1) Checked Exception
The classes which directly inherit Throwable class except RuntimeException and Error are
known as checked exceptions e.g. IOException, SQLException etc. Checked exceptions are
checked at compile-time.
2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked
exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Java Exception Keywords


There are 5 keywords which are used in handling exceptions in Java.
Keyword Description

try The "try" keyword is used to specify a block where we should place exception code.
The try block must be followed by either catch or finally. It means, we can't use try
block alone.

catch The "catch" block is used to handle the exception. It must be preceded by try block
which means we can't use catch block alone. It can be followed by finally block later.

finally The "finally" block is used to execute the important code of the program. It is
executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It
specifies that there may occur an exception in the method. It is always used with
method signature.

UNCAUGHT EXCEPTIONS
In java, assume that, if we do not handle the exceptions in a program. In this case, when an
exception occurs in a particular function, then Java prints a exception message with the help of
uncaught exception handler.

The uncaught exceptions are the exceptions that are not caught by the compiler but automatically
caught and handled by the Java built-in exception handler.

Department of CSE / Siddharth Group of Institutions, Puttur 61


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

Java programming language has a very strong exception handling mechanism. It allow us to
handle the exception use the keywords like try, catch, finally, throw, and throws.

When an uncaught exception occurs, the JVM calls a special private method known
dispatchUncaughtException( ), on the Thread class in which the exception occurs and
terminates the thread.

Example:
import java.util.Scanner;
public class UncaughtExceptionExample {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
System.out.println("Enter the a and b values: ");
int a = read.nextInt();
int b = read.nextInt();
int c = a / b;
System.out.println(a + "/" + b +" = " + c);
}
}
When we execute the above code, it produce the following output for the value a = 10 and b = 0.

In the above example code, we are not used try and catch blocks, but when the value of b is zero
the division by zero exception occurs and it caught by the default exception handler.

USING TRY AND CATCH


Java try block is used to enclose the code that might throw an exception. It must be used within
the method.
If an exception occurs at the particular statement of try block, the rest of the block code will not
execute. So, it is recommended not to keeping the code in try block that will not throw an
exception.
Java try block must be followed by either catch or finally block.

Syntax of Java try-catch

try{
//code that may throw an exception
}catch(Exception_class_Name ref){}
Syntax of try-finally block
try{
//code that may throw an exception
}finally{}

Department of CSE / Siddharth Group of Institutions, Puttur 62


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

ArithmeticException generated by the division-by-zero error:

class Exc2 {
public static void main(String args[]) {
int d, a;
try { // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
This program generates the following output:
Division by zero.
After catch statement.
Internal working of java try-catch block

Notice that the call to println( ) inside the try block is never executed. Once an exception
is thrown, program control transfers out of the try block into the catch block. Put
differently,catch is not ―called,‖ so execution never ―returns‖ to the try block from a catch. Thus,
theline "This will not be printed." is not displayed. Once the catch statement has
executed,program control continues with the next line in the program following the entire try
/catch mechanism.
A try and its catch statement form a unit. The scope of the catch clause is restricted to those
statements specified by the immediately preceding try statement. A catch statementcannot catch
an exception thrown by another try statement (except in the case of nestedtry statements,
described shortly). The statements that are protected by try must besurrounded by curly braces.
(That is, they must be within a block.) You cannot use tryon a single statement.

Department of CSE / Siddharth Group of Institutions, Puttur 63


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

NESTED TRY STATEMENTS


The try block within a try block is known as nested try block in java.

Why use nested try block


Sometimes a situation may arise where a part of a block may cause one error and the entire block
itself may cause another error. In such cases, exception handlers have to be nested.

Syntax:
....
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
....

Example
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}

try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);
}
System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");
}
System.out.println("normal flow..");
}
}
Department of CSE / Siddharth Group of Institutions, Puttur 64
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

THROW
The Java throw keyword is used to explicitly throw an exception.
We can throw either checked or uncheked exception in java by throw keyword. The throw
keyword is mainly used to throw custom exception. We will see custom exceptions later.
The syntax of java throw keyword is given below.
throw exception;

Example

public class TestThrow1{


static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:not valid

THROWS
The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to provide the
exception handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers fault that he is not
performing check up before the code being used.
Syntax of java throws
1. return_type method_name() throws exception_class_name{
2. //method code
3. }
# Which exception should be declared
Ans) checked exception only, because:
o unchecked Exception: under your control so correct your code.
o error: beyond your control e.g. you are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.

Advantage of Java throws keyword


 Now Checked Exception can be propagated (forwarded in call stack).
 It provides information to the caller of the method about the exception.

Department of CSE / Siddharth Group of Institutions, Puttur 65


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

FINALLY
A finally block contains all the crucial statements that must be executed whether exception
occurs or not. The statements present in this block will always execute regardless of whether
exception occurs in try block or not such as closing a connection, stream etc.
Syntax of Finally block
try {
//Statements that may cause an exception
}
catch {
//Handling exception
}
finally {
//Statements to be executed
}
A Simple Example of finally block
Here you can see that the exception occurred in try block which has been handled in catch block,
after that finally block got executed.
class Example
{
public static void main(String args[]) {
try{
int num=121/0;
System.out.println(num);
}
catch(ArithmeticException e){
System.out.println("Number should not be divided by zero");
}
/* Finally block will always execute
* even if there is no exception in try block
*/
finally{
System.out.println("This is finally block");
}
System.out.println("Out of try-catch-finally");
}
}
Output:
Number should not be divided by zero
This is finally block
Out of try-catch-finally
Few Important points regarding finally block
1. A finally block must be associated with a try block, you cannot use finally without a try
block. You should place those statements in this block that must be executed always.
2. Finally block is optional, as we have seen in previous tutorials that a try-catch block is
sufficient for exception handling, however if you place a finally block then it will always run
after the execution of try block.

Department of CSE / Siddharth Group of Institutions, Puttur 66


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

3.In normal case when there is no exception in try block then the finally block is executed after
try block. However if an exception occurs then the catch block is executed before finally block.
4.An exception in the finally block, behaves exactly like any other exception.
5.The statements present in the finally block execute even if the try block contains control
transfer statements like return, break or continue.
Cases when the finally block doesn’t execute
The circumstances that prevent execution of the code in a finally block are:
– The death of a Thread
– Using of the System. exit() method.
– Due to an exception arising in the finally block.

CREATING YOUR OWN EXCEPTION SUBCLASSES

Although Java‘s built-in exceptions handle most common errors, you will probably want to
create your own exception types to handle situations specific to your applications. This is quite
easy to do: just define a subclass of Exception (which is, of course, a subclass of Throwable).
Your subclasses don‘t need to actually implement anything it is their existence in the type
system that allows you to use them as exceptions.
The Exception class does not define any methods of its own. It does, of course, inherit those
methods provided by Throwable. Thus, all exceptions, including those that you create, have the
methods defined by Throwable available to them. They are shown in Table 10-3. You may also
wish to override one or more of these methods in exception classes that you create.
Exception defines four public constructors. Two support chained exceptions, described in the
next section. The other two are shown here:
Exception( )
Exception(String msg)
The first form creates an exception that has no description. The second form lets you specify a
description of the exception.
Although specifying a description when an exception is created is often useful, sometimes it is
better to override toString( ).
Here‘s why: The version of toString( ) defined by Throwable (and inherited by Exception) first
displays the name of the exception followed by a colon, which is then followed by your
description. By overriding toString( ), you can prevent the exception name and colon from
being displayed. This makes for a cleaner output, which is desirable in some cases.
The following example declares a new subclass of Exception and then uses that subclass to
signal an error condition in a method. It overrides the toString( ) method, allowing a carefully
tailored description of the exception to be displayed.

// This program creates a custom exception type.


class MyException extends Exception {
private int detail;
MyException(int a) { detail = a;
}
public String toString() {
return "MyException[" + detail + "]";
}
}
Department of CSE / Siddharth Group of Institutions, Puttur 67
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

class ExceptionDemo {
static void compute(int a) throws MyException {
System.out.println("Called compute(" + a + ")"); if(a > 10)
throw new MyException(a); System.out.println("Normal exit");
}
public static void main(String args[]) { try {
compute(1);
compute(20);
} catch (MyException e) {
System.out.println("Caught " + e);
}
}
}

This example defines a subclass of Exception called MyException. This subclass is quite
simple: It has only a constructor plus an overridden toString( ) method that displays the value of
the exception. The ExceptionDemo class defines a method named compute( ) that throws
a MyException object. The exception is thrown when compute( )‘s integer parameter is greater
than 10. The main( ) method sets up an exception handler for MyException, then
calls compute( ) with a legal value (less than 10) and an illegal one to show both paths through
the code.
Here is the result:
Called compute(1)
Normal exit
Called compute(20)
Caught MyException[20]

CHAINED EXCEPTIONS
Chained exception helps to relate one exception to other. Often we need to throw a custom
exception and want to keep the details of an original exception that in such scenarios we can use
the chained exception mechanism. Consider the following example, where we are throwing a
custom exception while keeping the message of the original exception.

public class Tester {


public static void main(String[] args) {
try {
test();
}catch(ApplicationException e) {
System.out.println(e.getMessage());
}
}
public static void test() throws ApplicationException {
try {
int a = 0;
int b = 1;
System.out.println(b/a);

Department of CSE / Siddharth Group of Institutions, Puttur 68


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

}catch(Exception e) {
throw new ApplicationException(e);
}
}
}
class ApplicationException extends Exception {
public ApplicationException(Exception e) {
super(e);
}
}
Output
java.lang.ArithmeticException: / by zero

The throwable class supports chained exception using the following methods:
Constructors
 Throwable(Throwable cause) - the cause is the current exception.
 Throwable(String msg, Throwable cause) - msg is the exception message, the cause is
the current exception.
Methods
 getCause - returns actual cause.
 initCause(Throwable cause) - sets the cause for calling an exception.

Department of CSE / Siddharth Group of Institutions, Puttur 69


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

MULTITHREADED PROGRAMMING
THE JAVA THREAD MODEL
Java is a multi-threaded programming language which means we can develop multi-threaded
program using Java. A multi-threaded program contains two or more parts that can run
concurrently and each part can handle a different task at the same time making optimal use of
the available resources specially when your computer has multiple CPUs.

By definition, multitasking is when multiple processes share common processing resources such
as a CPU. Multi-threading extends the idea of multitasking into applications where you can
subdivide specific operations within a single application into individual threads. Each of the
threads can run in parallel. The OS divides processing time not only among different
applications, but also among each thread within an application.

Multi-threading enables you to write in a way where multiple activities can proceed concurrently
in the same program.

Life Cycle of a Thread


A thread goes through various stages in its life cycle. For example, a thread is born, started, runs,
and then dies. The following diagram shows the complete life cycle of a thread.

Following are the stages of the life cycle −


 New − A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.
 Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this
state is considered to be executing its task.
 Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for
another thread to perform a task. A thread transitions back to the runnable state only when
another thread signals the waiting thread to continue executing.
 Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval
of time. A thread in this state transitions back to the runnable state when that time interval
expires or when the event it is waiting for occurs.
 Terminated (Dead) − A runnable thread enters the terminated state when it completes its task
or otherwise terminates.

THREAD PRIORITIES
Each thread have a priority. 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

Department of CSE / Siddharth Group of Institutions, Puttur 70


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

scheduling). But it is not guaranteed because it depends on JVM specification that which
scheduling it chooses.
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.

3 constants defined in Thread class:


1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and
the value of MAX_PRIORITY is 10.

Example of priority of a Thread:


class TestMultiPriority1 extends Thread{
public void run(){
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1(); TestMultiPriority1 m2=new
TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}

Output:
running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1

THE THREAD CLASS AND THE RUNNABLE INTERFACE


Java‘s multithreading system is built upon the Thread class, its methods, and its companion
interface, Runnable. Thread encapsulates a thread of execution. Since you can‘t directly refer
to the ethereal state of a running thread, you will deal with it through its proxy, the Thread
instance that spawned it. To create a new thread, your program will either extend Thread or
implement the Runnable interface.
Department of CSE / Siddharth Group of Institutions, Puttur 71
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

The Thread class defines several methods that help manage threads. Several of those used in
this chapter are shown here:

Creating a Thread
In the most general sense, you create a thread by instantiating an object of type Thread. Java
defines two ways in which this can be accomplished:
• You can implement the Runnable interface.
• You can extend the Thread class, itself.
The following two sections look at each method, in turn.
Implementing Runnable
The easiest way to create a thread is to create a class that implements the Runnable interface.
Runnable abstracts a unit of executable code. You can construct a thread on any object that
implements Runnable. To implement Runnable, a class need only implement a single method
called run( ), which is declared like this:
public void run( )
Inside run( ), you will define the code that constitutes the new thread. It is important to
understand that run( ) can call other methods, use other classes, and declare variables, just like
the main thread can.
After you 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)

After the new thread is created, it will not start running until you call its start( ) method,
which is declared within Thread. In essence, start( ) executes a call to run( ).
The start( ) method is shown here:
void start( )

class NewThread implements Runnable {


Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {

Department of CSE / Siddharth Group of Institutions, Puttur 72


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ThreadDemo {
public static void main(String args[ ] ) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
Extending Thread
The second way to create a thread is to create a new class that extends Thread, and then to create
an instance of that class. The extending class must override the run( ) method, which is the entry
point for the new thread. It must also call start( ) to begin execution of the new thread.
Here is the preceding program rewritten to extend Thread:

// Create a second thread by extending Thread


class NewThread extends Thread {
NewThread() {
// Create a new, second thread
super("Demo Thread");
System.out.println("Child thread: " + this);
start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
Department of CSE / Siddharth Group of Institutions, Puttur 73
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ExtendThread {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}

CREATING MULTIPLE THREADS


So far, you have been using only two threads: the main thread and one child thread.
However, your program can spawn as many threads as it needs. For example, the following
program creates three child threads:
// Create multiple threads.
class NewThread implements Runnable {
String name; // name of thread
Thread t;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}
Department of CSE / Siddharth Group of Institutions, Puttur 74
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

class MultiThreadDemo {
public static void main(String args[]) {
new NewThread("One"); // start threads
new NewThread("Two");
new NewThread("Three");
try {
// wait for other threads to end
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}
Sample output from this program is shown here. (Your output may vary based upon the
specific execution environment.)
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
One: 5
Two: 5
Three: 5
One: 4
Two: 4
Three: 4
One: 3
Three: 3
Two: 3
One: 2
Three: 2
Two: 2
One: 1
Three: 1
Two: 1
One exiting.
Two exiting.
Three exiting.
Main thread exiting.

USING ISALIVE( ) AND JOIN( )


isAlive() : It tests if this thread is alive. A thread is alive if it has been started and has not yet
died. There is a transitional period from when a thread is running to when a thread is not
running. After the run() method returns, there is a short period of time before the thread stops. If
we want to know if the start method of the thread has been called or if thread has been

Department of CSE / Siddharth Group of Institutions, Puttur 75


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

terminated, we must use isAlive() method. This method is used to find out if a thread has
actually been started and has yet not terminated.
General
Syntax :
final boolean isAlive( )

join() : When the join() method is called, the current thread will simply wait until the thread it is
joining with is no longer alive.
Or we can say the method that you will more commonly use to wait for a thread to finish is
called join( ). This method waits until the thread on which it is called terminates. Its name comes
from the concept of the calling thread waiting until the specified thread joins it. Additional forms
of join( ) allow you to specify a maximum amount of time that you want to wait for the specified
thread to terminate.
Syntax :
final void join( ) throws InterruptedException

// Using join() to wait for threads to finish.


class NewThread implements Runnable {
String name; // name of thread
Thread t;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}
}
class DemoJoin {
public static void main(String args[]) {
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
NewThread ob3 = new NewThread("Three");
System.out.println("Thread One is alive: "+ ob1.t.isAlive());
System.out.println("Thread Two is alive: "+ ob2.t.isAlive());
System.out.println("Thread Three is alive: "+ ob3.t.isAlive());
Department of CSE / Siddharth Group of Institutions, Puttur 76
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

// wait for threads to finish


try {
System.out.println("Waiting for threads to finish.");
ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Thread One is alive: "+ ob1.t.isAlive());
System.out.println("Thread Two is alive: "+ ob2.t.isAlive());
System.out.println("Thread Three is alive: "+ ob3.t.isAlive());
System.out.println("Main thread exiting.");
}
}

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. A monitor is an object that is used as a
mutually exclusive lock. Only one thread can own a monitor at a given time. When a thread
acquires a lock, it is said to have entered the monitor. All other threads attempting to enter the
locked monitor will be suspended until the first thread exits the monitor. These other threads are
said to be waiting for the monitor. A thread that owns a monitor can reenter the same monitor if
it so desires.
Using Synchronized Methods
Synchronization is easy in Java, because all objects have their own implicit monitor associated
with them. To enter an object‘s monitor, just call a method that has been modified with the
synchronized keyword.
To understand the need for synchronization, let‘s begin with a simple example that does not use
it—but should. The following program has three simple classes. The first one, Callme, has a
single method named call( ). The call( ) method takes a String parameter called msg. This
method tries to print the msg string inside of square brackets. The interesting thing to notice is
that after call( ) prints the opening bracket and the msg string, it calls Thread.sleep(1000),
which pauses the current thread for one second.
The constructor of the next class, Caller, takes a reference to an instance of the Callme class
and a String, which are stored in target and msg, respectively. The constructor also creates a
new thread that will call this object‘s run( ) method. The thread is started immediately. The run(
) method of Caller calls the call( ) method on the target instance of Callme, passing in the msg
string. Finally, the Synch class starts by creating a single instance of Callme, and three instances
of Caller, each with a unique message string. The same instance of Callme is passed to each
Caller.

// This program is not synchronized.


class Callme {
void call(String msg) {
Department of CSE / Siddharth Group of Institutions, Puttur 77
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

System.out.print("[" + msg);
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
System.out.println("Interrupted");
}
System.out.println("]");
}
}
class Caller implements Runnable {
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s) {
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
public void run() {
target.call(msg);
}
}
class Synch {
public static void main(String args[]) {
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
// wait for threads to end
try {
ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch(InterruptedException e) {
System.out.println("Interrupted");
}
}
}
Here is the output produced by this program:
Hello[Synchronized[World]]
The synchronized Statement
While creating synchronized methods within classes that you create is an easy and effective
means of achieving synchronization, it will not work in all cases. To understand why, consider
the following. Imagine that you want to synchronize access to objects of a class that was not
designed for multithreaded access. That is, the class does not use synchronized methods.

Department of CSE / Siddharth Group of Institutions, Puttur 78


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

This is the general form of the synchronized statement:


synchronized(object) {
// statements to be synchronized
}
Here, object is a reference to the object being synchronized. A synchronized block ensures that a
call to a method that is a member of object occurs only after the current thread has successfully
entered object‘s monitor.
// This program uses a synchronized block.
class Callme {
void call(String msg) {
System.out.print("[" + msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
System.out.println("]");
}
}
class Caller implements Runnable {
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s) {
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
// synchronize calls to call()
public void run() {
synchronized(target) { // synchronized block
target.call(msg);
}
}
}
class Synch1 {
public static void main(String args[]) {
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
// wait for threads to end
try {
ob1.t.join();
ob2.t.join();
ob3.t.join();
Department of CSE / Siddharth Group of Institutions, Puttur 79
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

} catch(InterruptedException e) {
System.out.println("Interrupted");
}
}
}

STRING HANDLING
In Java, a string is an object that represents a sequence of characters or char values. The
java.lang.String class is used to create a Java string object.
There are two ways to create a String object:
1. By string literal : Java String literal is created by using double quotes.
For Example: String s=―Welcome‖;
2. By new keyword : Java String is created by using a keyword ―new‖.
For example:
String s=new String(―Welcome‖);
It creates two objects (in String pool and in heap) and one reference variable where the variable
‗s‘ will refer to the object in the heap.

Java String Methods


1) Java String length(): The Java String length() method tells the length of the string. It returns
count of total number of characters present in the String. For example:
public class Example{
public static void main(String args[]{
String s1="hello";
String s2="whatsup";
System.out.println("string length is: "+s1.length());
System.out.println("string length is: "+s2.length());
}}

Here, String length() function will return the length 5 for s1 and 7 for s2 respectively.
2) Java String compareTo(): The Java String compareTo() method compares the given string
with current string. It is a method of ‗Comparable‘ interface which is implemented by String
class. Don‘t worry, we will be learning about String interfaces later. It either returns positive
number, negative number or 0. For example:
public class CompareToExample{
public static void main(String args[]){
String s1="hello";
String s2="hello";
String s3="hemlo";
String s4="flag";
System.out.println(s1.compareTo(s2)); // 0 because both are equal
System.out.println(s1.compareTo(s3)); //-1 because "l" is only one time lower than "m"
System.out.println(s1.compareTo(s4)); // 2 because "h" is 2 times greater than "f"
}}
3) Java String concat() : The Java String concat() method combines a specific string at the end
of another string and ultimately returns a combined string. It is like appending another string.
For example:
Department of CSE / Siddharth Group of Institutions, Puttur 80
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

public class ConcatExample{


public static void main(String args[]){
String s1="hello";
s1=s1.concat("how are you");
System.out.println(s1);
}}
4) Java String IsEmpty() : This method checks whether the String contains anything or not. If
the java String is Empty, it returns true else false. For example:
public class IsEmptyExample{
public static void main(String args[]){
String s1="";
String s2="hello";
System.out.println(s1.isEmpty()); // true
System.out.println(s2.isEmpty()); // false
}}
5) Java String Trim() : The java string trim() method removes the leading and trailing spaces.
It checks the unicode value of space character (‗u0020‘) before and after the string. If it exists,
then removes the spaces and return the omitted string. For example:
public class StringTrimExample{
public static void main(String args[]){
String s1=" hello ";
System.out.println(s1+"how are you"); // without trim()
System.out.println(s1.trim()+"how are you"); // with trim()
}}
6) Java String toLowerCase() : The java string toLowerCase() method converts all the
characters of the String to lower case. For example:
public class StringLowerExample{
public static void main(String args[]){
String s1="HELLO HOW Are You?”;
String s1lower=s1.toLowerCase();
System.out.println(s1lower);}
}
7) Java String toUpper() : The Java String toUpperCase() method converts all the characters of
the String to upper case. For example:
public class StringUpperExample{
public static void main(String args[]){
String s1="hello how are you";
String s1upper=s1.toUpperCase();
System.out.println(s1upper);
}}
8) Java String ValueOf(): This method converts different types of values into string.Using this
method, you can convert int to string, long to string, Boolean to string, character to string, float
to string, double to string, object to string and char array to string. The signature or syntax of
string valueOf() method is given below:
public static String valueOf(boolean b)
public static String valueOf(char c)
public static String valueOf(char[] c)
Department of CSE / Siddharth Group of Institutions, Puttur 81
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

public static String valueOf(int i)


public static String valueOf(long l)
public static String valueOf(float f)
public static String valueOf(double d)
public static String valueOf(Object o)

public class StringValueOfExample{


public static void main(String args[]){
int value=20;
String s1=String.valueOf(value);
System.out.println(s1+17); //concatenating string with 10
}}
9) Java String replace(): The Java String replace() method returns a string, replacing all the old
characters or CharSequence to new characters. There are 2 ways to replace methods in a Java
String.

public class ReplaceExample1{


public static void main(String args[]){
String s1="hello how are you";
String replaceString=s1.replace('h','t');
System.out.println(replaceString); }}

10) Java String contains() :The java string contains() method searches the sequence of
characters in the string. If the sequences of characters are found, then it returns true otherwise
returns false. For example:
class ContainsExample{
public static void main(String args[]){
String name=" hello how are you doing";
System.out.println(name.contains("how are you")); // returns true
System.out.println(name.contains("hello")); // returns true
System.out.println(name.contains("fine")); // returns false
}}
11) Java String equals() : The Java String equals() method compares the two given strings on
the basis of content of the string i.e Java String representation. If all the characters are matched,
it returns true else it will return false. For example:
public class EqualsExample{
public static void main(String args[]){
String s1="hello";
String s2="hello";
String s3="hi";
System.out.println(s1.equalsIgnoreCase(s2)); // returns true
System.out.println(s1.equalsIgnoreCase(s3)); // returns false
}
}
12) Java String equalsIgnoreCase(): This method compares two string on the basis of content
but it does not check the case like equals() method. In this method, if the characters match, it
returns true else false. For example:
Department of CSE / Siddharth Group of Institutions, Puttur 82
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

public class EqualsIgnoreCaseExample{


public static void main(String args[]){
String s1="hello";
String s2="HELLO";
String s3="hi";
System.out.println(s1.equalsIgnoreCase(s2)); // returns true
System.out.println(s1.equalsIgnoreCase(s3)); // returns false
}}

13) Java String toCharArray(): This method converts the string into a character array i.e first it
will calculate the length of the given Java String including spaces and then create an array of
char type with the same content. For example:

StringToCharArrayExample{
public static void main(String args[]){
String s1="Welcome to Edureka";
char[] ch=s1.toCharArray();
for(int i=0;i<ch.length;i++){
System.out.print(ch[i]);
}}}

14) Java StringGetBytes() : The Java string getBytes() method returns the sequence of bytes or
you can say the byte array of the string. For example:

public class StringGetBytesExample {


public static void main(String args[]){
String s1="ABC";
byte[] b=s1.getBytes();
for(int i=0;i<b.length;i++){
System.out.println(b[i]);
}
}}

15) Java String IsEmpty() : This method checks whether the String is empty or not. If the
length of the String is 0, it returns true else false. For example:

public class IsEmptyExample{


public static void main(String args[]) {
String s1="";
String s2="hello";
System.out.prinltn(s1.isEmpty()); // returns true
System.out.prinltn(s2.isEmpty()); // returns false
}}

16) Java String endsWith() : The Java String endsWith() method checks if this string ends with
the given suffix. If it returns with the given suffix, it will return true else returns false. For
example:
Department of CSE / Siddharth Group of Institutions, Puttur 83
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

public class EndsWithExample{


public static void main(String args[]) {
String s1="hello how are you”;
System.out.println(s1.endsWith("u")); // returns true
System.out.println(s1.endsWith("you")); // returns true
System.out.println(s1.endsWith("how")); // returns false
}}

Department of CSE / Siddharth Group of Institutions, Puttur 84


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

UNIT- IV
GENERICS
Generics- A simple Generic Example-General form of Generic class-Generic Interfaces
Collections overview, Collection class, Collection interfaces.
Introducing File Handling –File handling in java –Stream –Java File Method –File Operation
in Java-Create file –Write to a file –Read from a file.

A SIMPLE GENERIC EXAMPLE


enerics means parameterized types. The idea is to allow type (Integer, String, … etc, and user-
defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is
possible to create classes that work with different data types.
An entity such as class, interface, or method that operates on a parameterized type is called
generic entity.

Why Generics?
Object is the superclass of all other classes and Object reference can refer to any type object.
These features lack type safety. Generics adds that type safety feature.
// A Simple Java program to show working of user defined
// Generic classes

// We use < > to specify Parameter type


class Test<T>
{
// An object of type T is declared
T obj;
Test(T obj) { this.obj = obj; } // constructor
public T getObject() { return this.obj; }
}

// Driver class to test above


class Main
{
public static void main (String[] args)
{
// instance of Integer type
Test <Integer> iObj = new Test<Integer>(15);
System.out.println(iObj.getObject());

// instance of String type


Test <String> sObj = new Test<String>("Java");
System.out.println(sObj.getObject());
}
}
Output:
15
Java
Department of CSE / Siddharth Group of Institutions, Puttur 85
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

GENERAL FORM OF GENERIC CLASS


A generic class declaration looks like a non-generic class declaration, except that the class name
is followed by a type parameter section.

As with generic methods, the type parameter section of a generic class can have one or more
type parameters separated by commas. These classes are known as parameterized classes or
parameterized types because they accept one or more parameters.

Example
Following example illustrates how we can define a generic class –
// A Simple Java program to show multiple
// type parameters in Java Generics

// We use < > to specify Parameter type


class Test<T, U>
{
T obj1; // An object of type T
U obj2; // An object of type U

// constructor
Test(T obj1, U obj2)
{
this.obj1 = obj1;
this.obj2 = obj2;
}

// To print objects of T and U


public void print()
{
System.out.println(obj1);
System.out.println(obj2);
}
}

// Driver class to test above


class Main
{
public static void main (String[] args)
{
Test <String, Integer> obj =
new Test<String, Integer>("Java", 15);
obj.print();
}
}
Output:
Java
15
Department of CSE / Siddharth Group of Institutions, Puttur 86
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

GENERIC INTERFACES COLLECTIONS OVERVIEW


Java provided ad hoc classes such as Dictionary, Vector, Stack, and Properties to store and
manipulate groups of objects. Although these classes were quite useful, they lacked a central,
unifying theme. Thus, the way that you used Vector was different from the way that you used
Properties.

The collections framework was designed to meet several goals, such as −

 The framework had to be high-performance. The implementations for the fundamental


collections (dynamic arrays, linked lists, trees, and hashtables) were to be highly efficient.
 The framework had to allow different types of collections to work in a similar manner and
with a high degree of interoperability.
 The framework had to extend and/or adapt a collection easily.
The entire collections framework is designed around a set of standard interfaces. Several
standard implementations such as LinkedList, HashSet, and TreeSet, of these interfaces are
provided that you may use as-is and you may also implement your own collection, if you choose.
A collections framework is a unified architecture for representing and manipulating collections.
All collections frameworks contain the following –
 Interfaces − These are abstract data types that represent collections. Interfaces allow
collections to be manipulated independently of the details of their representation. In object-
oriented languages, interfaces generally form a hierarchy.
 Implementations, i.e., Classes − These are the concrete implementations of the collection
interfaces. In essence, they are reusable data structures.
 Algorithms − These are the methods that perform useful computations, such as searching and
sorting, on objects that implement collection interfaces. The algorithms are said to be
polymorphic: that is, the same method can be used on many different implementations of the
appropriate collection interface.

COLLECTION CLASS
Java provides a set of standard collection classes that implement Collection interfaces. Some of
the classes provide full implementations that can be used as-is and others are abstract class,
providing skeletal implementations that are used as starting points for creating concrete
collections.

The standard collection classes are summarized in the following table –


Sr.No. Class & Description

1 AbstractCollection
Implements most of the Collection interface.

2 AbstractList
Extends AbstractCollection and implements most of the List interface.

3 AbstractSequentialList
Extends AbstractList for use by a collection that uses sequential rather than random
access of its elements.

Department of CSE / Siddharth Group of Institutions, Puttur 87


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

4 LinkedList
Implements a linked list by extending AbstractSequentialList.

5 ArrayList
Implements a dynamic array by extending AbstractList.

6 AbstractSet
Extends AbstractCollection and implements most of the Set interface.

7 HashSet
Extends AbstractSet for use with a hash table.

8 LinkedHashSet
Extends HashSet to allow insertion-order iterations.

9 TreeSet
Implements a set stored in a tree. Extends AbstractSet.

10 AbstractMap
Implements most of the Map interface.

11 HashMap
Extends AbstractMap to use a hash table.

12 TreeMap
Extends AbstractMap to use a tree.

13 WeakHashMap
Extends AbstractMap to use a hash table with weak keys.

14 LinkedHashMap
Extends HashMap to allow insertion-order iterations.

15 IdentityHashMap
Extends AbstractMap and uses reference equality when comparing documents.
The LinkedList class extends AbstractSequentialList and implements the List interface. It
provides a linked-list data structure.

Following are the constructors supported by the LinkedList class.


Apart from the methods inherited from its parent classes, LinkedList defines following methods

Sr.No. Method & Description

1 void add(int index, Object element)


Inserts the specified element at the specified position index in this list. Throws
IndexOutOfBoundsException if the specified index is out of range (index < 0 || index
> size()).

2 boolean add(Object o)
Appends the specified element to the end of this list.

Department of CSE / Siddharth Group of Institutions, Puttur 88


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

3 boolean addAll(Collection c)
Appends all of the elements in the specified collection to the end of this list, in the
order that they are returned by the specified collection's iterator. Throws
NullPointerException if the specified collection is null.

4 boolean addAll(int index, Collection c)


Inserts all of the elements in the specified collection into this list, starting at the
specified position. Throws NullPointerException if the specified collection is null.

5 void addFirst(Object o)
Inserts the given element at the beginning of this list.

6 void addLast(Object o)
Appends the given element to the end of this list.

7 void clear()
Removes all of the elements from this list.

8 Object clone()
Returns a shallow copy of this LinkedList.

9 boolean contains(Object o)
Returns true if this list contains the specified element. More formally, returns true if
and only if this list contains at least one element e such that (o==null ? e==null :
o.equals(e)).

10 Object get(int index)


Returns the element at the specified position in this list. Throws
IndexOutOfBoundsException if the specified index is out of range (index < 0 || index
>= size()).

11 Object getFirst()
Returns the first element in this list. Throws NoSuchElementException if this list is
empty.

12 Object getLast()
Returns the last element in this list. Throws NoSuchElementException if this list is
empty.

13 int indexOf(Object o)
Returns the index in this list of the first occurrence of the specified element, or -1 if
the list does not contain this element.

14 int lastIndexOf(Object o)
Returns the index in this list of the last occurrence of the specified element, or -1 if the
list does not contain this element.

15 ListIterator listIterator(int index)


Returns a list-iterator of the elements in this list (in proper sequence), starting at the
specified position in the list. Throws IndexOutOfBoundsException if the specified

Department of CSE / Siddharth Group of Institutions, Puttur 89


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

index is out of range (index < 0 || index >= size()).

16 Object remove(int index)


Removes the element at the specified position in this list. Throws
NoSuchElementException if this list is empty.

17 boolean remove(Object o)
Removes the first occurrence of the specified element in this list. Throws
NoSuchElementException if this list is empty. Throws IndexOutOfBoundsException
if the specified index is out of range (index < 0 || index >= size()).

18 Object removeFirst()
Removes and returns the first element from this list. Throws
NoSuchElementException if this list is empty.

19 Object removeLast()
Removes and returns the last element from this list. Throws NoSuchElementException
if this list is empty.

20 Object set(int index, Object element)


Replaces the element at the specified position in this list with the specified element.
Throws IndexOutOfBoundsException if the specified index is out of range (index < 0
|| index >= size()).

21 int size()
Returns the number of elements in this list.

22 Object[] toArray()
Returns an array containing all of the elements in this list in the correct order. Throws
NullPointerException if the specified array is null.

23 Object[] toArray(Object[] a)
Returns an array containing all of the elements in this list in the correct order; the
runtime type of the returned array is that of the specified array.

import java.util.*;
public class LinkedListDemo {

public static void main(String args[]) {


// create a linked list
LinkedList ll = new LinkedList();

// add elements to the linked list


ll.add("F");
ll.add("B");
ll.add("D");
ll.add("E");
ll.add("C");
ll.addLast("Z");
Department of CSE / Siddharth Group of Institutions, Puttur 90
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

ll.addFirst("A");
ll.add(1, "A2");
System.out.println("Original contents of ll: " + ll);

// remove elements from the linked list


ll.remove("F");
ll.remove(2);
System.out.println("Contents of ll after deletion: " + ll);

// remove first and last elements


ll.removeFirst();
ll.removeLast();
System.out.println("ll after deleting first and last: " + ll);

// get and set a value


Object val = ll.get(2);
ll.set(2, (String) val + " Changed");
System.out.println("ll after change: " + ll);
}
}
This will produce the following result −
Output
Original contents of ll: [A, A2, F, B, D, E, C, Z]
Contents of ll after deletion: [A, A2, D, E, C, Z]
ll after deleting first and last: [A2, D, E, C]
ll after change: [A2, D, E Changed, C]

COLLECTION INTERFACES
The collections framework defines several interfaces. This section provides an overview of each
interface –

Sr.No. Interface & Description

1 The Collection Interface


This enables you to work with groups of objects; it is at the top of the collections
hierarchy.

2 The List Interface


This extends Collection and an instance of List stores an ordered collection of
elements.

3 The Set
This extends Collection to handle sets, which must contain unique elements.

4 The SortedSet
This extends Set to handle sorted sets.

5 The Map

Department of CSE / Siddharth Group of Institutions, Puttur 91


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

This maps unique keys to values.

6 The Map.Entry
This describes an element (a key/value pair) in a map. This is an inner class of Map.

7 The SortedMap
This extends Map so that the keys are maintained in an ascending order.

8 The Enumeration
This is legacy interface defines the methods by which you can enumerate (obtain one at
a time) the elements in a collection of objects. This legacy interface has been
superceded by Iterator.
The Collection interface is the foundation upon which the collections framework is built. It
declares the core methods that all collections will have. These methods are summarized in the
following table.
Because all collections implement Collection, familiarity with its methods is necessary for a
clear understanding of the framework. Several of these methods can throw
an UnsupportedOperationException.
Sr.No. Method & Description

1 boolean add(Object obj)


Adds obj to the invoking collection. Returns true if obj was added to the
collection. Returns false if obj is already a member of the collection, or if the
collection does not allow duplicates.

2 boolean addAll(Collection c)
Adds all the elements of c to the invoking collection. Returns true if the operation
succeeds (i.e., the elements were added). Otherwise, returns false.

3 void clear( )
Removes all elements from the invoking collection.

4 boolean contains(Object obj)


Returns true if obj is an element of the invoking collection. Otherwise, returns
false.

5 boolean containsAll(Collection c)
Returns true if the invoking collection contains all elements of c. Otherwise,
returns false.

6 boolean equals(Object obj)


Returns true if the invoking collection and obj are equal. Otherwise, returns false.

7 int hashCode( )
Returns the hash code for the invoking collection.

8 boolean isEmpty( )
Returns true if the invoking collection is empty. Otherwise, returns false.

9 Iterator iterator( )

Department of CSE / Siddharth Group of Institutions, Puttur 92


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

Returns an iterator for the invoking collection.

10 boolean remove(Object obj)


Removes one instance of obj from the invoking collection. Returns true if the
element was removed. Otherwise, returns false.

11 boolean removeAll(Collection c)
Removes all elements of c from the invoking collection. Returns true if the
collection changed (i.e., elements were removed). Otherwise, returns false.

12 boolean retainAll(Collection c)
Removes all elements from the invoking collection except those in c. Returns true
if the collection changed (i.e., elements were removed). Otherwise, returns false.

13 int size( )
Returns the number of elements held in the invoking collection.

14 Object[ ] toArray( )
Returns an array that contains all the elements stored in the invoking collection.
The array elements are copies of the collection elements.

15 Object[ ] toArray(Object array[ ])


Returns an array containing only those collection elements whose type matches
that of array.

Example
import java.util.*;
public class CollectionsDemo {

public static void main(String[] args) {


// ArrayList
List a1 = new ArrayList();
a1.add("Zara");
a1.add("Mahnaz");
a1.add("Ayan");
System.out.println(" ArrayList Elements");
System.out.print("\t" + a1);

// LinkedList
List l1 = new LinkedList();
l1.add("Zara");
l1.add("Mahnaz");
l1.add("Ayan");
System.out.println();
System.out.println(" LinkedList Elements");
System.out.print("\t" + l1);

// HashSet

Department of CSE / Siddharth Group of Institutions, Puttur 93


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

Set s1 = new HashSet();


s1.add("Zara");
s1.add("Mahnaz");
s1.add("Ayan");
System.out.println();
System.out.println(" Set Elements");
System.out.print("\t" + s1);

// HashMap
Map m1 = new HashMap();
m1.put("Zara", "8");
m1.put("Mahnaz", "31");
m1.put("Ayan", "12");
m1.put("Daisy", "14");
System.out.println();
System.out.println(" Map Elements");
System.out.print("\t" + m1);
}
}
Output
ArrayList Elements
[Zara, Mahnaz, Ayan]
LinkedList Elements
[Zara, Mahnaz, Ayan]
Set Elements
[Ayan, Zara, Mahnaz]
Map Elements
{Daisy = 14, Ayan = 12, Zara = 8, Mahnaz = 31}

INTRODUCING FILE HANDLING

FILE HANDLING IN JAVA


File handling in Java implies reading from and writing data to a file. The File class from the
java.io package, allows us to work with different formats of files. In order to use the File class,
you need to create an object of the class and specify the filename or directory name.

For example:
import java.io.File
File obj = new File("filename.txt");
Java uses the concept of a stream to make I/O operations on a file. So let‘s now understand what
is a Stream in Java.

WHAT IS A STREAM?
In Java, Stream is a sequence of data which can be of two types.

Department of CSE / Siddharth Group of Institutions, Puttur 94


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

1. Byte Stream
This mainly incorporates with byte data. When an input is provided and executed with byte data,
then it is called the file handling process with a byte stream.
2. Character Stream
Character Stream is a stream which incorporates with characters. Processing of input data with
character is called the file handling process with a character stream.
Now that you know what is a stream, let‘s dive deeper into this article on File Handling in Java
and know the various methods that are useful for operations on the files like creating, reading
and writing.

JAVA FILE METHODS


Below table depicts the various methods that are used for performing operations on Java files.
Method Type Description
canRead() Boolean It tests whether the file is readable or not
canWrite() Boolean It tests whether the file is writable or not
createNewFile() Boolean This method creates an empty file
delete() Boolean Deletes a file
exists() Boolean It tests whether the file exists
getName() String Returns the name of the file
getAbsolutePath() String Returns the absolute pathname of the file
length() Long Returns the size of the file in bytes
list() String[] Returns an array of the files in the directory
mkdir() Boolean Creates a directory

FILE OPERATION IN JAVA


Basically, you can perform four operations on a file. They are as follows:
1. Create a File
2. Get File Information
3. Write To a File
4. Read from a File
Now, let‘s get into the details of each of these operations

1. CREATE A FILE
In this case, to create a file you can use the createNewFile() method. This method returns true if
the file was successfully created, and false if the file already exists.
package FileHandling;

// Import the File class


import java.io.File;

// Import the IOException class to handle errors


import java.io.IOException;

public class CreateFile {


public static void main(String[] args) {

Department of CSE / Siddharth Group of Institutions, Puttur 95


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

try {
// Creating an object of a file
File myObj = new File("D:FileHandlingNewFilef1.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}

Output:
File created: NewFilef1.txt

2. GET FILE INFORMATION


Let‘s see how to get file information using various methods with the help of below example code
package FileHandling;
import java.io.File; // Import the File class

public class FileInformation {


public static void main(String[] args) {
// Creating an object of a file
File myObj = new File("NewFilef1.txt");
if (myObj.exists()) {
// Returning the file name
System.out.println("File name: " + myObj.getName());

// Returning the path of the file


System.out.println("Absolute path: " + myObj.getAbsolutePath());

// Displaying whether the file is writable


System.out.println("Writeable: " + myObj.canWrite());

// Displaying whether the file is readable or not


System.out.println("Readable " + myObj.canRead());

// Returning the length of the file in bytes


System.out.println("File size in bytes " + myObj.length());
} else {
System.out.println("The file does not exist.");
}
}
}
Department of CSE / Siddharth Group of Institutions, Puttur 96
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

Output:
File name: NewFilef1.txt
Absolute path: D:FileHandlingNewFilef1.txt
Writable: true
Readable true
File size in bytes 52

3. WRITE TO A FILE
In the following example, I have used the FileWriter class together with its write() method to
write some text into the file. Let‘s understand this with the help of a code.
package FileHandling;

// Import the FileWriter class


import java.io.FileWriter;

// Import the IOException class to handle errors


import java.io.IOException;

public class WriteToFile {


public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("D:FileHandlingNewFilef1.txt");
// Writes this content into the specified file
myWriter.write(Java is the prominent programming language of the millenium!");

// Closing is necessary to retrieve the resources allocated


myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Output:
Successfully wrote to the file

4. READ FROM A FILE


In the following example, I have used the Scanner class to read the contents of the text file.
package FileHandling;

// Import the File class


import java.io.File;

// Import this class to handle errors


import java.io.FileNotFoundException;
Department of CSE / Siddharth Group of Institutions, Puttur 97
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

// Import the Scanner class to read text files


import java.util.Scanner;

public class ReadFromFile {


public static void main(String[] args) {
try {
// Creating an object of the file for reading the data
File myObj = new File("D:FileHandlingNewFilef1.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}

Output:
Java is the prominent programming language of the millennium!

Department of CSE / Siddharth Group of Institutions, Puttur 98


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

UNIT V

Introducing the AWT - Using AWT Controls-Layout Managers -Introducing Swing -Exploring
Swing.
Introducing Java8 Features –Lambda Expression –Method references –forEach() method -
Method and Constructor reference by double colon(::) operator - Stream API –Date & Time
API.

INTRODUCING THE AWT - USING AWT CONTROLS:

Java AWT(Abstract Window Toolkit) controls are the controls that are used to design graphical
user interfaces or web applications. To make an effective GUI, Java provides java.awt package
that supports various AWT controls like Label, Button, CheckBox, CheckBox Group, List, Text
Field, Text Area, Choice, Canvas, Image, Scrollbar, Dialog, File Dialog, etc that creates or draw
various components on web and manage the GUI based application.

Java AWT Hierarchy


The hierarchy of Java AWT classes are given below

Container
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such as
Frame, Dialog and Panel.

Department of CSE / Siddharth Group of Institutions, Puttur 99


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

Window
The window is the container that have no borders and menu bars. You must use frame, dialog or
another window for creating a window.

Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.

Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.

1. Label
A label is a user for placing text inside the container. A label is used only for inputting text. The
label does not imply that the text can be altered or it can be used as a button which can be further
worked upon.
Syntax:
Label n=new Label("Name:",Label.CENTER);

2. Button
This command generates a button in the User Interface. Clicking on the button would move the
command to another page or another web server which is used to show several other outputs in
the user interface page.
Syntax:
a1=new Button("submit");
a2=new Button("cancel");

3. Checkbox
There can be a certain question and the checkbox is used to determine the true or false nature of
the question being asked. If the checkbox is ticked then it means that the said question is true
which if it is unchecked it means that the said question is false. It is basically a true or false state
in Java programming language.
Syntax:
Checkbox checkbox1 = new Checkbox("Hello World");

4. Checkbox Group
As the name implies the checkbox group is a set of checkboxes that are being used in the
programming language. There are many checkboxes that are being used and hence the group of
checkboxes is known as the checkbox group.
Syntax:
CheckboxGroup cb = new CheckboxGroup();
Checkbox checkBox1 = new Checkbox("Hello", cb, true);
checkBox1.setBounds (100,100, 50,50);

5. List

Department of CSE / Siddharth Group of Institutions, Puttur 100


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

The list gives a scrolling list of items for the user. The scrolling list of items is also being set by
the user. The user sets the scrolling list of items such as Fruits, Vegetables, some questionnaire
or other facts.
Syntax:
List l1=new List(4);
l1.setBounds(100,100, 75,75);

6. Text Field
A text field is used for the editing of a particular line of text which can be used within the
programming concept.
Syntax:
na=new TextField(20);

7. Text Area
A text area is used for the editing of multiple lines of text. The only difference between the Text
field and Text area is that Text Field is used for editing a single line of text within the user
interface while a Text Area is used for editing multiple lines of text.
Syntax:
TextArea area=new TextArea("Welcome to the universe");
area.setBounds(10,30, 300,300);

8. Choice
A choice, as the name implies, shows the various options and the choice that is selected is shown
in the top menu bar of the screen.
Syntax:
Choice c=new Choice();
c.setBounds(100,100, 75,75);
c.add("Subject 1");
c.add("Subject 2");
c.add("Subject 3");
c.add("Subject 4");
c.add("Subject 5");

9. Canvas
In the canvas space, there can be an input being given by the user or the user can draw
something on the Canvas space being given.
Syntax:
f.add(new MyCanvas());
f.setLayout(null);
f.setSize(400, 400);
f.setVisible(true);

10. Image
There can be a single image or multiple images within a UI. There can be a button being
associated with an image and when it is clicked it can produce some functionality.
Syntax:
Image i=t.getImage("pic2.gif");
Department of CSE / Siddharth Group of Institutions, Puttur 101
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

11. Scroll Bar


The scroll bar like a normal one is used to scroll or move from a varied range of values. The user
selects one value from those range of values.
Syntax:
Scrollbar s=new Scrollbar();
s.setBounds(100,100, 50,100);

12. Dialog
The dialog is used to take some form of input from the user and produce it in a sequential
manner.
Syntax:
d = new Dialog(f , "Hello World", true);

13. File Dialog


From a file dialog, a user can select a file which he/she wishes to use.
Syntax:
FileDialog(Dialog parent)

Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing
Button component on the Frame.

import java.awt.*;
class First extends Frame
{
First()
{
Button b=new Button("click me");
b.setBounds(30,100,80,30); // setting button position
setBounds(xcoordinate,ycoordinate,width, hight);
add(b); //adding button into frame
setSize(300,300); //frame size 300 width and 300 height
setLayout(null); //no layout manager
setVisible(true); //now frame will be visible, by default not visible
}
public static void main(String args[]){
First f=new First();
}}

Department of CSE / Siddharth Group of Institutions, Puttur 102


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

INTRODUCING SWING
Swing in java is part of Java foundation class which is lightweight and platform independent. It
is used for creating window based applications. It includes components like button, scroll bar,
text field etc. Putting together all these components makes a graphical user interface.

What is Swing In Java?


Swing in Java is a lightweight GUI toolkit which has a wide variety of widgets for building
optimized window based applications. It is a part of the JFC( Java Foundation Classes). It is
build on top of the AWT API and entirely written in java. It is platform independent unlike
AWT and has lightweight components.

It becomes easier to build applications since we already have GUI components like button,
checkbox etc. This is helpful because we do not have to start from the scratch.

Container Class
Any class which has other components in it is called as a container class. For building GUI
applications at least one container class is necessary.

Following are the three types of container classes:


 Panel – It is used to organize components on to a window
 Frame – A fully functioning window with icons and titles
 Dialog – It is like a pop up window but not fully functional like the frame

Department of CSE / Siddharth Group of Institutions, Puttur 103


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

AWT Swing

Java AWT is an API to develop GUI Swing is a part of Java Foundation Classes
1. applications in Java and is used to create various applications.

The components of Java AWT are The components of Java Swing are light
2. heavy weighted. weighted.

Java AWT has comparatively less Java Swing has more functionality as
3. functionality as compared to Swing. compared to AWT.

The execution time of AWT is more The execution time of Swing is less than
4. than Swing. AWT.

The components of Java AWT are The components of Java Swing are platform
5. platform dependent. independent.

6. MVC pattern is not supported by AWT. MVC pattern is supported by Swing.

AWT provides comparatively less


7. powerful components. Swing provides more powerful components.

JButton Class
It is used to create a labelled button. Using the ActionListener it will result in some action when
the button is pushed. It inherits the AbstractButton class and is platform independent.

Department of CSE / Siddharth Group of Institutions, Puttur 104


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

Example:
import javax.swing.*;
public class example
{
public static void main(String args[])
{
JFrame a = new JFrame("example");
JButton b = new JButton("click me");
b.setBounds(40,90,85,20);
a.add(b);
a.setSize(300,300);
a.setLayout(null);
a.setVisible(true);
}
}
import java.awt.*;
class First extends Frame
{
First()
{
Button b=new Button("click me");
b.setBounds(30,100,80,30); // setting button position
setBounds(xcoordinate,ycoordinate,width, hight);
add(b); //adding button into frame
setSize(300,300); //frame size 300 width and 300 height
setLayout(null); //no layout manager
setVisible(true); //now frame will be visible, by default not visible
}
public static void main(String args[]){
First f=new First();
}}

Output:

JTextField Class
It inherits the JTextComponent class and it is used to allow editing of single line text.

Department of CSE / Siddharth Group of Institutions, Puttur 105


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

Example:
import javax.swing.*;
public class example{
public static void main(String args[]) {
JFrame a = new JFrame("example");
JTextField b = new JTextField("edureka");
b.setBounds(50,100,200,30);
a.add(b);
a.setSize(300,300);
a.setLayout(null);
a.setVisible(true);
}
}

JScrollBar Class
It is used to add scroll bar, both horizontal and vertical.

import javax.swing.*;
class example{
example(){
JFrame a = new JFrame("example");
JScrollBar b = new JScrollBar();
b.setBounds(90,90,40,90);
a.add(b);
a.setSize(300,300);
a.setLayout(null);
a.setVisible(true);
}
public static void main(String args[]){
new example();
}
}

Output:

Department of CSE / Siddharth Group of Institutions, Puttur 106


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

JPanel Class
It inherits the JComponent class and provides space for an application which can attach any
other component.
import java.awt.*;
import javax.swing.*;
public class Example{
Example(){
JFrame a = new JFrame("example");
JPanel p = new JPanel();
p.setBounds(40,70,200,200);
JButton b = new JButton("click me");
b.setBounds(60,50,80,40);
p.add(b);
a.add(p);
a.setSize(400,400);
a.setLayout(null);
a.setVisible(true);
}
public static void main(String args[])
{
new Example();
}
}

JMenu Class

Department of CSE / Siddharth Group of Institutions, Puttur 107


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

It inherits the JMenuItem class, and is a pull down menu component which is displayed from the
menu bar.

import javax.swing.*;
class Example{
JMenu menu;
JMenuItem a1,a2;
Example()
{
JFrame a = new JFrame("Example");
menu = new JMenu("options");
JMenuBar m1 = new JMenuBar();
a1 = new JMenuItem("example");
a2 = new JMenuItem("example1");
menu.add(a1);
menu.add(a2);
m1.add(menu);
a.setJMenuBar(m1);
a.setSize(400,400);
a.setLayout(null);
a.setVisible(true);
}
public static void main(String args[])
{
new Example();
}
}

JList Class
It inherits JComponent class, the object of JList class represents a list of text items.

import javax.swing.*;
public class Example
{
Example(){
JFrame a = new JFrame("example");
DefaultListModel<String> l = new DefaultListModel< >();
l.addElement("first item");
l.addElement("second item");
Department of CSE / Siddharth Group of Institutions, Puttur 108
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

JList<String> b = new JList< >(l);


b.setBounds(100,100,75,75);
a.add(b);
a.setSize(400,400);
a.setVisible(true);
a.setLayout(null);
}
public static void main(String args[])
{
new Example();
}
}

JLabel Class
It is used for placing text in a container. It also inherits JComponent class.
import javax.swing.*;
public class Example{
public static void main(String args[])
{
JFrame a = new JFrame("example");
JLabel b1;
b1 = new JLabel("edureka");
b1.setBounds(40,40,90,20);
a.add(b1);
a.setSize(400,400);
a.setLayout(null);
a.setVisible(true);
}}

JComboBox Class
It inherits the JComponent class and is used to show pop up menu of choices.

import javax.swing.*;
public class Example{

Department of CSE / Siddharth Group of Institutions, Puttur 109


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

JFrame a;
Example(){
a = new JFrame("example");
string courses[] = { "core java","advance java", "java servlet"};
JComboBox c = new JComboBox(courses);
c.setBounds(40,40,90,20);
a.add(c);
a.setSize(400,400);
a.setLayout(null);
a.setVisible(true);
}
public static void main(String args[])
{
new Example();
}
}

Layout Manager
To arrange the components inside a container we use the layout manager. Following are several
layout managers:

 Border layout
 Flow layout
 GridBag layout

Border Layout
The default layout manager for every JFrame is BorderLayout. It places components in upto five
places which is top, bottom, left, right and center.

import java.awt.*;
import javax.swing.*;
public class Border
{
JFrame f; Border()
{
f=new JFrame();
JButton b1=new JButton("NORTH");;
JButton b2=new JButton("SOUTH");;
JButton b3=new JButton("EAST");;

Department of CSE / Siddharth Group of Institutions, Puttur 110


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

JButton b4=new JButton("WEST");;


JButton b5=new JButton("CENTER");;
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{
new Border();
}}

Flow Layout
FlowLayout simply lays the components in a row one after the other, it is the default layout
manager for every JPanel.

import java.awt.*;
import javax.swing.*;
public class MyFlowLayout{
JFrame f;
MyFlowLayout(){
f=new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4"); JButton b5=new JButton("5");
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
Department of CSE / Siddharth Group of Institutions, Puttur 111
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

//setting flow layout of right alignment


f.setSize(300,300);
f.s etVisible(true);
}
public static void main(String[] args) {
new MyFlowLayout();
}}

GridBag Layout
GridBagLayout places the components in a grid which allows the components to span more than
one cell.

import java.awt.*;
import javax.swing.*;
public class MyGridLayout{
JFrame f;
MyGridLayout(){
f=new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
JButton b8=new JButton("8");
JButton b9=new JButton("9");
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.add(b6);
f.add(b7);
f.add(b8);
f.add(b9);
f.setLayout(new GridLayout(3,3));
//setting grid layout of 3 rows and 3 columns

Department of CSE / Siddharth Group of Institutions, Puttur 112


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

f.setSize(300,300);
f.s etVisible(true);
}
public static void main(String[] args) {
new MyGridLayout(); }}

INTRODUCING JAVA8 FEATURES


LAMBDA EXPRESSION
Lambda expressions are an anonymous function, meaning that they have no name or identifier.
They can be passed as a parameter to another function. They are paired with a functional
interface and feature a parameter with an expression that references that parameter.

The syntax of a basic lambda expression is:

parameter -> expression


The expression is used as the code body for the abstract method (a named but empty method)
within the paired functional interface.

Unlike most functions in Java, lambda expressions exist outside of any object‘s scope. This
means they are callable anywhere in the program and can be passed around. In the simplest
terms, lambda expressions allow functions to behave like just another piece of data.
lambda expressions are added in Java 8 and provide below functionalities.

 Enable to treat functionality as a method argument, or code as data.


 A function that can be created without belonging to any class.
 A lambda expression can be passed around as if it was an object and executed on
demand.
// Java program to demonstrate lambda expressions
// to implement a user defined functional interface.

// A sample functional interface (An interface with


// single abstract method
interface FuncInterface
{
// An abstract function

Department of CSE / Siddharth Group of Institutions, Puttur 113


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

void abstractFun(int x);

// A non-abstract (or default) function


default void normalFun()
{
System.out.println("Hello");
}
}

class Test
{
public static void main(String args[])
{
// lambda expression to implement above
// functional interface. This interface
// by default implements abstractFun()
FuncInterface fobj = (int x)->System.out.println(2*x);

// This calls above lambda expression and prints 10.


fobj.abstractFun(5);
}
}

Syntax:
lambda operator -> body
where lambda operator can be:
Zero parameter:
() -> System.out.println("Zero parameter lambda");
One parameter:–
(p) -> System.out.println("One parameter: " + p);
It is not mandatory to use parentheses, if the type of that variable can be inferred from the
context

Multiple parameters :
(p1, p2) -> System.out.println("Multiple parameters: " + p1 + ", " + p2);
Please note: Lambda expressions are just like functions and they accept parameters just like
functions.

// A Java program to demonstrate simple lambda expressions


import java.util.ArrayList;
class Test
{
Department of CSE / Siddharth Group of Institutions, Puttur 114
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

public static void main(String args[])


{
// Creating an ArrayList with elements
// {1, 2, 3, 4}
ArrayList<Integer> arrL = new ArrayList<Integer>();
arrL.add(1);
arrL.add(2);
arrL.add(3);
arrL.add(4);

// Using lambda expression to print all elements


// of arrL
arrL.forEach(n -> System.out.println(n));

// Using lambda expression to print even elements


// of arrL
arrL.forEach(n -> { if (n%2 == 0) System.out.println(n); });
}
}
Output :
1
2
3
4
2
4
A Java program to demonstrate working of lambda expression with two arguments.

// Java program to demonstrate working of lambda expressions


public class Test
{
// operation is implemented using lambda expressions
interface FuncInter1
{
int operation(int a, int b);
}

// sayMessage() is implemented using lambda expressions


// above
interface FuncInter2
{
void sayMessage(String message);
}

// Performs FuncInter1's operation on 'a' and 'b'


private int operate(int a, int b, FuncInter1 fobj)
{
return fobj.operation(a, b);
}

Department of CSE / Siddharth Group of Institutions, Puttur 115


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

public static void main(String args[])


{
// lambda expression for addition for two parameters
// data type for x and y is optional.
// This expression implements 'FuncInter1' interface
FuncInter1 add = (int x, int y) -> x + y;

// lambda expression multiplication for two parameters


// This expression also implements 'FuncInter1' interface
FuncInter1 multiply = (int x, int y) -> x * y;

// Creating an object of Test to call operate using


// different implementations using lambda Expressions
Test tobj = new Test();

// Add two numbers using lambda expression


System.out.println("Addition is " +
tobj.operate(6, 3, add));

// Multiply two numbers using lambda expression


System.out.println("Multiplication is " +
tobj.operate(6, 3, multiply));

// lambda expression for single parameter


// This expression implements 'FuncInter2' interface
FuncInter2 fobj = message ->System.out.println("Hello "

fobj.sayMessage("Geek");
}
}

METHOD REFERENCES
Java provides a new feature called method reference in Java 8. Method reference is used to
refer method of functional interface. It is compact and easy form of lambda expression. Each
time when you are using lambda expression to just referring a method, you can replace your
lambda expression with method reference
Types of Method References
There are following types of method references in java:

1. Reference to a static method.


2. Reference to an instance method.
3. Reference to a constructor.

1. Reference to a static method:


You can refer to static method defined in the class. Following is the syntax and example which
describe the process of referring static method in Java.
Syntax

ContainingClass::staticMethodName
Example 1

Department of CSE / Siddharth Group of Institutions, Puttur 116


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

In the following example, we have defined a functional interface and referring a static method to
it's functional method say().
interface Sayable{
void say();
}
public class MethodReference {
public static void saySomething(){
System.out.println("Hello, this is static method.");
}
public static void main(String[] args) {
// Referring static method
Sayable sayable = MethodReference::saySomething;
// Calling interface method
sayable.say();
}
}
Output:

Hello, this is static method.


Example-2
import java.util.function.BiFunction;
class Arithmetic{
public static int add(int a, int b){
return a+b;
}
}
public class MethodReference3 {
public static void main(String[] args) {
BiFunction<Integer, Integer, Integer>adder = Arithmetic::add;
int result = adder.apply(10, 20);
System.out.println(result);
}
}

2) Reference to an Instance Method


like static methods, you can refer instance methods also. In the following example, we are
describing the process of referring the instance method.

Syntax

containingObject::instanceMethodName
Example 1
In the following example, we are referring non-static methods. You can refer methods by class
object and anonymous object.
interface Sayable{
void say();
}
public class InstanceMethodReference {
public void saySomething(){
System.out.println("Hello, this is non-static method.");
}
public static void main(String[] args) {
InstanceMethodReference methodReference = new InstanceMethodReference();

Department of CSE / Siddharth Group of Institutions, Puttur 117


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

// Creating object
// Referring non-static method using reference
Sayable sayable = methodReference::saySomething;
// Calling interface method
sayable.say();
// Referring non-static method using anonymous object
Sayable sayable2 = new InstanceMethodReference()::saySomething;
// You can use anonymous object also
// Calling interface method
sayable2.say();
}
}
Output:

Hello, this is non-static method.


Hello, this is non-static method

3) Reference to a Constructor
You can refer a constructor by using the new keyword. Here, we are referring constructor with the
help of functional interface.

Syntax

ClassName::new

Example
interface Messageable{
Message getMessage(String msg);
}
class Message{
Message(String msg){
System.out.print(msg);
}
}
public class ConstructorReference {
public static void main(String[] args) {
Messageable hello = Message::new;
hello.getMessage("Hello");
}
}
Output:

Hello

FUNCTIONAL INTERFACE
A functional interface is an interface that contains only one abstract method. They can have only one
functionality to exhibit. From Java 8 onwards, lambda expressions can be used to represent the
instance of a functional interface. A functional interface can have any number of default methods.
Runnable, ActionListener, Comparable are some of the examples of functional interfaces.
Before Java 8, we had to create anonymous inner class objects or implement these interfaces.
// Java program to demonstrate functional interface

class Test
{
Department of CSE / Siddharth Group of Institutions, Puttur 118
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

public static void main(String args[])


{
// create anonymous inner class object
new Thread(new Runnable()
{
@Override
public void run()
{
System.out.println("New thread created");
}
}).start();
}
}
Java 8 onwards, we can assign lambda expression to its functional interface object like this:

// Java program to demonstrate Implementation of


// functional interface using lambda expressions

class Test
{
public static void main(String args[])
{

// lambda expression to create the object


new Thread(()->
{System.out.println("New thread created");}).start();
}
}
@FunctionalInterface Annotation
@FunctionalInterface annotation is used to ensure that the functional interface can‘t have more than
one abstract method. In case more than one abstract methods are present, the compiler flags an
‗Unexpected @FunctionalInterface annotation‘ message. However, it is not mandatory to use this
annotation.
// Java program to demonstrate lamda expressions to implement
// a user defined functional interface.

@FunctionalInterface
interface Square
{
int calculate(int x);
}

class Test
{
public static void main(String args[])
{
int a = 5;

// lambda expression to define the calculate method


Square s = (int x)->x*x;

// parameter passed and return type must be


// same as defined in the prototype
int ans = s.calculate(a);
Department of CSE / Siddharth Group of Institutions, Puttur 119
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

System.out.println(ans);
}
}
java.util.function Package:
The java.util.function package in Java 8 contains many builtin functional interfaces like-

Predicate: The Predicate interface has an abstract method test which gives a Boolean value as a
result for the specified argument. Its prototype is
public interface Predicate
{
public boolean test(T t);
}
BinaryOperator: The BinaryOperator interface has an abstract method apply which takes two
argument and returns a result of same type. Its prototype is
public interface BinaryOperator
{
public T apply(T x, T y);
}
Function: The Function interface has an abstract method apply which takes argument of type T and
returns a result of type R. Its prototype is
public interface Function
{
public R apply(T t);
}

// A simple program to demonstrate the use


// of predicate interface
import java.util.*;
import java.util.function.Predicate;

class Test
{
public static void main(String args[])
{

// create a list of strings


List<String> names =
Arrays.asList("Geek","GeeksQuiz","g1","QA","Geek2");

// declare the predicate type as string and use


// lambda expression to create object
Predicate<String> p = (s)->s.startsWith("G");

// Iterate through the list


for (String st:names)
{
// call the test method
if (p.test(st))
System.out.println(st);
}
}
}

DEFAULT METHOD
Department of CSE / Siddharth Group of Institutions, Puttur 120
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

Java provides a facility to create default methods inside the interface. Methods which are defined
inside the interface and tagged with default are known as default methods. These methods are non-
abstract methods.

Java Default Method Example


In the following example, Sayable is a functional interface that contains a default and an abstract
method. The concept of default method is used to define a method with default implementation. You
can override default method also to provide more specific implementation for the method.

interface Sayable{
// Default method
default void say(){
System.out.println("Hello, this is default method");
}
// Abstract method
void sayMore(String msg);
}
public class DefaultMethods implements Sayable{
public void sayMore(String msg){ // implementing abstract method
System.out.println(msg);
}
public static void main(String[] args) {
DefaultMethods dm = new DefaultMethods();
dm.say(); // calling default method
dm.sayMore("Work is worship"); // calling abstract method

}
}
Output:

Hello, this is default method


Work is worship

STATIC METHOD
You can also define static methods inside the interface. Static methods are used to define utility
methods. The following example explain, how to implement static method in interface?
interface Sayable{
// default method
default void say(){
System.out.println("Hello, this is default method");
}
// Abstract method
void sayMore(String msg);
// static method
static void sayLouder(String msg){
System.out.println(msg);
}
}
public class DefaultMethods implements Sayable{
public void sayMore(String msg){ // implementing abstract method

Department of CSE / Siddharth Group of Institutions, Puttur 121


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

System.out.println(msg);
}
public static void main(String[] args) {
DefaultMethods dm = new DefaultMethods();
dm.say(); // calling default method
dm.sayMore("Work is worship"); // calling abstract method
Sayable.sayLouder("Helloooo..."); // calling static method
}
}

Output:

Hello there
Work is worship
Helloooo...

FOREACH() METHOD
Java provides a new method forEach() to iterate the elements. It is defined in Iterable and Stream
interface. It is a default method defined in the Iterable interface. Collection classes which extends
Iterable interface can use forEach loop to iterate elements.

This method takes a single parameter which is a functional interface. So, you can pass lambda
expression as an argument.
forEach() Signature in Iterable Interface

default void forEach(Consumer<super T>action)

import java.util.ArrayList;
import java.util.List;
public class ForEachExample {
public static void main(String[] args) {
List<String> gamesList = new ArrayList<String>();
gamesList.add("Football");
gamesList.add("Cricket");
gamesList.add("Chess");
gamesList.add("Hocky");
System.out.println("------------Iterating by passing lambda expression--------------");
gamesList.forEach(games -> System.out.println(games));

}
}
Output:
------------Iterating by passing lambda expression--------------
Football
Cricket
Chess
Hocky
Java Stream forEachOrdered() Method
Along with forEach() method, Java provides one more method forEachOrdered(). It is used to
iterate elements in the order specified by the stream.
Singnature:
void forEachOrdered(Consumer<? super T> action)

Java Stream forEachOrdered() Method Example


Department of CSE / Siddharth Group of Institutions, Puttur 122
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

import java.util.ArrayList;
import java.util.List;
public class ForEachOrderedExample {
public static void main(String[] args) {
List<String> gamesList = new ArrayList<String>();
gamesList.add("Football");
gamesList.add("Cricket");
gamesList.add("Chess");
gamesList.add("Hocky");
System.out.println("------------Iterating by passing lambda expression-------------");
gamesList.stream().forEachOrdered(games -> System.out.println(games));
System.out.println("------------Iterating by passing method reference-------------");
gamesList.stream().forEachOrdered(System.out::println);
}

}
Output:

------------Iterating by passing lambda expression---------------


Football
Cricket
Chess
Hocky
------------Iterating by passing method reference---------------
Football
Cricket
Chess
Hocky

METHOD AND CONSTRUCTOR REFERENCE BY DOUBLE COLON(::) OPERATOR

The double colon operator (::) introduced in java 8, also known as method reference operator in
java. It is used to call a method by referring to it with the help of its class/instance. They behave
exactly as the lambda expressions. The only difference it has from lambda expressions is that
this uses direct reference to the method by name instead of providing a delegate to the method.
1. Double Colon Operator and Lambda
Double colon operator (::) also a short hand for lambdas. Let‘s see a very simple example that
print list items.

Using Lambda:
List<String> list = List.of("Peter", "Thomas", "Edvard", "Gerhard");

// print using lambda


list.forEach(item -> System.out.println(item));
Using :: operator :

To concise code and readable, we used Lambda in above example. Java method reference makes
it even more shorter and readable.
// print using :: (method reference operator)
list.forEach(System.out::println);

Department of CSE / Siddharth Group of Institutions, Puttur 123


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

To reference a method or to reference a constructor, we must use double colon operator.


Following are the various scenarios where it can used.
1. Reference to static method.
2. Reference to an instance method of a particular object.
3. Reference to an instance method of an arbitrary object of a particular type
4. Reference to a Constructor

1. Reference to static method.

You can refer to static method defined in the class. Following is the syntax and example which
describe the process of referring static method in Java.
Syntax:
<target class name>::<static method name>
Example with lambda expression
@FunctionalInterface
interface MyFunctionalInterface {

boolean isEvenNumber(int i);


}
public class MethodReferenceDemo {

public static void main(String[] args) {


//Lambda Example
MyFunctionalInterface mi = i -> i%2 == 0;

System.out.println(mi.isEvenNumber(15));//false
System.out.println(mi.isEvenNumber(20));//true
}
}
Same example with reference to a method
@FunctionalInterface
interface MyFunctionalInterface {

boolean isEvenNumber(int i);


}

public class MethodReferenceDemo {

static boolean myImplementation(int i) {

return i%2 == 0;
}

public static void main(String[] args) {

MyFunctionalInterface mi = MethodReferenceDemo::myImplementation;
Department of CSE / Siddharth Group of Institutions, Puttur 124
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

System.out.println(mi.isEvenNumber(15));//false
System.out.println(mi.isEvenNumber(20));//true
}
}
2. Reference to an instance method of a particular object.

Like static methods, you can refer instance methods also. In the following example, we are
describing the process of referring the instance method.
Syntax:
<target class object>::<instance method>

@FunctionalInterface
interface MyFunctionalInterface {

boolean isEvenNumber(int i);


}
public class MethodReferenceDemo {

//instance method
boolean myImplementation(int i) {

return i%2 == 0;
}
public static void main(String[] args) {

MethodReferenceDemo demo = new MethodReferenceDemo();


MyFunctionalInterface mi = demo::myImplementation;

MyFunctionalInterface mi2 = new MethodReferenceDemo()::myImplementation;

System.out.println(mi.isEvenNumber(15));//false
System.out.println(mi2.isEvenNumber(20));//true
}
}
3. Reference to an instance method of an arbitrary object of a particular type

Like static methods, you can refer instance methods also. In the following example, we are
describing the process of referring the instance method.
Syntax:
<arbitary object type>::<instance method>
Look into the example, String::toUpperCase, usually toUpperCase() method is called on a
string reference but we have written class name ―String‖ as like reference to static method.
In the following example, String is particular type and the arbitrary object is the instance
of String that is used during method invoke. When reference to an instance method of an
arbitrary object of a particular type, that invokes a method onto the current object.

Department of CSE / Siddharth Group of Institutions, Puttur 125


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

@FunctionalInterface
interface MyFunctionalInterface {

String processString(String name);


}

public class MethodReferenceDemo {

public static void main(String[] args) {

MyFunctionalInterface f1 = s -> s.toUpperCase();


System.out.println(f1.processString("Peter")); // PETER

// Above two lines equalant to following lines


MyFunctionalInterface f2 = String::toUpperCase;
System.out.println(f2.processString("Peter")); // PETER
}
}

STREAM API

Java provides a new additional package in Java 8 called java.util.stream. This package consists
of classes, interfaces and enum to allows functional-style operations on the elements. You can
use stream by importing java.util.stream package.

Stream provides following features:


Stream does not store elements. It simply conveys elements from a source such as a data
structure, an array, or an I/O channel, through a pipeline of computational operations.
 Stream is functional in nature. Operations performed on a stream does not modify it's
source. For example, filtering a Stream obtained from a collection produces a new
Stream without the filtered elements, rather than removing elements from the source
collection.
 Stream is lazy and evaluates code only when required.
 The elements of a stream are only visited once during the life of a stream. Like an
Iterator, a new stream must be generated to revisit the same elements of the source.
You can use stream to filter, collect, print, and convert from one data structure to other etc.

Stream Creation
There are many ways to create a stream instance of different sources. Once created, the instance
will not modify its source, therefore allowing the creation of multiple instances from a single
source.
Empty Stream
We should use the empty() method in case of the creation of an empty stream:

Stream<String> streamEmpty = Stream.empty();

Department of CSE / Siddharth Group of Institutions, Puttur 126


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

We often use the empty() method upon creation to avoid returning null for streams with no
element:

public Stream<String> streamOf(List<String> list) {


return list == null || list.isEmpty() ? Stream.empty() : list.stream();
}

Stream of Collection
We can also create a stream of any type of Collection (Collection, List, Set):

Collection<String> collection = Arrays.asList("a", "b", "c");


Stream<String> streamOfCollection = collection.stream();

Stream of Array
An array can also be the source of a stream:

Stream<String> streamOfArray = Stream.of("a", "b", "c");


We can also create a stream out of an existing array or of part of an array:

String[] arr = new String[]{"a", "b", "c"};


Stream<String> streamOfArrayFull = Arrays.stream(arr);
Stream<String> streamOfArrayPart = Arrays.stream(arr, 1, 3);

Stream.builder()
When builder is used, the desired type should be additionally specified in the right part of the
statement, otherwise the build() method will create an instance of the Stream<Object>:

Stream.generate()
The generate() method accepts a Supplier<T> for element generation. As the resulting stream is
infinite, the developer should specify the desired size, or the generate() method will work until it
reaches the memory limit:

Stream<String> streamGenerated =
Stream.generate(() -> "element").limit(10);

Stream.iterate()
Another way of creating an infinite stream is by using the iterate() method:

Stream<Integer> streamIterated = Stream.iterate(40, n -> n + 2).limit(20);


The first element of the resulting stream is the first parameter of the iterate() method. When
creating every following element, the specified function is applied to the previous element. In
the example above the second element will be 42.
Stream of Primitives
Java 8 offers the possibility to create streams out of three primitive types: int, long and double.
As Stream<T> is a generic interface, and there is no way to use primitives as a type parameter
with generics, three new special interfaces were created: IntStream, LongStream, DoubleStream.
Stream of String
Department of CSE / Siddharth Group of Institutions, Puttur 127
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

We can also use String as a source for creating a stream with the help of the chars() method of
the String class. Since there is no interface for CharStream in JDK, we use the IntStream to
represent a stream of chars instead.

IntStream streamOfChars = "abc".chars();


The following example breaks a String into sub-strings according to specified RegEx:

Stream<String> streamOfString =
Pattern.compile(", ").splitAsStream("a, b, c");
Stream of File
Furthermore, Java NIO class Files allows us to generate a Stream<String> of a text file through
the lines() method. Every line of the text becomes an element of the stream:

Path path = Paths.get("C:\\file.txt");


Stream<String> streamOfStrings = Files.lines(path);
Stream<String> streamWithCharset =
Files.lines(path, Charset.forName("UTF-8"));
The Charset can be specified as an argument of the lines() method.
Referencing a Stream
We can instantiate a stream, and have an accessible reference to it, as long as only intermediate
operations are called. Executing a terminal operation makes a stream inaccessible.

To demonstrate this, we will forget for a while that the best practice is to chain the sequence of
operation. Besides its unnecessary verbosity, technically the following code is valid:

Stream<String> stream =
Stream.of("a", "b", "c").filter(element -> element.contains("b"));
Optional<String> anyElement = stream.findAny();
However, an attempt to reuse the same reference after calling the terminal operation will trigger
the IllegalStateException:

Optional<String> firstElement = stream.findFirst();


Stream Pipeline
To perform a sequence of operations over the elements of the data source and aggregate their
results, we need three parts: the source, intermediate operation(s) and a terminal operation.

Intermediate operations return a new modified stream. For example, to create a new stream of
the existing one without few elements, the skip() method should be used:

Java Example: Filtering Collection without using Stream


In the following example, we are filtering data without using stream. This approach we are used
before the stream package was released.

import java.util.*;
class Product{
int id;
Department of CSE / Siddharth Group of Institutions, Puttur 128
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

String name;
float price;
public Product(int id, String name, float price) {
this.id = id;
this.name = name;
this.price = price;
}
}
public class JavaStreamExample {
public static void main(String[] args) {
List<Product> productsList = new ArrayList<Product>();
//Adding Products
productsList.add(new Product(1,"HP Laptop",25000f));
productsList.add(new Product(2,"Dell Laptop",30000f));
productsList.add(new Product(3,"Lenevo Laptop",28000f));
productsList.add(new Product(4,"Sony Laptop",28000f));
productsList.add(new Product(5,"Apple Laptop",90000f));
List<Float> productPriceList = new ArrayList<Float>();
for(Product product: productsList){

// filtering data of list


if(product.price<30000){
productPriceList.add(product.price); // adding price to a productPriceList
}
}
System.out.println(productPriceList); // displaying data
}
}
Output:

[25000.0, 28000.0, 28000.0]

Java Stream Example: Filtering Collection by using Stream


Here, we are filtering data by using stream. You can see that code is optimized and maintained.
Stream provides fast execution.
import java.util.*;
import java.util.stream.Collectors;
class Product{
int id;
String name;
float price;
public Product(int id, String name, float price) {
this.id = id;
this.name = name;
this.price = price;
}
}
Department of CSE / Siddharth Group of Institutions, Puttur 129
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

public class JavaStreamExample {


public static void main(String[] args) {
List<Product> productsList = new ArrayList<Product>();
//Adding Products
productsList.add(new Product(1,"HP Laptop",25000f));
productsList.add(new Product(2,"Dell Laptop",30000f));
productsList.add(new Product(3,"Lenevo Laptop",28000f));
productsList.add(new Product(4,"Sony Laptop",28000f));
productsList.add(new Product(5,"Apple Laptop",90000f));
List<Float> productPriceList2 =productsList.stream()
.filter(p -> p.price > 30000)// filtering data
.map(p->p.price) // fetching price
.collect(Collectors.toList()); // collecting as list
System.out.println(productPriceList2);
}
}

Java Stream Iterating Example


You can use stream to iterate any number of times. Stream provides predefined methods to deal
with the logic you implement. In the following example, we are iterating, filtering and passed a
limit to fix the iteration.

import java.util.stream.*;
public class JavaStreamExample {
public static void main(String[] args){
Stream.iterate(1, element->element+1)
.filter(element->element%5==0)
.limit(5)
.forEach(System.out::println);
}
}

Java Stream Example: Filtering and Iterating Collection


In the following example, we are using filter() method. Here, you can see code is optimized and
very concise.

import java.util.*;
class Product{
int id;
String name;
float price;
public Product(int id, String name, float price) {
this.id = id;
this.name = name;
this.price = price;
}
}

Department of CSE / Siddharth Group of Institutions, Puttur 130


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

public class JavaStreamExample {


public static void main(String[] args) {
List<Product> productsList = new ArrayList<Product>();
//Adding Products
productsList.add(new Product(1,"HP Laptop",25000f));
productsList.add(new Product(2,"Dell Laptop",30000f));
productsList.add(new Product(3,"Lenevo Laptop",28000f));
productsList.add(new Product(4,"Sony Laptop",28000f));
productsList.add(new Product(5,"Apple Laptop",90000f));
// This is more compact approach for filtering data
productsList.stream()
.filter(product -> product.price == 30000)
.forEach(product -> System.out.println(product.name));
}
}

Java Stream Example : reduce() Method in Collection


This method takes a sequence of input elements and combines them into a single summary result
by repeated operation. For example, finding the sum of numbers, or accumulating elements into
a list.

In the following example, we are using reduce() method, which is used to sum of all the product
prices.

import java.util.*;
class Product{
int id;
String name;
float price;
public Product(int id, String name, float price) {
this.id = id;
this.name = name;
this.price = price;
}
}
public class JavaStreamExample {
public static void main(String[] args) {
List<Product> productsList = new ArrayList<Product>();
//Adding Products
productsList.add(new Product(1,"HP Laptop",25000f));
productsList.add(new Product(2,"Dell Laptop",30000f));
productsList.add(new Product(3,"Lenevo Laptop",28000f));
productsList.add(new Product(4,"Sony Laptop",28000f));
productsList.add(new Product(5,"Apple Laptop",90000f));
// This is more compact approach for filtering data
Float totalPrice = productsList.stream()
.map(product->product.price)

Department of CSE / Siddharth Group of Institutions, Puttur 131


20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

.reduce(0.0f,(sum, price)->sum+price); // accumulating price


System.out.println(totalPrice);
// More precise code
float totalPrice2 = productsList.stream()
.map(product->product.price)
.reduce(0.0f,Float::sum); // accumulating price, by referring method of Float class
System.out.println(totalPrice2);

}
}

DATE & TIME API

Java 8 introduces a new date-time API under the package java.time. Following are some of the
important classes introduced in java.time package.

 Local − Simplified date-time API with no complexity of timezone handling.


 Zoned − Specialized date-time API to deal with various timezones.

Local Date-Time API


LocalDate/LocalTime and LocalDateTime classes simplify the development where timezones are
not required. Let's see them in action.

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.Month;

public class Java8Tester {

public static void main(String args[]) {


Java8Tester java8tester = new Java8Tester();
java8tester.testLocalDateTime();
}

public void testLocalDateTime() {


// Get the current date and time
LocalDateTime currentTime = LocalDateTime.now();
System.out.println("Current DateTime: " + currentTime);

LocalDate date1 = currentTime.toLocalDate();


System.out.println("date1: " + date1);

Month month = currentTime.getMonth();


int day = currentTime.getDayOfMonth();
int seconds = currentTime.getSecond();
Department of CSE / Siddharth Group of Institutions, Puttur 132
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

System.out.println("Month: " + month +"day: " + day +"seconds: " + seconds);

LocalDateTime date2 = currentTime.withDayOfMonth(10).withYear(2012);


System.out.println("date2: " + date2);

//12 december 2014


LocalDate date3 = LocalDate.of(2014, Month.DECEMBER, 12);
System.out.println("date3: " + date3);

//22 hour 15 minutes


LocalTime date4 = LocalTime.of(22, 15);
System.out.println("date4: " + date4);

//parse a string
LocalTime date5 = LocalTime.parse("20:15:30");
System.out.println("date5: " + date5);
}
}

Output:

F:\JAVA NOTES\programs> javac Java8Tester.java


F:\JAVA NOTES\programs> java Java8Tester
C
urrent DateTime: 2021-05-01T14:46:14.350006500
date1: 2021-05-01
Month: MAY day: 1 seconds: 14
date2: 2012-05-10T14:46:14.350006500
date3: 2014-12-12
date4: 22:15
date5: 20:15:30

Zoned Date-Time API


Zoned date-time API is to be used when time zone is to be considered. Let us see them in action.

import java.time.ZonedDateTime;
import java.time.ZoneId;

public class Java8Tester {


public static void main(String args[]) {
Java8Tester java8tester = new Java8Tester();
java8tester.testZonedDateTime();
}
public void testZonedDateTime() {
// Get the current date and time
ZonedDateTime date1 = ZonedDateTime.parse("2007-12-03T10:15:30+05:30[Asia/Karachi]");
Department of CSE / Siddharth Group of Institutions, Puttur 133
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA

System.out.println("date1: " + date1);


ZoneId id = ZoneId.of("Europe/Paris");
System.out.println("ZoneId: " + id);
ZoneId currentZone = ZoneId.systemDefault();
System.out.println("CurrentZone: " + currentZone);
}
}
Output:

PS F:\JAVA NOTES\programs> javac Java8Tester.java


PS F:\JAVA NOTES\programs> java Java8Tester
date1: 2007-12-03T09:45:30+05:00[Asia/Karachi]
ZoneId: Europe/Paris
CurrentZone: Asia/Calcutta

Department of CSE / Siddharth Group of Institutions, Puttur 134

You might also like