Oops Full Notes-R20
Oops Full Notes-R20
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.
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:
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
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:
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
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.
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.
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.
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.
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.
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.
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.
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);
// 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
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
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.
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
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.
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
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
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
"javatpoint" String
Operator Symbols
Arithmetic +,-,/,*,%
Unary ++ , - - , !
Assignment = , += , -= , *= , /= , %= , ^=
Logical && , ||
Bitwise &,|,^,~
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[])
{
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
}
}
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!
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)
{
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
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
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?
// declare an array
int[] age = new int[5];
// initialize array
age[0] = 12;
age[1] = 4;
age[2] = 5;
..
class OneD
{
public static void main (String[] args)
{
// declares an Array of integers.
int[] arr;
//so on...
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
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:
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
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
args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100
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.
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‖.
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.
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:
import java.io.*;
class Addition {
int sum = 0;
class Test {
public static void main (String[] args) {
}
}
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.
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();
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.
// Driver code
public class Test
{
Department of CSE / Siddharth Group of Institutions, Puttur 39
20CS0506 OBJECT ORIENTED PROGRAMMING THROUGH JAVA
double vol;
OUTPUT:
Volume of mybox1 is 3000.0
Volume of mybox2 is 0.0
Volume of mycube is 343.0
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
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
Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC). This
thread calls the finalize() method before 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;
class FinalDemo {
// create a final method
public final void display() {
System.out.println("This is a final method.");
}
}
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.
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.
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 {
.....
.....
}
File: TestInheritance.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}
}
Output:
barking...
eating...
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...
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.
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.
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
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:
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
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
class Bank{
int getRateOfInterest(){return 0;}
}
//Creating child classes.
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
The differences between Method Overloading and Method Overriding in Java are:
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
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();
}
}
Output:
bike is created
running safely..
gear changed
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.
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
{
……..
……..
}
{
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.
Example:
package java.util;
public interface EventListner
{
}
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.
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
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.
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.
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.
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{}
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.
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
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.
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.
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.
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.
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.
}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.
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.
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
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.
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 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( )
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:
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.");
}
}
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.
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
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.
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.
} 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.
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
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
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:
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:
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
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.
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
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
// constructor
Test(T obj1, U obj2)
{
this.obj1 = obj1;
this.obj2 = obj2;
}
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.
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.
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.
2 boolean add(Object o)
Appends the specified element to the end of this list.
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.
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)).
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.
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.
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 {
ll.addFirst("A");
ll.add(1, "A2");
System.out.println("Original contents of ll: " + ll);
COLLECTION INTERFACES
The collections framework defines several interfaces. This section provides an overview of each
interface –
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
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
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.
5 boolean containsAll(Collection c)
Returns true if the invoking collection contains all elements of c. 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( )
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.
Example
import java.util.*;
public class CollectionsDemo {
// 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
// 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}
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.
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.
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;
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
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;
Output:
Java is the prominent programming language of the millennium!
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.
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.
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.
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
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
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);
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();
}}
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.
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.
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.
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.
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.
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:
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
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
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{
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");;
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
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
f.setSize(300,300);
f.s etVisible(true);
}
public static void main(String[] args) {
new MyGridLayout(); }}
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.
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);
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.
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:
ContainingClass::staticMethodName
Example 1
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:
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();
// 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:
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
class Test
{
public static void main(String args[])
{
@FunctionalInterface
interface Square
{
int calculate(int x);
}
class Test
{
public static void main(String args[])
{
int a = 5;
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);
}
class Test
{
public static void main(String args[])
{
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.
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:
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
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
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)
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:
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");
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);
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 {
System.out.println(mi.isEvenNumber(15));//false
System.out.println(mi.isEvenNumber(20));//true
}
}
Same example with reference to a method
@FunctionalInterface
interface MyFunctionalInterface {
return i%2 == 0;
}
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 {
//instance method
boolean myImplementation(int i) {
return i%2 == 0;
}
public static void main(String[] args) {
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.
@FunctionalInterface
interface MyFunctionalInterface {
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 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:
We often use the empty() method upon creation to avoid returning null for streams with no
element:
Stream of Collection
We can also create a stream of any type of Collection (Collection, List, Set):
Stream of Array
An array can also be the source of a stream:
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:
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.
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:
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:
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:
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){
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);
}
}
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;
}
}
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)
}
}
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.
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.Month;
//parse a string
LocalTime date5 = LocalTime.parse("20:15:30");
System.out.println("date5: " + date5);
}
}
Output:
import java.time.ZonedDateTime;
import java.time.ZoneId;