Advanced Java Programming
CSE4019
Module 1
CSE4019 - Advanced Java Programming 1
Overview of the Java platform
1. Java Language
•Java Programming Language: An object-oriented,
high-level language designed for ease of use, readability, and
maintainability. Java's syntax is similar to C++, but it
simplifies many aspects of C++ and eliminates some of its
more complex features.
CSE4019 Advanced Java Programming 2
2. Java Virtual Machine (JVM)
•Role: The JVM is an abstract computing machine that enables
a computer to run a Java program. It interprets Java bytecode
(compiled Java code) and translates it into machine code.
•Portability: The JVM allows Java programs to be
platform-independent, meaning you can write your code once
and run it anywhere without modification.
•Just-In-Time (JIT) Compilation: The JVM includes a JIT
compiler that improves performance by compiling bytecode
into native machine code at runtime.
CSE4019 - Advanced Java Programming 3
3. Java Development Kit (JDK)
•Components: The JDK includes tools for developing Java
applications, such as:
• Java Compiler (javac): Converts Java source code into
bytecode.
• Java Runtime Environment (JRE): Provides the
libraries, Java Virtual Machine (JVM), and other
components to run Java applications.
• Development Tools: Includes a debugger (jdb),
documentation generator (javadoc), and other utility
tools.
CSE4019 - Advanced Java Programming 4
4. Java Runtime Environment (JRE)
•Components: The JRE includes:
• JVM: For executing Java bytecode.
• Java Class Libraries: A set of standard libraries
providing functionality for Java programs (e.g., I/O
operations, networking, data structures).
• Java Class Loader: Responsible for loading classes into
the JVM.
CSE4019 - Advanced Java Programming 5
5. Java Standard Edition (Java SE)
•Purpose: Provides core functionality for general-purpose
programming. It includes essential libraries and APIs for
building and running Java applications.
•Key Libraries: Collections Framework, I/O (Input/Output),
Networking, Concurrency, and more.
CSE4019 - Advanced Java Programming 6
6. Java Enterprise Edition (Java EE)
•Purpose: Extends Java SE with additional libraries and APIs
for enterprise-level applications, such as web-based
applications and large-scale systems.
•Components:
• Servlets: For handling web requests.
• JavaServer Pages (JSP): For creating dynamic web
content.
• Enterprise JavaBeans (EJB): For business logic.
• Java Persistence API (JPA): For managing relational
data in Java applications.
CSE4019 - Advanced Java Programming 7
7. Java Micro Edition (Java ME)
•Purpose: Designed for developing applications on mobile and
embedded devices with limited resources.
•Components:
• CLDC (Connected Limited Device Configuration):
Provides a minimal JVM and APIs for small devices.
• MIDP (Mobile Information Device Profile): Adds
higher-level APIs for creating mobile applications.
CSE4019 - Advanced Java Programming 8
8. Java Modules
•Java Platform Module System (JPMS): Introduced in Java
9, it allows developers to modularize applications and
libraries, providing better encapsulation and improved
dependency management.
•9. Ecosystem and Tools
•Integrated Development Environments (IDEs): Popular
IDEs for Java include IntelliJ IDEA, Eclipse, and NetBeans.
•Build Tools: Tools like Maven and Gradle are used for
managing project dependencies and automating the build
process.
CSE4019 - Advanced Java Programming 9
10. Community and Support
•OpenJDK: The open-source implementation of the Java
Platform, including the JDK and JVM.
•Oracle JDK: A commercial distribution of the JDK by Oracle,
with additional features and support.
CSE4019 - Advanced Java Programming 10
Features of Java
• There is given many features of java. They are also known as java
buzzwords. The Java Features given below are simple and easy to
understand.
•Simple
•Object-Oriented
•Platform independent
•Secured
•Robust
•Architecture neutral
•Portable
•Dynamic
•Interpreted
•High Performance
•Multithreaded
•Distributed
CSE4019 - Advanced Java Programming 11
Simple
•According to Sun, Java language is simple because:
• syntax is based on C++ (so easier for programmers to learn it after C++).
• removed many confusing and/or rarely-used features e.g., explicit pointers,
operator overloading etc.
• No need to remove unreferenced objects because there is Automatic Garbage
Collection in java.
Object-oriented
•Object-oriented means we organize our software as a combination of different types
of objects that incorporates both data and behaviour.
•Object-oriented programming(OOPs) is a methodology that simplify software
development and maintenance by providing some rules.
•Basic concepts of OOPs are:
•Object
•Class
•Inheritance
•Polymorphism
•Abstraction
•Encapsulation
CSE4019 - Advanced Java Programming 12
Platform Independent
•A platform is the hardware or software environment in which a program runs.
•There are two types of platforms software-based and hardware-based. Java
provides software-based platform.
•The Java platform differs from most other platforms in the sense that it is a
software-based platform that runs on the top of other hardware-based
platforms. It has two components:
•Runtime Environment
•API(Application Programming Interface)
• Java code can be run on multiple
platforms e.g. Windows, Linux, Sun
Solaris, Mac/OS etc. Java code is
compiled by the compiler and
converted into bytecode. This bytecode
is a platform-independent code because
it can be run on multiple platforms i.e.
Write Once and Run
Anywhere(WORA).
CSE4019 - Advanced Java Programming 13
Secured
•Java is secured because:
•No explicit pointer
•Java Programs run inside virtual machine sandbox
•Classloader: adds security by separating the package for the classes of the local file system
from those that are imported from network sources.
•Bytecode Verifier: checks the code fragments for illegal code that can violate access right to
objects.
•Security Manager: determines what resources a class can access such as reading and writing
to the local disk.
•These security are provided by java language. Some security can also be provided by
application developer through SSL, JAAS, Cryptography etc.
CSE4019 - Advanced Java Programming 14
Robust
Robust simply means strong. Java uses strong memory management. There are lack
of pointers that avoids security problem. There is automatic garbage collection in
java. There is exception handling and type checking mechanism in java. All these
points makes java robust.
Architecture-neutral
There is no implementation dependent features e.g. size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture
and 4 bytes of memory for 64-bit architecture. But in java, it occupies 4 bytes of
memory for both 32 and 64 bit architectures.
Portable
We may carry the java bytecode to any platform.
High-performance
Java is faster than traditional interpretation since byte code is "close" to native code
still somewhat slower than a compiled language (e.g., C++)
CSE4019 - Advanced Java Programming 15
Distributed
We can create distributed applications in java. RMI and EJB are used for
creating distributed applications. We may access files by calling the
methods from any machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write
Java programs that deal with many tasks at once by defining multiple
threads. The main advantage of multi-threading is that it doesn't occupy
memory for each thread. It shares a common memory area. Threads are
important for multi-media, Web applications etc.
CSE4019 - Advanced Java Programming 16
Java Architecture
•Java Architecture is a collection of components,
namely JVM (Java Virtual Machine), JRE (Java Runtime
Environment), and JDK (Java Development Kit). It
orchestrates the process of both interpretation and
compilation, delineating all processes involved in creating a
Java program.
Components of Java Architecture
•Java architecture comprises three main components:
•Java Virtual Machine (JVM)
•Java Runtime Environment (JRE)
•Java Development Kit (JDK)
CSE4019 - Advanced Java Programming 17
•Java Bytecode
∙ Definition: Bytecode is the low-level representation of Java
code that the JVM can execute. It is platform-independent
and allows Java applications to be portable across different
operating systems and hardware architectures.
CSE4019 - Advanced Java Programming 18
•Java Virtual Machine (JVM)
∙ Role: The JVM is an abstract computing machine that
interprets or compiles bytecode into native machine code that
the host system can execute.
∙ Components:
o Class Loader: Loads .class files into memory.
o Bytecode Verifier: Ensures that the bytecode adheres to
Java's security constraints and does not violate access
rights. Execution Engine: Executes the bytecode, either
by interpreting it or by using Just-In-Time (JIT)
compilation to convert bytecode into native code for
better performance.
o Garbage Collector: Automatically manages memory by
reclaiming unused objects and freeing up space. 19
Java Runtime Environment (JRE)
Components:
o JVM: The core component that executes Java bytecode.
o Java Class Libraries: A set of standard libraries and
APIs (e.g., [Link], [Link], [Link]) that provide basic
functionality for Java applications.
o Java Class Loader: Part of the JVM that loads classes
at runtime.
CSE4019 - Advanced Java Programming 20
Java Development Kit (JDK)
∙ Components:
o JRE: Provides the runtime environment necessary for
executing Java applications.
o Java Compiler (javac): Compiles Java source code into
bytecode.
o Development Tools: Includes utilities for
documentation (javadoc), debugging (jdb), and other
tasks.
CSE4019 - Advanced Java Programming 21
CSE4019 - Advanced Java Programming 22
Describe the OOPs concepts
CSE4019 - Advanced Java Programming 23
• Object means a real word entity such as pen, chair, table
etc. Object-Oriented Programming is a methodology or paradigm to
design a program using classes and objects. It simplifies the software
development and maintenance by providing some concepts:
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
Object
• Any entity that has state and behavior is known as an object. For
example: chair, pen, table, keyboard, bike etc. It can be physical and
logical.
Class
• Collection of objects is called class. It is a logical entity.
CSE4019 - Advanced Java Programming 24
Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
When one task is performed by different ways
i.e. known as polymorphism.
For example: to convince the customer
differently, to draw something e.g. shape or rectangle etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example: phone
call, we don't know the internal processing.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation.
For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because
all the data members are private here.
CSE4019 - Advanced Java Programming 25
Define Java virtual machine
CSE4019 - Advanced Java Programming 26
A Java virtual machine (JVM) is an abstract computing machine that
enables a computer to run a Java program. There are three notions of
the JVM specification, implementation and instance.
CSE4019 - Advanced Java Programming 27
Difference Between JDK, JRE, and JVM
Parameter JDK JRE JVM
Full-Form The JDK is an The JRE is an The JVM is an
abbreviation for Java abbreviation for Java abbreviation for Java
Development Kit. Runtime Virtual Machine.
Environment.
Definition The JDK (Java The Java Runtime The Java Virtual
Development Kit) is Environment (JRE) Machine (JVM) is a
a software is an implementation platform-independen
development kit that of JVM. It is a type of t abstract machine
develops software package that has three
applications in Java. that provides class notions in the form of
Along with JRE, the libraries of Java, specifications. This
JDK also consists of JVM, and various document describes
various development other components the requirement of
tools (Java for running the JVM implementation.
Debugger, JavaDoc, applications written
compilers, etc.) in Java
programming.
CSE4019 - Advanced Java Programming 28
Difference Between JDK, JRE, and JVM
Parameter JDK JRE JVM
Functionality The JDK primarily JRE has a major JVM specifies all of
assists in responsibility for the
executing codes. It creating an implementations. It
primarily functions environment for the is responsible for
in development. execution of code. providing all of
these
implementations to
the JRE.
Platform The JDK is JRE, just like JDK, The JVM is
Dependency platform-dependen is also platform-independe
t. It means that for platform-dependen nt. It means that
every different t. It means that for you won’t require a
platform, you every different different JVM for
require a different platform, you every different
JDK. require a different platform.
JRE.
CSE4019 - Advanced Java Programming 29
Difference Between JDK, JRE, and JVM
Parameter JDK JRE JVM
Tools Since JDK is JRE, on the other JVM does not
primarily hand, does not consist of any tools
responsible for the consist of any tool- for software
development, it like a debugger, development.
consists of various compiler, etc. It
tools for rather contains
debugging, various supporting
monitoring, and files for JVM, and
developing java the class libraries
applications. that help JVM in
running the
program.
Implementation JDK = JRE = Libraries for JVM = Only the
Development Tools running the runtime
+ JRE (Java application + JVM environment that
Runtime (Java Virtual helps in executing
Environment) Machine) the Java bytecode.
CSE4019 - Advanced Java Programming 30
Difference Between JDK, JRE, and JVM
Parameter JDK JRE JVM
Why Use It? Why use JDK? Why use JRE? Why use JVM?
Some crucial reasons to use Some crucial reasons to Some crucial reasons to use
JDK are: use JRE are: JVM are:
•It consists of various tools •If a user wants to run the •It provides its users with a
required for writing Java Java applets, then they platform-independent way for
programs. must install JRE on their executing the Java source
•JDK also contains JRE for system. code.
executing Java programs. •The JRE consists of class •JVM consists of various tools,
•It includes an Appletviewer, libraries along with JVM libraries, and multiple
Java application launcher, and its supporting files. It frameworks.
compiler, etc. has no other tools like a •The JVM also comes with a
•The compiler helps in compiler or a debugger for Just-in-Time (JIT) compiler for
converting the code written in Java development. converting the Java source
Java into bytecodes. •JRE uses crucial package code into a low-level machine
•The Java application launcher classes like util, math, awt, language. Thus, it ultimately
helps in opening a JRE. It then lang, and various runtime runs faster than any regular
loads all of the necessary libraries. application.
details and then executes all of •Once you run the Java
its main methods. program, you can run JVM on
any given platform to save your
time.
CSE4019 - Advanced Java Programming 31
Difference Between JDK, JRE, and JVM
Parameter JDK JRE JVM
Features Features of JDK Features of JRE Features of JVM
•Here are a few crucial features of •Here are a few crucial features Here are a few crucial features of JVM:
JDK: of JRE: •The JVM enables a user to run applications
•It has all the features that JRE •It is a set of tools that actually on their device or in a cloud environment.
does. helps the JVM to run. •It helps in converting the bytecode into
•JDK enables a user to handle •The JRE also consists of machine-specific code.
multiple extensions in only one deployment technology. It •JVM also provides some basic Java
catch block. includes Java Plug-in and Java functions, such as garbage collection,
•It basically provides an Web Start as well. security, memory management, and many
environment for developing and •A developer can easily run a more.
executing the Java source code. source code in JRE. But it does •It uses a library along with the files given by
•It has various development tools not allow them to write and JRE (Java Runtime Environment) for
like the debugger, compiler, etc. compile the concerned Java running the program.
•One can use the Diamond operator program. •Both JRE and JDK contain JVM.
to specify a generic interface in •JRE also contains various •It is easily customizable. For instance, a
place of writing the exact one. integration libraries like the user can feasibly allocate a maximum and
•Any user can easily install JDK on JDBC (Java Database minimum memory to it.
Unix, Mac, and Windows OS Connectivity), JNDI (Java •JVM can also execute a Java program line
(Operating Systems). Naming and Directory Interface), by line. It is thus also known as an
RMI (Remote Method interpreter.
Invocation), and many more. •JVM is also independent of the OS and
•It consists of the JVM and virtual hardware. It means that once a user writes
machine client for Java HotSpot. a Java program, they can easily run it
anywhere.
CSE4019 - Advanced Java Programming 32
Difference between path and
classpath variable
CSE4019 - Advanced Java Programming 33
Path Classpath
Path is an environment variable Classpath is an environment
which is used by the operating variable which is used by the Java
system to find the executables. compiler to find the path, of
[Link] in J2EE we give the path
of jar files.
PATH is nothing but setting up an Classpath is nothing but setting up
environment for operating system. the environment for Java. Java will
Operating System will look in this use to find compiled classes
PATH for executables.
Path refers to the system classpath refers to the Developing
Envornment
In path we set the path of classpath we set path of jars for
executables compiling classes
CSE4019 - Advanced Java Programming 34
Illustrate the Data types and variable
CSE4019 - Advanced Java Programming 35
Data type
•Data type specifies the size and type of values that can be stored in an identifier.
The Java language is rich in its data types. Different data types allow you to select
the type appropriate to the needs of the application.
•Data types in Java are classified into two types:
•Primitive—which include Integer, Character, Boolean, and Floating Point.
•Non-primitive—which include Classes, Interfaces, and Arrays.
Primitive Data Types
1. Integer
•Integer types can hold whole numbers such as 123 and −96. The size of the values
that can be stored depends on the integer type that we choose.
Type Size Range of values that can be stored
byte 1 byte −128 to 127
short 2 bytes −32768 to 32767
int 4 bytes −2,147,483,648 to 2,147,483,647
9,223,372,036,854,775,808 to
long 8 bytes
9,223,372,036,854,755,807
CSE4019 - Advanced Java Programming 36
• 2. Floating Point
• Floating point data types are used to represent numbers with a
fractional part. Single precision floating point numbers occupy 4 bytes
and Double precision floating point numbers occupy 8 bytes. There are
two subtypes:
Type Size Range of values that can be stored
float 4 bytes 3.4e−038 to 3.4e+038
double 8 bytes 1.7e−308 to 1.7e+038
• 3. Character
• It stores character constants in the memory. It assumes a size of 2 bytes,
but basically it can hold only a single character because char stores
unicode character sets. It has a minimum value of ‘u0000’ (or 0) and a
maximum value of ‘uffff’ (or 65,535, inclusive).
• 4. Boolean
• Boolean data types are used to store values with two states: true or
false.
CSE4019 - Advanced Java Programming 37
• Java Tokens
• A token is the smallest element in a program that is meaningful to the
compiler. These tokens define the structure of the language. The Java
token set can be divided into five categories: Identifiers, Keywords,
Literals, Operators, and Separators.
• 1. Identifiers
• Identifiers are names provided by you. These can be assigned to
variables, methods, functions, classes etc. to uniquely identify them to
the compiler.
• 2. Keywords
• Keywords are reserved words that have a specific meaning for the
compiler. They cannot be used as identifiers. Java has a rich set of
keywords. Some examples are: boolean, char, if, protected, new, this,
try, catch, null, threadsafe etc.
CSE4019 - Advanced Java Programming 38
3. Literals
Literals are variables whose values remain constant throughout the program. They are also
called Constants. Literals can be of four types. They are:
a. String Literals
String Literals are always enclosed in double quotes and are implemented
using the [Link] class. Enclosing a character string within double
quotes will automatically create a new String object. For example, String s =
"this is a string";. String objects are immutable, which means that once
created, their values cannot be changed.
b. Character Literals
These are enclosed in single quotes and contain only one character.
c. Boolean Literals
They can only have the values true or false. These values do not correspond to
1 or 0 as in C or C++.
d. Numeric Literals
Numeric Literals can contain integer or floating point values.
4. Operators
An operator is a symbol that operates on one or more operands to produce a result.
They will be discussed in greater detail in the next article.
CSE4019 - Advanced Java Programming 39
5. Separators
Separators are symbols that indicate the division and arrangement of groups of code. The
structure and function of code is generally defined by the separators. The separators used in
Java are as follows:
parentheses ( )
Used to define precedence in expressions, to enclose parameters in method definitions, and
enclosing cast types.
braces { }
Used to define a block of code and to hold the values of arrays.
brackets [ ]
Used to declare array types.
semicolon ;
Used to separate statements.
comma ,
Used to separate identifiers in a variable declaration and in the for statement.
period .
Used to separate package names from classes and subclasses and to separate a variable or a
method from a reference variable.
CSE4019 - Advanced Java Programming 40
Variables
There are different types of variables in Java. They are as follows:
1. Instance Variables (Non-Static Fields)
Objects store their individual states in “non-static fields”, that is, fields
declared without the static keyword.
Non-static fields are also known as instance variables because their values
are unique to each instance of a class. For example, the currentSpeed of
one bicycle is independent from the currentSpeed of another.
2. Class Variables (Static Fields)
A class variable is any field declared with the static modifier; this tells the
compiler that there is exactly one copy of this variable in existence,
regardless of how many times the class has been instantiated. A field
defining the number of gears for a particular kind of bicycle could be
marked as static since, conceptually, the same number of gears will apply
to all instances. The code static int numGears = 6; would create such a
static field.
CSE4019 - Advanced Java Programming 41
3. Local Variables
A method stores its temporary state in local variables. The syntax for declaring a local
variable is similar to declaring a field (for example, int count = 0;). There is no special
keyword designating a variable as local; that determination comes entirely from the location
in which the variable is declared—between the opening and closing braces of a method. As
such, local variables are only visible to the methods in which they are declared; they are not
accessible from the rest of the class.
4. Parameters
They are the variables that are passed to the methods of a class
CSE4019 - Advanced Java Programming 42
Variable Declaration
Identifiers are the names of variables. They must be composed of only
letters, numbers, the underscore, and the dollar sign ($). They cannot
contain white spaces. Identifiers may only begin with a letter, the
underscore, or the dollar sign. A variable cannot begin with a number. All
variable names are case sensitive.
Syntax for variable declaration
datatype1 variable1, datatype2 variable2, … datatypen variablen;
For example:
int a, char ch;
Initialisation
Variables can be assigned values in the following way: Variablename =
value;
For example;
ch='a';
a=0;
CSE4019 - Advanced Java Programming 43
Explain the concepts of arrays and
expressions in any problem
CSE4019 - Advanced Java Programming 44
Arrays
An array is a group of variables that share the same data type, and 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. The array index ranges from
0 to n−1; therefore, in an array of size 10, the first element is stored at index 0 and
the last or the 10th element at index 9.
The following program, Printarr, creates an array of integers, puts some values in
it, and prints each value to standard output.
CSE4019 - Advanced Java Programming 45
Example
class Printarr {
public static void main(String[] args) { The output from this program is:
// declares an array of integers
Element at index 0: 15
int[ ] A; Element at index 1: 20
// allocates memory for 5 integers Element at index 2: 25
A = new int[5]; Element at index 3: 30
// initialize elements Element at index 4: 50
A[0] = 15;//first element
A[1] = 20;//second element
A[2] = 25;//third element
A[3] = 30;//fourth element
A[4] = 50;//fifth element
[Link]("Element at index 0: "+ A[0]);
[Link]("Element at index 1: "+ A[1]);
[Link]("Element at index 2: "+ A[2]);
[Link]("Element at index 3: "+ A[3]);
[Link]("Element at index 4: "+ A[4]);
}}
CSE4019 - Advanced Java Programming 46
Copying Arrays
The data from one array can be copied into another array by using the arraycopy method of
the System class:
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
The two Object arguments specify the array to copy from, and the array to copy to. The three
int arguments specify the starting position in the source array, the starting position in the
destination array, and the number of array elements to copy.
The following program, Copyarr, declares an array of char elements, spelling the word
“array”. It uses arraycopy to copy three elements of the first array into the second array:
class Copyarr {
public static void main(String[] args) {
char[] source = { 'a', 'r', 'r', 'a', 'y' };
char[] target = new char[3];
[Link](source, 0, target, 0, 3);
[Link](new String(target));
}
}
The output from this program is:
arr
CSE4019 - Advanced Java Programming 47
Expressions
• Expressions are essential building blocks of any Java program, usually
created to produce a new value, although sometimes an expression
simply assigns a value to a variable.
• Expressions are built using values, variables, operators and method
calls.
• An expression is a construct made up of variables, operators, and
method invocations, which are constructed according to the syntax
of the language, that evaluates to a single value. You've already seen
examples of expressions, illustrated in bold below:
CSE4019 - Advanced Java Programming 48
int cadence = 0;
anArray[0] = 100;
[Link]("Element 1 at index 0: " + anArray[0]);
int result = 1 + 2; // result is now 3
if (value1 == value2)
[Link]("value1 == value2");
•For example, the following expression gives different results,
depending on whether you perform the addition or the division
operation first:
x + y / 100 // ambiguous
•You can specify exactly how an expression will be evaluated using
balanced parenthesis: ( and ).
CSE4019 - Advanced Java Programming 49
• For example, to make the previous expression unambiguous, you
could write the following:
(x + y) / 100 // unambiguous, recommended
• Operators that have a higher precedence get evaluated first. For
example, the division operator has a higher precedence than does
the addition operator. Therefore, the following two statements are
equivalent:
x + y / 100
x + (y / 100) // unambiguous, recommended
• When writing compound expressions, be explicit and indicate with
parentheses which operators should be evaluated first. This practice
makes code easier to read and to maintain.
CSE4019 - Advanced Java Programming 50
Describe the concepts of operators
in any problem
CSE4019 - Advanced Java Programming 51
Content
• Group of Operators
• Arithmetic Operators
• Assignment Operator
• Order of Precedence
• Increment/Decrement Operators
• Relational Operators
• Logical Operators
CSE4019 - Advanced Java Programming Page 52
Operators
•Operators are special symbols used for:
•mathematical functions
•assignment statements
•logical comparisons
•Examples of operators:
•3 + 5 // uses + operator
•14 + 5 – 4 * (5 – 3) // uses +, -, * operators
•Expressions: can be combinations of variables and
operators that result in a value
CSE4019 - Advanced Java Programming Page 53
Groups of Operators
• There are 5 different groups of operators:
• Arithmetic Operators
• Assignment Operator
• Increment / Decrement Operators
• Relational Operators
• Logical Operators
Java Arithmetic Operators
Addition +
Subtraction –
Multiplication *
Division /
Remainder (modulus ) %
CSE4019 - Advanced Java Programming Page 54
Arithmetic Operators
• The following table summarizes the arithmetic operators available in
Java.
This is an integer division
where the fractional part
is truncated.
CSE4019 - Advanced Java Programming Page 55
Example
Example of division issues:
10 / 3 gives 3
10.0 / 3 gives 3.33333
As we can see,
•if we divide two integers we get an integer result.
•if one or both operands is a floating-point value we get a
floating-point result.
CSE4019 - Advanced Java Programming Page 56
Modulus
❖Generates the remainder when you divide two integer
values.
5%3 gives 2 5%4 gives 1
5%5 gives 0 5%10 gives 5
❖Modulus operator is most commonly used with integer
operands. If we attempt to use the modulus operator on
floating-point values we will garbage!
CSE4019 - Advanced Java Programming Page 57
Order of Precedence
( ) evaluated first, inside-out
*, /, or % evaluated second, left-to-right
+, − evaluated last, left-to-right
CSE4019 - Advanced Java Programming Page 58
Basic Assignment Operator
•We assign a value to a variable using the basic assignment
operator (=).
•Assignment operator stores a value in memory.
•The syntax is
leftSide = rightSide ;
It is either a literal | a
Allways it is a
variable identifier | an
variable identifier.
expression.
Examples:
i = 1;
start = i;
sum = firstNumber + secondNumber;
avg = (one + two + three) / 3;
CSE4019 - Advanced Java Programming Page 59
The Right Side of the Assignment Operator
• The Java assignment operator assigns the value on the right side of
the operator to the variable appearing on the left side of the
operator.
• The right side may be either:
• Literal: ex. i = 1;
• Variable identifier: ex. start = i;
• Expression: ex. sum = first + second;
CSE4019 - Advanced Java Programming Page 60
Assigning Literals
• In this case, the literal is stored in the space memory allocated for
the variable at the left side.
A. Variables are
allocated in memory.
firstNumber 1
A
secondNumber ???
int firstNumber=1, secondNumber;
firstNumber = 234;
secondNumber = 87; B B. Literals are
assigned to variables.
firstNumber 234
Code secondNumber 8
7
State of Memory
CSE4019 - Advanced Java Programming Page 61
Assigning Variables
• In this case, the value of the variable at the right side is stored in the
space memory allocated for the variable at the left side.
A. Variables are
allocated in memory.
firstNumber 1
A
i ???
int firstNumber=1, i;
firstNumber = 234;
i = firstNumber; B B. values are assigned
to variables.
firstNumber 234
Code i 23
4
State of Memory
CSE4019 - Advanced Java Programming Page 62
Assigning Expressions
• In this case, the result of the evaluation of the expression is stored in the
space memory allocated for variable at the left side.
A. Variables are
allocated in memory.
first 1 second ???
A
int first, second, sum; sum ???
first = 234;
second = 87; B B. Values are
Sum = first + second assigned to variables.
first 234 second 87
Code
sum 321
State of Memory
CSE4019 - Advanced Java Programming Page 63
Updating Data
A. The variable
is allocated in
memory.
number ???
B. The value 237
is assigned
to number.
int number; number 237
A
number = 237;
B C. The value 35
number = 35; C overwrites the
previous value 237.
number 35
Code State of Memory
CSE4019 - Advanced Java Programming Page 64
Example: Sum of two integer
public class Sum {
// main method
public static void main( String args[] ){
int a, b, sum;
a = 20;
b = 10;
sum = a + b;
[Link](a + ” + ” + b + “ = “ +
sum);
} // end main
} // end class Sum
CSE4019 - Advanced Java Programming Page 65
Arithmetic/Assignment Operators
Java allows combining arithmetic and assignment operators into a single
operator:
Addition/assignment +=
Subtraction/assignment −=
Multiplication/assignment *=
Division/assignment /=
Remainder/assignment %=
CSE4019 - Advanced Java Programming Page 66
Arithmetic/Assignment Operators
•The syntax is It is either a literal | a
leftSide Op= rightSide ; variable identifier | an
expression.
Allways it is a
variable identifier. It is an arithmetic
operator.
•This is equivalent to:
leftSide = leftSide Op rightSide ;
•x%=5; ⇔ x = x % 5;
•x*=y+w*z; ⇔ x = x*(y+w*z);
CSE4019 - Advanced Java Programming Page 67
Increment/Decrement Operators
Only use ++ or − − when a variable is
being incremented/decremented as
a statement by itself.
x++; is equivalent to x = x+1;
x--; is equivalent to x = x-1;
CSE4019 - Advanced Java Programming Page 68
Relational Operators
•Relational operators compare two values
•They Produce a boolean value (true or false)
depending on the relationship
Operation Is true when
a >b a is greater than b
a >=b a is greater than or equal to b
a ==b a is equal to b
a !=b a is not equal to b
a <=b a is less than or equal to b
a <b a is less than b
Page 69
CSE4019 - Advanced Java Programming
Example
• int x = 3;
• int y = 5;
• boolean result;
result = (x > y);
• now result is assigned the value false because 3 is not greater than 5
Logical Operators
Symbol Name
&& AND
|| OR
! NOT
&& T F || T F
T T F T T T
F F F F T F
Page 70
CSE4019 - Advanced Java Programming
Example
boolean x = true;
boolean y = false;
boolean result;
result = (x && y);
result is assigned the value false
result = ((x || y) && x);
(x || y) evaluates to true
(true && x) evaluates to true
result is then assigned the value true
CSE4019 - Advanced Java Programming Page 71
Operators Precedence
Parentheses (), inside-out
Increment/decrement ++, --, from left to right
Multiplicative *, /, %, from left to right
Additive +, -, from left to right
Relational <, >, <=, >=, from left to right
Equality ==, !=, from left to right
Logical AND &&
Logical OR ||
Assignment =, +=, -=, *=, /=, %=
Page 72
CSE4019 - Advanced Java Programming
Explain the concepts of control
structures in any problem
CSE4019 - Advanced Java Programming 73
What are control structures?
• Our programs so far consist of just a list of commands to be done in
order
• The program cannot choose whether or not to perform a command
• The program cannot perform the same command more than once
• Such programs are extremely limited!
• Control structures allow a program to base its behavior on the values
of variables
boolean
• boolean is one of the eight primitive types
• booleans are used to make yes/no decisions
• All control structures use booleans
• There are exactly two boolean values, true (“yes”) and false (“no”)
• boolean, true, and false are all lowercase
• booleans are named after George Boole, the founder of Boolean
logic
CSE4019 - Advanced Java Programming 74
Declaring boolean variables
• boolean variables are declared like any other kind of variable:
boolean hungry;
boolean passingGrade;
boolean taskCompleted = false;
• boolean values can be assigned to boolean variables:
taskCompleted = true;
CSE4019 - Advanced Java Programming 75
Numeric comparisons
•The following numeric comparisons each give
a boolean result:
x <y // is x less than y?
x <= y // is x less than or equal to y?
x == y // is x equal to y? (do not use =)
x != y // is x unequal to y?
x >= y // is x greater than or equal to y?
x >y // is x greater than y?
•Reminder: Don’t use == or != for
floating-point numbers
CSE4019 - Advanced Java Programming 76
The if statement
• The if statement has the form:
if (boolean-expression) statement
• Examples:
if (passingGrade) [Link]("Whew!");
if (x > largest) largest = x;
if ([Link] < 40.00) [Link]();
• The if statement controls one other statement
• Often this isn’t enough; we want to control a group of statements
CSE4019 - Advanced Java Programming 77
Compound statements
• We can use braces to group together several statements into one
“compound” statement:
{ statement; statement; ...; statement; }
• Braces can group any number of statements:
{} // OK--this is an “empty” statement
{ x = 0; } // OK--braces don’t hurt
{ temp = x;
x = y;
y = temp; } //typical use
• The compound statement is the only kind of statement that does not
end with a semicolon
CSE4019 - Advanced Java Programming 78
The if statement again
•The if statement controls one other statement, but it can be a
compound statement
•Example:
if (cost < amountInPocket) {
[Link]("Spending $" + cost);
amountInPocket = amountInPocket - cost;
}
•It’s good style to use braces even if the if statement controls
only a single statement:
if (cost > amountInPocket) {
[Link]("You can't afford it!");
}
•I personally make an exception to this style rule when the
controlled statement fits easily on the same line with the if:
if (x < 0) x = -x; // use absolute value of x
CSE4019 - Advanced Java Programming 79
Flowchart for the if statement
conditi true
on? statement
false
CSE4019 - Advanced Java Programming 80
The if-else statement
• The if-else statement chooses which of two statements to execute
• The if-else statement has the form:
if (condition) statement-to-execute-if-true ;
else statement-to-execute-if-false ;
• Either statement (or both) may be a compound statement
• Notice the semicolon after each statement
CSE4019 - Advanced Java Programming 81
Example if-else statements
•if (x >= 0) absX = x;
else absX = -x;
•if (itemCost <= bankBalance) {
writeCheck(itemCost);
bankBalance = bankBalance - itemCost;
}
else {
callHome();
askForMoreMoney(2 * itemCost);
}
CSE4019 - Advanced Java Programming 82
Flowchart for the if-else statement
true conditi false
on?
statement-1 statement-2
CSE4019 - Advanced Java Programming 83
Aside: the “mod” operator
• The modulo, or “mod,” operator returns the remainder of an integer
division
• The symbol for this operation is %
• Examples:
57 % 10 gives 7
20 % 6 gives 2
• Useful rule: x is divisible by y if x % y == 0
CSE4019 - Advanced Java Programming 84
Nesting if (or if-then) statements
• A year is a leap year if it is divisible by 4 but not by 100, unless it is
also divisible by 400
if (year % 4 == 0) {
if (year % 100 == 0) {
if (year % 400 == 0) leapYear = true;
else leapYear = false;
}
else leapYear = true;
}
else leapYear = false;
CSE4019 - Advanced Java Programming 85
Operations on booleans
• Assume p and q are booleans
• There are four basic operations on booleans:
• Negation (“not”):
!p is true if p is false (and false otherwise)
• Conjunction (“and”):
p && q is true if both p and q are true
• Disjunction (“or”):
p || q is true if either of p and q is true
• Exclusive or (“xor”):
p ^ q is true if just one of p and q is true
CSE4019 - Advanced Java Programming 86
Simpler tests
•A simpler leap-year test:
if (year % 4 == 0 &&
(year % 100 != 0 || year % 400 == 0))
leapYear = true;
else leapYear = false;
•An even simpler leap-year test:
leapYear = year % 4 == 0 &&
(year % 100 != 0 || year % 400 == 0);
CSE4019 - Advanced Java Programming 87
Conditional Operator
if (x > 0) y = 1
else y = -1;
is equivalent to
y = (x > 0) ? 1 : -1;
CSE4019 - Advanced Java Programming 88
switch Statements
switch (year)
{
case 7: annualInterestRate = 7.25;
break;
case 15: annualInterestRate = 8.50;
break;
case 30: annualInterestRate = 9.0;
break;
default: [Link](
"Wrong number of years, enter 7, 15, or 30");
}
CSE4019 - Advanced Java Programming 89
switch Statement Flow Chart
CSE4019 - Advanced Java Programming 90
Repetitions
• while Loops
• do Loops
• for Loops
• break and continue
CSE4019 - Advanced Java Programming 91
while Loop Flow Chart
CSE4019 - Advanced Java Programming 92
while Loops
while (continue-condition)
{
// loop-body;
}
Example 3.2: Using while Loops
[Link]
TestWhile
CSE4019 - Advanced Java Programming 93
do Loops
do
{
// Loop body;
} while (continue-condition)
CSE4019 - Advanced Java Programming 94
do Loop Flow Chart
CSE4019 - Advanced Java Programming 95
for Loops
for (control-variable-initializer;
continue-condition; adjustment-statement)
{
//loop body;
}
int i = 0;
while (i < 100)
{
[Link]("Welcome to Java! ” + i);
i++;
}
Example:
int i;
for (i = 0; i<100; i++)
{
[Link]("Welcome to Java! ” + i);
} CSE4019 - Advanced Java Programming 96
for Loop Flow Chart
CSE4019 - Advanced Java Programming 97
for Loop Examples
Examples for using the for loop:
● Example 3.3: Using for Loops
TestSum
● Example 3.4: Using Nested for Loops
TestMulTable
CSE4019 - Advanced Java Programming 98
The break Keyword
CSE4019 - Advanced Java Programming 99
The continue Keyword
CSE4019 - Advanced Java Programming 100
Using break and continue
Examples for using the break and continue
keywords:
● Example 3.5: [Link]
TestBreak
● Example 3.6: [Link]
TestContinue
CSE4019 - Advanced Java Programming 101
Describe the concepts of Classes
Classes and Objects in Java
102
Introduction
•Java is a true OO language and therefore the underlying
structure of all Java programs is classes.
•Anything we wish to represent in Java must be encapsulated
in a class that defines the “state” and “behaviour” of the
basic program components known as objects.
•Classes create objects and objects use methods to
communicate between them. They provide a convenient
method for packaging a group of logically related data items
and functions that work on them.
•A class essentially serves as a template for an object and
behaves like a basic data type “int”. It is therefore important
to understand how the fields and methods are defined in a
class and how they are used to build a Java program that
incorporates the basic OO concepts such as encapsulation,
inheritance, and polymorphism.
103 CSE4019 - Advanced Java Programming
Classes
• A class is a collection of fields (data) and methods (procedure or
function) that operate on that data.
Circle
centre
radius
circumference()
area()
104 CSE4019 - Advanced Java Programming
Classes
•A class is a collection of fields (data) and methods (procedure
or function) that operate on that data.
•The basic syntax for a class definition:
class ClassName [extends
SuperClassName]
{
[fields declaration]
[methods declaration]
}
•Bare bone class – no fields, no methods
public class Circle {
// my circle class
}
105 CSE4019 - Advanced Java Programming
Adding Fields: Class Circle with fields
• Add fields
public class Circle {
public double x, y; // centre coordinate
public double r; // radius of the circle
• The fields (data) are also called the instance varaibles.
106 CSE4019 - Advanced Java Programming
Adding Methods
•A class with only data fields has no life. Objects
created by such a class cannot respond to any
messages.
•Methods are declared inside the body of the class
but immediately after the declaration of data fields.
•The general form of a method declaration is:
type MethodName (parameter-list)
{
Method-body;
}
107 CSE4019 - Advanced Java Programming
Adding Methods to Class Circle
public class Circle {
public double x, y; // centre of the circle
public double r; // radius of circle
//Methods to return circumference and area
public double circumference() {
return 2*3.14*r;
}
Method Body
public double area() {
return 3.14 * r * r;
}
}
108 CSE4019 - Advanced Java Programming
Data Abstraction
• Declare the Circle class, have created a new data type – Data
Abstraction
• Can define variables (objects) of that type:
Circle aCircle;
Circle bCircle;
109 CSE4019 - Advanced Java Programming
Class of Circle cont.
• aCircle, bCircle simply refers to a Circle object, not an object itself.
aCircle bCircle
null null
Points to nothing (Null Reference) Points to nothing (Null Reference)
110 CSE4019 - Advanced Java Programming
Illustrate the concepts of Objects
CSE4019 - Advanced Java Programming 111
Creating objects of a class
• Objects are created dynamically using the new keyword.
• aCircle and bCircle refer to Circle objects
aCircle = new Circle() ; bCircle = new Circle() ;
112 CSE4019 - Advanced Java Programming
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;
bCircle = aCircle;
113 CSE4019 - Advanced Java Programming
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;
bCircle = aCircle;
Before Assignment Before Assignment
aCircle bCircle aCircle bCircle
P Q P Q
114 CSE4019 - Advanced Java Programming
Automatic garbage collection
Q
• The object does not have a reference and cannot be used in
future.
• The object becomes a candidate for automatic garbage collection.
• Java automatically collects garbage periodically and releases the
memory used to be used in the future.
115 CSE4019 - Advanced Java Programming
Accessing Object/Circle Data
• Similar to C syntax for accessing data defined in a structure.
[Link]
[Link](parameter-list)
Circle aCircle = new Circle();
aCircle.x = 2.0 // initialize center and radius
aCircle.y = 2.0
aCircle.r = 1.0
116 CSE4019 - Advanced Java Programming
Executing Methods in Object/Circle
• Using Object Methods:
sent ‘message’ to aCircle
Circle aCircle = new Circle();
double area;
aCircle.r = 1.0;
area = [Link]();
117 CSE4019 - Advanced Java Programming
Using Circle Class
// [Link]: Contains both Circle class and its user class
//Add Circle class code here
class MyMain
{
public static void main(String args[])
{
Circle aCircle; // creating reference
aCircle = new Circle(); // creating object
aCircle.x = 10; // assigning value to data field
aCircle.y = 20;
aCircle.r = 5;
double area = [Link](); // invoking method
double circumf = [Link]();
[Link]("Radius="+aCircle.r+" Area="+area);
[Link]("Radius="+aCircle.r+" Circumference ="+circumf);
}
} 118 CSE4019 - Advanced Java Programming
Example
class Animal {
public void move() { [Link]("Animals can move");
}}
class Dog extends Animal {
public void move() {
[Link]("Dogs can walk and run");
}}
public class TestDog {
public static void main(String args[]) {
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
[Link](); // runs the method in Animal class
[Link](); // runs the method in Dog class
}}
119 CSE4019 - Advanced Java Programming
Explain the concepts of Abstract
classes
CSE4019 - Advanced Java Programming 120
What is an Abstract class?
• Superclasses are created through the process called "generalization"
• Common features (methods or variables) are factored out of object
classifications (ie. classes).
• Those features are formalized in a class. This becomes the superclass
• The classes from which the common features were taken become subclasses to
the newly created super class
• Often, the superclass does not have a "meaning" or does not directly
relate to a "thing" in the real world
• It is an artifact of the generalization process
• Because of this, abstract classes cannot be instantiated
• They act as place holders for abstraction
CSE4019 - Advanced Java Programming 121
Abstract Class Example
• In the following example, the subclasses represent objects taken from
the problem domain.
• The superclass represents an abstract concept that does not exist "as
is" in the real world.
Abstract superclass: Vehicle Note: UML represents abstract
- make: String classes by displaying their name
- model: String in italics.
- tireCount: int
Car Truck
- trunkCapacity: int - bedCapacity: int
CSE4019 - Advanced Java Programming 122
What Are Abstract Classes Used For?
• Abstract classes are used heavily in Design Patterns
• Creational Patterns: Abstract class provides interface for creating objects. The
subclasses do the actual object creation
• Structural Patterns: How objects are structured is handled by an abstract class.
What the objects do is handled by the subclasses
• Behavioural Patterns: Behavioural interface is declared in an abstract
superclass. Implementation of the interface is provided by subclasses.
• Be careful not to over use abstract classes
• Every abstract class increases the complexity of your design
• Every subclass increases the complexity of your design
• Ensure that you receive acceptable return in terms of functionality given the
added complexity.
CSE4019 - Advanced Java Programming 123
Defining Abstract Classes
• Inheritance is declared using the "extends" keyword
• If inheritance is not defined, the class extends a class called Object
public abstract class Vehicle
{ Vehicle
private String make; - make: String
private String model; - model: String
private int tireCount; - tireCount: int
[...]
public class Car extends Vehicle
{ Car Truck
private int trunkCapacity; - trunkCapacity: int - bedCapacity: int
[...]
public class Truck extends Vehicle
{
private int bedCapacity; Often referred to as "concrete" classes
[...]
CSE4019 - Advanced Java Programming 124
Abstract Methods
• Methods can also be abstracted
• An abstract method is one to which a signature has been provided, but no
implementation for that method is given.
• An Abstract method is a placeholder. It means that we declare that a method
must exist, but there is no meaningful implementation for that methods within
this class
• Any class which contains an abstract method MUST also be abstract
• Any class which has an incomplete method definition cannot be
instantiated (ie. it is abstract)
• Abstract classes can contain both concrete and abstract methods.
• If a method can be implemented within an abstract class, and implementation
should be provided.
CSE4019 - Advanced Java Programming 125
Abstract Method Example
• In the following example, a Transaction's value can be computed, but
there is no meaningful implementation that can be defined within the
Transaction class.
• How a transaction is computed is dependent on the transaction's type
• Note: This is polymorphism.
Transaction
- computeValue(): int
RetailSale StockTrade
- computeValue(): int - computeValue(): int
CSE4019 - Advanced Java Programming 126
Defining Abstract Methods
• Inheritance is declared using the "extends" keyword
• If inheritance is not defined, the class extends a class called Object
Note: no implementation
public abstract class Transaction
{
public abstract int computeValue(); Transaction
- computeValue(): int
public class RetailSale extends Transaction
{
public int computeValue() RetailSale StockTrade
{ - computeValue(): int - computeValue(): int
[...]
public class StockTrade extends Transaction
{
public int computeValue()
{
[...]
CSE4019 - Advanced Java Programming 127
Describe the concepts of
Static classes and Inner
classes
CSE4019 - Advanced Java Programming 128
What is static
• The static keyword is used when a member variable of a class has to
be shared between all the instances of the class.
• All static variables and methods belong to the class and not to any
instance of the class
CSE4019 - Advanced Java Programming 129
When can we access static variable
• When a class is loaded by the virtual machine all the static variables
and methods are available for use.
• Hence we don’t need to create any instance of the class for using the
static variables or methods.
• Variables which don’t have static keyword in the definition are
implicitly non static.
CSE4019 - Advanced Java Programming 130
Example
Class staticDemo{
public static int a = 100; // All instances of staticDemo have this variable as a common `
variable
public int b =2 ;
public static showA(){
[Link](“A is “+a);
}
}
Class execClass{
public static void main(String args[]){
staticDemo.a = 35; // when we use the class name, the class is loaded, direct access to a without any
instance
staticDemo.b=22; // ERROR this is not valid for non static variable
staticDemo demo = new staticDemo();
demo.b = 200; // valid to set a value for a non static variable after creating an instance.
[Link](); //prints 35
}
}
CSE4019 - Advanced Java Programming 131
Static and Non-static
• We can access static variables without creating an instance of the
class
• As they are already available at class loading time, we can use them
in any of our non static methods.
• We cannot use non static methods and variables without creating an
instance of the class as they are bound to the instance of the class.
• They are initialized by the constructor when we create the object
using new operator.
CSE4019 - Advanced Java Programming 132
How it works Basic Steps of how objects are created
1. Class is loaded by JVM
2. Static variable and methods are loaded
and initialized and available for use
3. Constructor is called to instantiate the
non static variables
4. Non static variables and methods are
now available
• As all the non static variable are
available only after the constructor
is called, there is a restriction on
using non static variable in static
methods.
CSE4019 - Advanced Java Programming 133
Why do we need this
• Static methods are identified to be mostly used when we are writing
any utility methods.
• We can also use static variables when sharing data.
• When sharing data do keep in mind about multithreading can cause
inconsistency in the value. (synchronize the variable)
CSE4019 - Advanced Java Programming 134
Inner Classes
• Inner classes are classes defined within other classes
• The class that includes the inner class is called the outer class
• There is no particular location where the definition of the inner class (or
classes) must be place within the outer class
• Placing it first or last, however, will guarantee that it is easy to find
Simple Uses of Inner Classes
•An inner class definition is a member of the outer class
in the same way that the instance variables and
methods of the outer class are members
• An inner class is local to the outer class definition
• The name of an inner class may be reused for something else
outside the outer class definition
• If the inner class is private, then the inner class cannot be
accessed by name outside the definition of the outer class
CSE4019 - Advanced Java Programming 135
Inner/Outer Classes
public class Outer
{
private class Inner
{
// inner class instance variables
// inner class methods
} // end of inner class definition
// outer class instance variables
// outer class methods
}
Simple Uses of Inner Classes
•There are two main advantages to inner classes
• They can make the outer class more self-contained since
they are defined inside a class
• Both of their methods have access to each other's private
methods and instance variables
CSE4019 - Advanced Java Programming 136
Apply the concepts of Packages in
any problem
CSE4019 - Advanced Java Programming 137
Introduction
•A java package is a group of similar types of classes,
interfaces and sub-packages.
•Package in java can be categorized in two form, built-in
package and user-defined package.
•There are many built-in packages such as java, lang,
awt, javax, swing, net, io, util, sql etc.
•Here, we will have the detailed learning of creating and
using user-defined packages.
CSE4019 - Advanced Java Programming 138
Introduction
Advantage of Java Package
1) Java package is used to categorize the classes and
interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
CSE4019 - Advanced Java Programming 139
Introduction
CSE4019 - Advanced Java Programming 140
Creation Of Jar Files
•In Java source files the package the file belongs to is
specified with the package keyword .
•package [Link];
•JAR Files are created with the jar command-line utility.
• The command “jar cf [Link] *.class” compresses all
*.class files into the JAR file [Link].
CSE4019 - Advanced Java Programming 141
•Some package are
•lang Package: Lang stands for language. This package
contains those class which are essential for every java
program.
E.g. String and System class
Lang is the default package of java which means it is optional
to import Lang package in program
Syntax of Import package:-
import [package name].*; // (all class)
import [package name].[class name];//(Single class)
CSE4019 - Advanced Java Programming 142
•Some package are
•io package: io stands for input/output. This package
contains those class which are essential for input and
output. Some classes of input/output package are;
E.g. – DataInputStream, BufferReader,
DataInoutStramReader
•util package: util stands for utility package this package
contain different type of classes related to various task.
E.g.: Date, time, calendar, array, vector. Array List etc.
CSE4019 - Advanced Java Programming 143
•Some package are
•awt package (swing): awt stands for abstract windowing
tool. With the help of this package we can create GUI
interface. This package provide many GUI tools.
E.g.: Command button, choice, list, radio, etc.
awt contain a sub package name “even”.
•applet: with the help of applet function we can create a java
program which can be embedded into HTML page by which
web browser execute the java program. Web browser must
be java enabled.
CSE4019 - Advanced Java Programming 144
•Some package are
•Sql Package: sql stands for structure query language. This
package provides a complete range of classes which is
needed for jdbc (java database connectivity). Some
important classes of sql package are:
E.g.: connection, ResultSet, PrepareStatement, etc.
•Net package: net stands for networking. This package
contains classes to implement or create connection between
two or more systems or if we want to implement client
server approach then. We can use the classes of net
package.
E.g.: TCP/IP, Request, etc.
CSE4019 - Advanced Java Programming 145
How to create package in Java
1. First create a directory within name of package.
2. Create a java file in newly created directory.
3. In this java file you must specify the package
name with the help of package keyword.
4. Save this file with same name of public class
Note: only one class in a program can declare as
public.
5. Now you can use this package in your program.
CSE4019 - Advanced Java Programming 146
Example Program
• ALGORITHM:
• STEP 1:Start the process
• STEP 2:Create a package1, package2 and package 3 to define the
triangle shape.
• STEP 3:Create a main class.
• STEP 4: Import the all three packages into main class.
• STEP 5:To get the number of rows as an input. Based on the input the
triangle is processed.
• STEP 6: Run the program.
• STEP 7:Stop the process
CSE4019 - Advanced Java Programming 147
PACKAGE ONE: void sec(int row,int i)
{
package one; for(k=row-i;k<row;k++)
public class cls1 {
{ [Link]("* ");
int j,k; }
public void first(int row,int i) for(j=1;j<=row-i;j++)
{ {
for(j=1;j<=row-i;j++) [Link](" ");
{ }
[Link](" ");
} }
for(k=row-i;k<row;k++) }
{
[Link]("* ");
}
space(row);
sec(row,i);
}
void space(int row)
{
for(j=1;j<=row;j++)
{
[Link](" ");
}
}
CSE4019 - Advanced Java Programming 148
PACKAGE TWO: void sec(int row,int i)
{
package [Link]; for(j=1;j<=row-i;j++)
public class cls2 {
{ [Link]("* ");
int j,k; }
public void second(int row,int i) for(k=row-i;k<row;k++)
{ {
for(k=row-i;k<row;k++) [Link](" ");
{ }
[Link](" "); }
} }
for(j=1;j<=row-i;j++)
{
[Link](" *");
}
space(row);
sec(row,i);
}
void space(int row)
{
for(j=1;j<=row;j++)
{
[Link](" ");
}
}
CSE4019 - Advanced Java Programming 149
PACKAGE THREE: void sh(int row,int i)
{
package [Link]; for(k=row-i;k<row;k++) {
public class cls3 [Link](" "); }
{ for(j=1;j<=row-i;j++) {
int j,k; [Link](" * "); }
public void third(int row,int i) }}
{
for(j=1;j<=row-i;j++)
{
[Link](" ");
}
for(k=row-i;k<row;k++)
{
[Link]("* ");
}
space(row);
sh(row,i);
}
void space(int row)
{
int j;
for(j=1;j<=row;j++)
{
[Link](" ");
}
}
CSE4019 - Advanced Java Programming 150
MAIN CLASS: for(i=0;i<=row;i++)
{
import [Link].*; [Link](row,i);
import one.*; [Link]("\n");
import [Link].*; }
import [Link].*; [Link]("\n");
class m for(i=0;i<=row;i++)
{ {
public static void main(String args[])throws [Link](row,i);
IOException [Link]("\n");
{ }
int row,i; }
BufferedReader sd=new BufferedReader(new }
InputStreamReader([Link]));
[Link]("ENTER number of rows ");
row=[Link]([Link]());
cls1 a=new cls1();
cls2 b=new cls2();
cls3 c=new cls3();
for(i=0;i<=row;i++)
{
[Link](row,i);
[Link]("\n");
}
[Link]("\n");
CSE4019 - Advanced Java Programming 151
OUTPUT:
D:\>javac [Link]
D:\>java m
ENTER number of rows
4
* *
** **
*** ***
**** ****
**** ****
*** ***
** **
* *
* * * *
* * * *
** * *
*** *
****
CSE4019 - Advanced Java Programming 152
Apply the concepts of wrapper classes in
any problem
CSE4019 - Advanced Java Programming 153
Wrapper class in Java
• Wrapper class in java provides the mechanism to convert primitive into
object and object into primitive.
• The main difference is that whereas variables can be declared in Java as
double, short, int, or char, etc., data types, the eight primitive wrapper
classes create instantiated objects and methods that inherit but hide the
eight primitive data types, not variables that are assigned data type
values.
Primitive Wrapper Primitive Wrapper
Type Class Type Class
boolean Boolean float Float
byte Byte int Integer
char Character long Long
double Double short Short
CSE4019 - Advanced Java Programming 154
Primitive to Wrapper
public class WrapperExample1{
public static void main(String args[]){
//Converting int into Integer
int a=20;
Integer i=[Link](a);//converting int into Integer
Integer j=a;//autoboxing, now compiler will write Intege
[Link](a) internally
[Link](a+" "+i+" "+j);
}}
Output:
20 20 20
CSE4019 - Advanced Java Programming 155
Wrapper to Primitive
public class WrapperExample2{
public static void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3);
int i=[Link]();//converting Integer to int
int j=a;//unboxing, now compiler will write [Link]() i
nternally
[Link](a+" "+i+" "+j);
}}
Output:
3 3
CSE4019 - Advanced Java Programming
3 156
Apply the concepts of Interfaces in
any application
CSE4019 - Advanced Java Programming 157
What is an Interface?
• An interface is similar to an abstract class with the following
exceptions:
• All methods defined in an interface are abstract. Interfaces can contain no
implementation
• Interfaces cannot contain instance variables. However, they can contain public
static final variables (ie. constant class variables)
• Interfaces are declared using the "interface" keyword
• If an interface is public, it must be contained in a file which has the
same name.
• Interfaces are more abstract than abstract classes
• Interfaces are implemented by classes using the "implements"
keyword.
CSE4019 - Advanced Java Programming 158
Declaring an Interface
In [Link]:
public interface Steerable
{
public void turnLeft(int degrees); When a class "implements" an
public void turnRight(int degrees); interface, the compiler ensures that
} it provides an implementation for
all methods defined within the
interface.
In [Link]:
public class Car extends Vehicle implements Steerable
{
public int turnLeft(int degrees)
{
[...]
}
public int turnRight(int degrees)
{
[...]
}
CSE4019 - Advanced Java Programming 159
Implementing Interfaces
• A Class can only inherit from one superclass. However, a class may
implement several Interfaces
• The interfaces that a class implements are separated by commas
• Any class which implements an interface must provide an
implementation for all methods defined within the interface.
• NOTE: if an abstract class implements an interface, it NEED NOT implement
all methods defined in the interface. HOWEVER, each concrete subclass
MUST implement the methods defined in the interface.
• Interfaces can inherit method signatures from other interfaces.
CSE4019 - Advanced Java Programming 160
Declaring an Interface
In [Link]:
public class Car extends Vehicle implements Steerable, Driveable
{
public int turnLeft(int degrees)
{
[...]
}
public int turnRight(int degrees)
{
[...]
}
// implement methods defined within the Driveable interface
CSE4019 - Advanced Java Programming 161
Inheriting Interfaces
• If a superclass implements an interface, it's subclasses also implement
the interface
public abstract class Vehicle implements Steerable
{ Vehicle
private String make; - make: String
[...] - model: String
- tireCount: int
public class Car extends Vehicle
{ Car Truck
private int trunkCapacity; - trunkCapacity: int - bedCapacity: int
[...]
public class Truck extends Vehicle
{
private int bedCapacity;
[...]
CSE4019 - Advanced Java Programming 162
Multiple Inheritance?
• Some people (and textbooks) have said that allowing classes to
implement multiple interfaces is the same thing as multiple
inheritance
• This is NOT true. When you implement an interface:
• The implementing class does not inherit instance variables
• The implementing class does not inherit methods (none are defined)
• The Implementing class does not inherit associations
• Implementation of interfaces is not inheritance. An interface defines a
list of methods which must be implemented.
CSE4019 - Advanced Java Programming 163
Interfaces as Types
• When a class is defined, the compiler views the class as a new type.
• The same thing is true of interfaces. The compiler regards an
interface as a type.
• It can be used to declare variables or method parameters
int i;
Car myFleet[];
Steerable anotherFleet[];
[...]
myFleet[i].start();
anotherFleet[i].turnLeft(100);
anotherFleet[i+1].turnRight(45);
CSE4019 - Advanced Java Programming 164
Abstract Classes Versus Interfaces
• When should one use an Abstract class instead of an interface?
• If the subclass-superclass relationship is genuinely an "is a" relationship.
• If the abstract class can provide an implementation at the appropriate level of
abstraction
• When should one use an interface in place of an Abstract Class?
• When the methods defined represent a small portion of a class
• When the subclass needs to inherit from another class
• When you cannot reasonably implement any of the methods
CSE4019 - Advanced Java Programming 165
CSE4019 - Advanced Java Programming 166
CSE4019 - Advanced Java Programming 167
CSE4019 - Advanced Java Programming 168
CSE4019 - Advanced Java Programming 169
CSE4019 - Advanced Java Programming 170
Describe the concepts of this and
super keyword
CSE4019 - Advanced Java Programming 171
this keyword
class Vehicle{
Vehicle(){[Link]("
Vehicle is created");}
}
class Bike6 extends Vehicle{
int speed;
Bike6(int speed){
[Link]=speed;
[Link](speed);
}
public static void main(String
args[]){
Bike6 b=new Bike6(10);
}
CSE4019 - Advanced Java Programming 172
}
super keyword
class Vehicle{
Vehicle(){[Link]("Vehicle is
created");}
}
class Bike5 extends Vehicle{
Bike5(){
super();//will invoke parent class const
ructor
[Link]("Bike is created");
}
public static void main(String args[]){
Bike5 b=new Bike5();
}
CSE4019 - Advanced Java Programming 173
}
class Parentclass {
//Overridden method
void display(){
[Link]("Parent class method");
}
}
class Subclass extends Parentclass {
//Overriding method
void display(){
[Link]("Child class method");
}
void printMsg(){
//This would call Overriding method display();
//This would call Overridden method
[Link]();
}
public static void main(String args[]){
Subclass obj= new Subclass();
[Link]();
} }
CSE4019 - Advanced Java Programming 174
Apply the concepts of string handling
functions in various applications
CSE4019 - Advanced Java Programming 175
String Handling
•Java string is a sequence of characters. They are objects of
type String.
•Once a String object is created it cannot be changed. Stings
are Immutable.
•To get changeable strings use the class called StringBuffer.
•String and StringBuffer classes are declared final, so there
cannot be subclasses of these classes.
•The default constructor creates an empty string.
String s = new String();
CSE4019 - Advanced Java Programming 176
Creating Strings
• String str = "abc"; is equivalent to:
char data[] = {'a', 'b', 'c'};
String str = new String(data);
•If data array in the above example is modified after the
string object str is created, then str remains unchanged.
•Construct a string object by passing another string object.
String str2 = new String(str);
CSE4019 - Advanced Java Programming 177
String Operations
•The length() method returns the length of the string.
Eg: [Link](“Hello”.length()); // prints 5
•The + operator is used to concatenate two or more strings.
Eg: String myname = “Harry”
String str = “My name is” + myname+ “.”;
•For string concatenation the Java compiler converts an
operand to a String whenever the other operand of the + is a
String object.
CSE4019 - Advanced Java Programming 178
String Operations
•Characters in a string can be extracted in a number of ways.
public char charAt(int index)
•Returns the character at the specified index. An index
ranges from 0 to length() - 1. The first character of the
sequence is at index 0, the next at index 1, and so on, as
for array indexing.
char ch;
ch = “abc”.charAt(1); // ch = “b”
CSE4019 - Advanced Java Programming 179
String Operations
•getChars() - Copies characters from this string into the
destination character array.
public void getChars(int srcBegin, int srcEnd,
char[] dst, int dstBegin)
• srcBegin - index of the first character in the string to copy.
• srcEnd - index after the last character in the string to copy.
• dst - the destination array.
• dstBegin - the start offset in the destination array.
CSE4019 - Advanced Java Programming 180
String Operations
• equals() - Compares the invoking string to the specified object. The
result is true if and only if the argument is not null and is a String object
that represents the same sequence of characters as the invoking object.
public boolean equals(Object anObject)
• equalsIgnoreCase()- Compares this String to another String, ignoring
case considerations. Two strings are considered equal ignoring case if
they are of the same length, and corresponding characters in the two
strings are equal ignoring case.
public boolean equalsIgnoreCase(String
anotherString)
CSE4019 - Advanced Java Programming 181
String Operations
•startsWith() – Tests if this string starts with the specified
prefix.
public boolean startsWith(String prefix)
“Figure”.startsWith(“Fig”); // true
•endsWith() - Tests if this string ends with the specified
suffix.
public boolean endsWith(String suffix)
“Figure”.endsWith(“re”); // true
CSE4019 - Advanced Java Programming 182
String Operations
•startsWith() -Tests if this string starts with the specified
prefix beginning at a specified index.
public boolean startsWith(String prefix,
int toffset)
prefix - the prefix.
toffset - where to begin looking in the
string.
“figure”.startsWith(“gure”, 2); // true
CSE4019 - Advanced Java Programming 183
String Operations
•compareTo() - Compares two strings lexicographically.
• The result is a negative integer if this String object lexicographically
precedes the argument string.
• The result is a positive integer if this String object lexicographically
follows the argument string.
• The result is zero if the strings are equal.
• compareTo returns 0 exactly when the equals(Object) method
would return true.
public int compareTo(String anotherString)
public int compareToIgnoreCase(String str)
CSE4019 - Advanced Java Programming 184
String Operations
indexOf – Searches for the first occurrence of a character or substring.
Returns -1 if the character does not occur.
public int indexOf(int ch)- Returns the index within this
string of the first occurrence of the specified character.
public int indexOf(String str) - Returns the index within
this string of the first occurrence of the specified substring.
String str = “How was your day today?”;
[Link](‘t’);
str(“was”);
CSE4019 - Advanced Java Programming 185
String Operations
public int indexOf(int ch, int fromIndex)- Returns
the index within this string of the first occurrence of the specified
character, starting the search at the specified index.
public int indexOf(String str, int fromIndex) -
Returns the index within this string of the first occurrence of the
specified substring, starting at the specified index.
String str = “How was your day today?”;
[Link](‘a’, 6);
str(“was”, 2);
CSE4019 - Advanced Java Programming 186
String Operations
lastIndexOf() –Searches for the last occurrence of a character
or substring. The methods are similar to indexOf().
substring() - Returns a new string that is a substring of this
string. The substring begins with the character at the
specified index and extends to the end of this string.
public String substring(int beginIndex)
Eg: "unhappy".substring(2) returns "happy"
CSE4019 - Advanced Java Programming 187
String Operations
•public String
substring(int beginIndex,
int endIndex)
Eg: "smiles".substring(1, 5) returns
"mile“
CSE4019 - Advanced Java Programming 188
String Operations
concat() - Concatenates the specified string to the end of this
string.
If the length of the argument string is 0, then this String
object is returned.
Otherwise, a new String object is created, containing the
invoking string with the contents of the str appended to it.
public String concat(String str)
"to".concat("get").concat("her") returns
"together"
CSE4019 - Advanced Java Programming 189
String Operations
•replace()- Returns a new string resulting from replacing all
occurrences of oldChar in this string with newChar.
public String replace(char oldChar, char newChar)
"mesquite in your cellar".replace('e', 'o')
returns "mosquito in your collar"
CSE4019 - Advanced Java Programming 190
String Operations
•trim() - Returns a copy of the string, with leading and trailing
whitespace omitted.
public String trim()
String s = “ Hi Mom! “.trim();
S = “Hi Mom!”
•valueOf() – Returns the string representation of the char
array argument.
public static String valueOf(char[] data)
CSE4019 - Advanced Java Programming 191
String Operations
•The contents of the character array are copied; subsequent
modification of the character array does not affect the
newly created string.
Other forms are:
public static String valueOf(char c)
public static String valueOf(boolean b)
public static String valueOf(int i)
public static String valueOf(long l)
public static String valueOf(float f)
public static String valueOf(double d)
CSE4019 - Advanced Java Programming 192
String Operations
•toLowerCase(): Converts all of the characters in a String to
lower case.
•toUpperCase(): Converts all of the characters in this String
to upper case.
public String toLowerCase()
public String toUpperCase()
Eg: “HELLO THERE”.toLowerCase();
“hello there”.toUpperCase();
CSE4019 - Advanced Java Programming 193
StringBuffer
•A StringBuffer is like a String, but can be modified.
•The length and content of the StringBuffer sequence can be
changed through certain method calls.
•StringBuffer defines three constructors:
• StringBuffer()
• StringBuffer(int size)
• StringBuffer(String str)
CSE4019 - Advanced Java Programming 194
StringBuffer Operations
•The principal operations on a StringBuffer are the append
and insert methods, which are overloaded so as to accept
data of any type.
Here are few append methods:
StringBuffer append(String str)
StringBuffer append(int num)
•The append method always adds these characters at the end
of the buffer.
CSE4019 - Advanced Java Programming 195
StringBuffer Operations
•The insert method adds the characters at a specified point.
Here are few insert methods:
StringBuffer insert(int index, String str)
StringBuffer append(int index, char ch)
Index specifies at which point the string will be inserted into
the invoking StringBuffer object.
CSE4019 - Advanced Java Programming 196
StringBuffer Operations
•delete() - Removes the characters in a substring of this
StringBuffer. The substring begins at the specified start and
extends to the character at index end - 1 or to the end of the
StringBuffer if no such character exists. If start is equal to
end, no changes are made.
public StringBuffer delete(int start, int end)
CSE4019 - Advanced Java Programming 197
StringBuffer Operations
•replace() - Replaces the characters in a substring of this
StringBuffer with characters in the specified String.
public StringBuffer replace(int start, int end,
String str)
•substring() - Returns a new String that contains a
subsequence of characters currently contained in this
StringBuffer. The substring begins at the specified index and
extends to the end of the StringBuffer.
public String substring(int start)
CSE4019 - Advanced Java Programming 198
StringBuffer Operations
•reverse() - The character sequence contained in this string
buffer is replaced by the reverse of the sequence.
public StringBuffer reverse()
•length() - Returns the length of this string buffer.
public int length()
CSE4019 - Advanced Java Programming 199
StringBuffer Operations
•capacity() - Returns the current capacity of the String buffer.
The capacity is the amount of storage available for newly
inserted characters.
public int capacity()
• charAt() - The specified character of the sequence currently
represented by the string buffer, as indicated by the index
argument, is returned.
public char charAt(int index)
CSE4019 - Advanced Java Programming 200
StringBuffer Operations
•getChars() - Characters are copied from this string buffer
into the destination character array dst. The first character
to be copied is at index srcBegin; the last character to be
copied is at index srcEnd-1.
public void getChars(int srcBegin, int srcEnd,
char[] dst, int dstBegin)
• setLength() - Sets the length of the StringBuffer.
public void setLength(int newLength)
CSE4019 - Advanced Java Programming 201
Examples: StringBuffer
StringBuffer sb = new StringBuffer(“Hello”);
[Link](); // 5
[Link](); // 21 (16 characters room is
added if no size is specified)
[Link](1); // e
[Link](1,’i’); // Hillo
[Link](2); // Hi
[Link](“l”).append(“l”); // Hill
[Link](0, “Big “); // Big Hill
CSE4019 - Advanced Java Programming 202
Examples: StringBuffer
[Link](3, 11, “”); // Big
[Link](); // gib
CSE4019 - Advanced Java Programming 203
Exception Handling
Apply the try-catch block in given
problem.
CSE4019 - Advanced Java Programming 204
What is an exception?
•An exception is an error condition that changes the normal flow
of control in a program
•Exceptions in Java separates error handling from main business
logic
•Based on ideas developed in Ada, Eiffel and C++
•Java has a uniform approach for handling all synchronous errors
∙ From very unusual (e.g. out of memory)
∙ To more common ones your program should check itself (e.g. index out
of bounds)
∙ From Java run-time system errors (e.g., divide by zero)
∙ To errors that programmers detect and raise deliberately
CSE4019 - Advanced Java Programming 205
CSE4019 - Advanced Java Programming 206
CSE4019 - Advanced Java Programming 207
scenarios where an exception occurs
• 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.
CSE4019 - Advanced Java Programming 208
Exception Handling Keywords
• throw – keyword is used to throw exception to the runtime to handle
it.
• throws We can provide multiple exceptions in the throws clause and
it can be used with main() method also.
• try-catch – We use try-catch block for exception handling in our
code. try is the start of the block and catch is at the end of try block
to handle the exceptions. We can have multiple catch blocks with a
try and try-catch block can be nested also. catch block requires a
parameter that should be of type Exception.
• finally – finally block is optional and can be used only with try-catch
block. Since exception halts the process of execution, we might have
some resources open that will not get closed, so we can use finally
block. finally block gets executed always, whether exception
occurred or not.
CSE4019 - Advanced Java Programming 209
Types of Exception
• Checked exceptions − A checked exception is an exception that
occurs at the compile time. These exceptions cannot simply be
ignored at the time of compilation, the programmer should take care
of (handle) these exceptions.
• Unchecked exceptions − An unchecked exception is an exception
that occurs at the time of execution. These are also called
as Runtime Exceptions. These include programming bugs, such as
logic errors or improper use of an API. Runtime exceptions are
ignored at the time of compilation.
CSE4019 - Advanced Java Programming 210
Following is the list of Java Checked Exceptions Defined in [Link].
[Link]. Exception & Description
1 ClassNotFoundException - Class not found.
CloneNotSupportedException
2 Attempt to clone an object that does not implement the Cloneable interface.
3 IllegalAccessException - Access to a class is denied.
InstantiationException - Attempt to create an object of an abstract class or
4 interface.
InterruptedException - One thread has been interrupted by another thread.
5
6 NoSuchFieldException - A requested field does not exist.
7 NoSuchMethodException - A requested method does not exist.
CSE4019 - Advanced Java Programming 211
Following is the list of Java Unchecked RuntimeException.
[Link]. Exception & Description
1 ArithmeticException - Arithmetic error, such as divide-by-zero.
2 ArrayIndexOutOfBoundsException - Array index is out-of-bounds.
3 ArrayStoreException - Assignment to an array element of an incompatible type.
4 ClassCastException - Invalid cast.
5 IllegalArgumentException - Illegal argument used to invoke a method.
IllegalMonitorStateException - Illegal monitor operation, such as waiting on an unlocked
6
thread.
7 IllegalStateException - Environment or application is in incorrect state.
IllegalThreadStateException - Requested operation not compatible with the current
8
thread state.
9 IndexOutOfBoundsException - Some type of index is out-of-bounds.
10 NegativeArraySizeException - Array created with a negative size.
11 NullPointerException - Invalid use of a null reference.
12 NumberFormatException - Invalid conversion of a string to a numeric format.
13 SecurityException - Attempt to violate security.
14 StringIndexOutOfBounds - Attempt to index outside the bounds of a string.
15 UnsupportedOperationException - An unsupported operation was encountered.
CSE4019 - Advanced Java Programming 212
Catching an exception
try { // statement that could throw an exception
}
catch (<exception type> e) {
// statements that handle the exception
}
catch (<exception type> e) { //e higher in hierarchy
// statements that handle the exception
}
finally {
// release resources
}
//other statements
• At most one catch block executes
• finally block always executes once, whether there’s an error or not
CSE4019 - Advanced Java Programming 213
Execution of try catch blocks
• For normal execution:
• try block executes, then finally block executes, then other statements execute
• When an error is caught and the catch block throws an exception or returns:
• try block is interrupted
• catch block executes (until throw or return statement)
• finally block executes
• When error is caught and catch block doesn’t throw an exception or return:
• try block is interrupted
• catch block executes
• finally block executes
• other statements execute
• When an error occurs that is not caught:
• try block is interrupted
• finally block executes
CSE4019 - Advanced Java Programming 214
Example:
try { p.a = 10; }
catch (NullPointerException e)
{ [Link]("p was null"); }
catch (Exception e)
{ [Link]("other error occurred"); }
catch (Object obj)
{ [Link]("Who threw that object?"); }
finally { [Link](“final processing"); }
[Link](“Continue with more statements");
CSE4019 - Advanced Java Programming 215
Example of Checked exceptions
import [Link];
import [Link];
public class FilenotFound_Demo {
public static void main(String args[]) {
File file = new File("E://[Link]");
FileReader fr = new FileReader(file);
}
}
Output
C:\>javac FilenotFound_Demo.java
FilenotFound_Demo.java:8: error: unreported exception
FileNotFoundException; must be caught or declared to be thrown
FileReader fr = new FileReader(file);
^
1 error
CSE4019 - Advanced Java Programming 216
Example of unchecked exceptions
public class Unchecked_Demo {
public static void main(String args[]) {
int num[] = {1, 2, 3, 4};
[Link](num[5]);
}
}
Output
Exception in thread "main"
[Link]: 5
at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)
CSE4019 - Advanced Java Programming 217
DivideByZero exception
public class MainClass {
public static void main(String args[]) {
int urAns, urDiv;
try {
urDiv = 0;
urAns = 25 / urDiv;
[Link]("Do you really think this will print out? No! It won't!");
catch (ArithmeticException e) {
[Link]("Division by zero not Possible!");
[Link]("This will print out after Exception Handling");
}
CSE4019 - Advanced Java Programming 218
NullPointerException
package [Link];
class Exception2
{
public static void main(String args[])
{
try{
String str=null;
[Link] ([Link]());
}catch(NullPointerException e){
[Link]("NullPointerException..");
}
}
}
Output:
NullPointerException..
CSE4019 - Advanced Java Programming 219
ArithmeticException
class ExceptionDemo1
{
public static void main(String args[])
{
try{
int num1=30, num2=0;
int output=num1/num2;
[Link] ("Result = " +output);
}
catch(ArithmeticException e){
[Link] ("Arithmetic Exception: You can't divide an integer by 0");
}
}
}
Output of above program:
Arithmetic Exception: You can't divide an integer by 0
CSE4019 - Advanced Java Programming 220
ArrayIndexOutOfBounds Exception
class ExceptionDemo2
{
public static void main(String args[])
{
try{
int a[]=new int[10];
//Array has only 10 elements
a[11] = 9;
}
catch(ArrayIndexOutOfBoundsException e){
[Link] ("ArrayIndexOutOfBounds");
}
}
}
Output:
ArrayIndexOutOfBounds
CSE4019 - Advanced Java Programming 221
NumberFormat Exception
class ExceptionDemo3
{
public static void main(String args[])
{
try{
int num=[Link] ("XYZ") ;
[Link](num);
}catch(NumberFormatException e){
[Link]("Number format exception occurred");
}
}
}
Output:
Number format exception occurred
CSE4019 - Advanced Java Programming 222
StringIndexOutOfBound Exception
class ExceptionDemo4
{
public static void main(String args[])
{
try{
String str="easysteps2buildwebsite";
[Link]([Link]());;
char c = [Link](0);
c = [Link](40);
[Link](c);
}catch(StringIndexOutOfBoundsException e){
[Link]("StringIndexOutOfBoundsException!!");
}
}
}
Output:
22
StringIndexOutOfBoundsException!!
CSE4019 - Advanced Java Programming 223
Apply the throw keyword with given
problem.
CSE4019 - Advanced Java Programming 224
Throwing and catching
• An error can throw an exception
throw <exception object>;
• By default, exceptions result in the thread terminating after printing an
error message
• However, exception handlers can catch specified exceptions and recover
from error
catch (<exception type> e) {
//statements that handle the
exception
}
CSE4019 - Advanced Java Programming 225
Throwing an exception
• Example creates a subclass of Exception and throws an exception:
class MyException extends Exception { }
class MyClass {
void oops()
{ if (/* no error occurred */)
{ /* normal processing */ }
else { /* error occurred */
throw new MyException();
}
} //oops
}//class MyClass
CSE4019 - Advanced Java Programming 226
Apply the concepts of Custom Exception in
given scenario.
• If you are creating your own Exception that is known as custom
exception or user-defined exception. Java custom exceptions are used to
customize the exception according to user need.
• By the help of custom exception, you can have your own exception and
message.
CSE4019 - Advanced Java Programming 227
class InvalidAgeException extends Exception{
InvalidAgeException(String s){
super(s);
Output:
} Exception occured:
} InvalidAgeException:not
valid
class TestCustomException1{
rest of the code...
static void validate(int age)throws InvalidAgeException{
if(age<18)
throw new InvalidAgeException("not valid");
else
[Link]("welcome to vote");
}
public static void main(String args[]){
try{
validate(13);
}catch(Exception m){[Link]("Exception occured: "+m);}
[Link]("rest of the code...");
}
}
CSE4019 - Advanced Java Programming 228
Multithreading
CSE4019 - Advanced Java Programming 229
Explain the concepts of Life Cycle of a
Thread.
• Multithreading in java is a process of executing
multiple threads simultaneously.
• Thread is basically a lightweight sub-process, a
smallest unit of processing.
• Multiprocessing and multithreading, both are used to
achieve multitasking.
• But we use multithreading than multiprocessing
because threads share a common memory area.
• They don't allocate separate memory area so saves
memory, and context-switching between the threads
takes less time than process.
• Java Multithreading is mostly used in games,
animation etc.
CSE4019 - Advanced Java Programming 230
What is Thread in java
• A thread is a lightweight sub process, a smallest unit of
processing. It is a separate path of execution.
• Threads are independent, if there occurs exception in one
thread, it doesn't affect other threads. It shares a common
memory area.
• As shown in the above figure,
thread is executed inside the
process.
• There is context-switching
between the threads.
• There can be multiple
processes inside the OS and
one process can have multiple
threads.
CSE4019 - Advanced Java Programming 231
Life cycle of a Thread (Thread States)
• A thread can be in one of the five states. According to
sun, there is only 4 states in thread life cycle in
java new, runnable, non-runnable and terminated. There
is no running state.
• But for better understanding the threads, we are
explaining it in the 5 states.
• The life cycle of the thread in java is controlled by JVM.
The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
CSE4019 - Advanced Java Programming 232
CSE4019 - Advanced Java Programming 233
Life cycle of a Thread (Thread States)
1) New
• The thread is in new state if you create an instance of
• Thread class but before the invocation of start() method.
2) Runnable
• The thread is in runnable state after invocation of start() method, but
the thread scheduler has not selected it to be the running thread.
3) Running
• The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
• This is the state when the thread is still alive, but is currently not
eligible to run.
5) Terminated
• A thread is in terminated or dead state when its run() method exits.
CSE4019 - Advanced Java Programming 234
Apply the concepts of Creating Thread and
Thread Schedular in given situation.
How to create thread
There are two ways to create a thread:
[Link] extending Thread class
[Link] implementing Runnable interface.
Thread class:
[Link] class provide constructors and methods to create and perform operations on a thread.
[Link] class extends Object class and implements Runnable interface.
Commonly used Constructors of Thread class:
• Thread()
• Thread(String name)
• Thread(Runnable r)
• Thread(Runnable r,String name)
CSE4019 - Advanced Java Programming 235
Commonly used methods of Thread class:
1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the [Link] calls the run() method on the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily
cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing thread.
11. public int getId(): returns the id of the thread.
12. public [Link] getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily pause and allow other
threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been interrupted.
CSE4019 - Advanced Java Programming 236
Runnable interface:
The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread. Runnable interface have only one method
named run().
1. public void run(): is used to perform action for a thread.
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs
following tasks:
•A new thread starts(with new callstack).
•The thread moves from New state to the Runnable state.
•When the thread gets a chance to execute, its target run() method will run.
CSE4019 - Advanced Java Programming 237
1) Java Thread Example by extending Thread class
class Multi extends Thread{
public void run(){
[Link]("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
[Link]();
}
}
Output:thread is running...
CSE4019 - Advanced Java Programming 238
2) Java Thread Example by implementing Runnable interface
class Multi3 implements Runnable{
public void run(){
[Link]("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
[Link]();
}
}
Output:thread is running...
CSE4019 - Advanced Java Programming 239
Advantages of Java Multithreading
1. It doesn't block the user because threads are
independent and you can perform multiple
operations at same time.
2. You can perform many operations together so
it saves time.
3. Threads are independent so it doesn't affect
other threads if exception occur in a single
thread.
CSE4019 - Advanced Java Programming 240
Thread Scheduler in Java
• Thread scheduler in java is the part of the JVM that decides which
thread should run.
• There is no guarantee that which runnable thread will be chosen to run by
the thread scheduler.
• Only one thread at a time can run in a single process.
• The thread scheduler mainly uses preemptive or time slicing scheduling
to schedule the threads.
Difference between preemptive scheduling and time slicing
• Under preemptive scheduling, the highest priority task executes until it
enters the waiting or dead states or a higher priority task comes into
existence.
• Under time slicing, a task executes for a predefined slice of time and then
reenters the pool of ready tasks. The scheduler then determines which
task should execute next, based on priority and other factors.
CSE4019 - Advanced Java Programming 241
Thread Scheduler Java
•In Java program, you create threads but they are not
executed by Java alone.
•The scheduler maintains a pool of threads.
•Priority of thread.
•The JVM is based on preemptive and priority
based scheduling algorithm.
•main is a method for us, but main is a thread for
JVM.
CSE4019 - Advanced Java Programming 242
WorkerThrea
package
[Link] [Link];
import [Link];
public class WorkerThread implements Runnable{
private String command;
public WorkerThread(String s){
[Link]=s;
}
@Override
public void run() {
[Link]([Link]().getName()+" Start. Time = "+new Date());
processCommand();
[Link]([Link]().getName()+" End. Time = "+new Date());
}
private void processCommand() {
try {
[Link](5000);
} catch (InterruptedException e) {
[Link]();
}
}
@Override
public String toString(){
return [Link];
}
}
CSE4019 - Advanced Java Programming 243
Apply the concepts of Sleeping a thread and
Joining a thread in given problem.
Sleep method in java
The sleep() method of Thread class is used to sleep a thread for the specified amount
of time.
Syntax of sleep() method in java
The Thread class provides two methods for sleeping a thread:
• public static void sleep(long miliseconds)throws InterruptedException
• public static void sleep(long miliseconds, int nanos)throws
InterruptedException
CSE4019 - Advanced Java Programming 244
Example of sleep method in java
class TestSleepMethod1 extends Thread{
public void run(){
for(int i=1;i<5;i++){
try{[Link](500);}
catch(InterruptedException e){ Output:
[Link](e);} 1
[Link](i); 1
} 2
} 2
public static void main(String args[]){
TestSleepMethod1 t1=new TestSleepMethod1();
3
TestSleepMethod1 t2=new TestSleepMethod1(); 3
4
[Link](); 4
[Link]();
}
}
CSE4019 - Advanced Java Programming 245
Can we start a thread twice
No. After starting a thread, it can never be started again. If you does so,
an IllegalThreadStateException is thrown.
In such case, thread will run once but for second time, it will throw exception.
Let's understand it by the example given below:
public class TestThreadTwice1 extends Thread{
public void run(){
[Link]("running...");
}
public static void main(String args[]){
TestThreadTwice1 t1=new TestThreadTwice1();
[Link]();
[Link]();
}
}
Test it Now
running Exception in thread "main" [Link]
CSE4019 - Advanced Java Programming 246
Joining Threads in
Java
[Link] class provides the join() method which allows one thread to wait
until another thread completes its execution. If t is a Thread object whose thread is
currently executing, then [Link](); it causes the current thread to pause its execution
until thread it join completes its execution.
There are three overloaded join functions.
[Link](): It will put the current thread on wait until the thread on which it is called is
dead. If thread is interrupted then it will throw InterruptedException.
Syntax: public final void join()
[Link](long millis) :It will put the current thread on wait until the thread on which it is
called is dead or wait for specified time (milliseconds).
Syntax: public final synchronized void join(long millis)
[Link](long millis, int nanos): It will put the current thread on wait until the thread on
which it is called is dead or wait for specified time (milliseconds + nanos).
Syntax: public final synchronized void join(long millis, int nanos)
CSE4019 - Advanced Java Programming 247
// Java program to explain the
// concept of joining a thread.
import [Link].*;
// Creating thread by creating the
// objects of that class
class ThreadJoining extends Thread
{
@Override
public void run()
{
for (int i = 0; i < 2; i++)
{
try
{
[Link](500);
[Link]("Current Thread:
"+[Link]().getName());
}
catch(Exception ex)
{
[Link]("Exception has" + " been caught" + ex);
}
[Link](i);
}
}
}
CSE4019 - Advanced Java Programming 248
Output:
Current Thread: main
class GFG Current Thread: Thread-0
{ 0
public static void main (String[] args) Current Thread: Thread-0
{ 1
// creating two threads Current Thread: main
ThreadJoining t1 = new ThreadJoining(); Current Thread: Thread-1
ThreadJoining t2 = new ThreadJoining(); 0
ThreadJoining t3 = new ThreadJoining(); Current Thread: Thread-1
// thread t1 starts 1
[Link](); Current Thread: Thread-2
// starts second thread after when 0
// first thread t1 is died. Current Thread: Thread-2
try 1
{
[Link]("Current Thread: "+ [Link]().getName());
[Link]();
}
catch(Exception ex)
{
[Link]("Exception has " + "been caught" + ex);
}
// t2 starts
[Link]();
// starts t3 after when thread t2 is died.
try
{
[Link]("Current Thread: "+ [Link]().getName());
[Link]();
}
catch(Exception ex)
{
[Link]("Exception has been" + " caught" + ex);
}
[Link](); CSE4019 - Advanced Java Programming 249
}
Apply the concepts of Thread Priority in
given problem.
Priority of a Thread (Thread Priority):
• 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.
• 3 constants defiend in Thread class:
public static int MIN_PRIORITY
public static int NORM_PRIORITY
public static int MAX_PRIORITY
• Default priority of a thread is 5 (NORM_PRIORITY). The value of
MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.
CSE4019 - Advanced Java Programming 250
Example of priority of a Thread:
class TestMultiPriority1 extends Thread{
public void run(){
[Link]("running thread name is:"+[Link]().getName());
[Link]("running thread priority is:"+[Link]().getPriorit
y());
}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
[Link](Thread.MIN_PRIORITY);
[Link](Thread.MAX_PRIORITY);
[Link]();
[Link](); Output:
}
running thread name is:Thread-0
} running thread priority is:10
running thread name is:Thread-1
running
CSE4019 - Advanced thread priority is:1
Java Programming 251
Apply the concepts of synchronized
method in given problem.
Synchronization in Java
• Synchronization in java is the capability to control
the access of multiple threads to any shared
resource.
• Java Synchronization is better option where we
want to allow only one thread to access the shared
resource.
Why use Synchronization
The synchronization is mainly used to
1. To prevent thread interference.
2. To prevent consistency problem.
CSE4019 - Advanced Java Programming 252
Synchronization in Java
Types of Synchronization
There are two types of synchronization
1. Process Synchronization
2. Thread Synchronization
Here, we will discuss only thread synchronization.
Thread Synchronization
There are two types of thread synchronization mutual exclusive
and inter-thread communication.
[Link] Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
[Link] (Inter-thread communication in java)
CSE4019 - Advanced Java Programming 253
Mutual Exclusive
• Mutual Exclusive helps keep threads from interfering with one another while sharing data.
• This can be done by three ways in java:
1. by synchronized method
2. by synchronized block
3. by static synchronization
Concept of Lock in Java
• Synchronization is built around an internal entity known as the lock or monitor.
• Every object has an lock associated with it.
• By convention, a thread that needs consistent access to an object's fields has to acquire the
object's lock before accessing them, and then release the lock when it's done with them.
• From Java 5 the package [Link] contains several lock implementations.
CSE4019 - Advanced Java Programming 254
Understanding the problem without Synchronization
Class Table{ class MyThread2 extends Thread{
Table t;
void printTable(int n){//method not synchroniz MyThread2(Table t){
ed this.t=t;
for(int i=1;i<=5;i++){ }
[Link](n*i); public void run(){
try{ [Link](100);
[Link](400); }
}catch(Exception e){[Link](e);} }
}
} class TestSynchronization1{
} public static void main(String args[]){
class MyThread1 extends Thread{ O/P: Table obj = new Table();//only one object
Table t; 5 100 MyThread1 t1=new MyThread1(obj);
MyThread1(Table t){ 10 MyThread2 t2=new MyThread2(obj);
200
this.t=t; 15 [Link]();
} 300 [Link]();
public void run(){ 20 }
400
[Link](5); 25 }
} 500
}
CSE4019 - Advanced Java Programming 255
Java synchronized method
• If you declare any method as synchronized, it is known as synchronized
method.
• Synchronized method is used to lock an object for any shared resource.
• When a thread invokes a synchronized method, it automatically acquires
the lock for that object and releases it when the thread completes its task.
CSE4019 - Advanced Java Programming 256
Example of java synchronized method
class Table{ class MyThread2 extends Thread{
synchronized void printTable(int n){//sync method Table t;
for(int i=1;i<=5;i++){ MyThread2(Table t){
[Link](n*i); this.t=t;
try{ }
[Link](400); public void run(){
}catch(Exception e){[Link](e);} [Link](100);
} }
}} }
class MyThread1 extends Thread{ public class TestSynchronization2{
Table t; public static void main(String args[]){
MyThread1(Table t){ O/P:
Table obj = new Table();//only one object
this.t=t; 5 MyThread1 t1=new MyThread1(obj);
10 15
} 20 25 MyThread2 t2=new MyThread2(obj);
100
public void run(){ 200 [Link]();
[Link](5); 300
400
[Link]();
} 500 }
} }
CSE4019 - Advanced Java Programming 257
Serialization and Deserialization
CSE4019 - Advanced Java Programming 258
Serialization and Deserialization
• Serialization in Java is a mechanism of writing the state of
an object into a byte-stream. It is mainly used in Hibernate,
RMI, JPA, EJB and JMS technologies.
• The reverse operation of serialization is
called deserialization where byte-stream is converted into an
object. The serialization and deserialization process is
platform-independent, it means you can serialize an object
on one platform and deserialize it on a different platform.
• For serializing the object, we call the writeObject() method
of ObjectOutputStream class, and for deserialization we call
the readObject() method of ObjectInputStream class.
• We must have to implement the Serializable interface for
serializing the object.
CSE4019 - Advanced Java Programming 259
Advantages of Java Serialization
• It is mainly used to travel object's state on the network (that
is known as marshalling).
CSE4019 - Advanced Java Programming 260
[Link] interface
Serializable is a marker interface (has no data member and
method). It is used to "mark" Java classes so that the objects
of these classes may get a certain capability.
The Cloneable and Remote are also marker interfaces.
The Serializable interface must be implemented by the class
whose object needs to be persisted.
The String class and all the wrapper classes implement
the [Link] interface by default.
CSE4019 - Advanced Java Programming 261
[Link] interface
Let's see the example given below:
[Link]
import [Link];
public class Student implements Serializable{
int id;
String name;
public Student(int id, String name) {
[Link] = id;
[Link] = name;
}
}
In the above example, Student class implements Serializable
interface. Now its objects can be converted into stream. The
main class implementation of is showed in the next code.
CSE4019 - Advanced Java Programming 262
ObjectOutputStream class
The ObjectOutputStream class is used to write primitive data
types, and Java objects to an OutputStream. Only objects
that support the [Link] interface can be written
to streams.
Constructor
1) public ObjectOutputStream(OutputStream out) throws It creates an ObjectOutputStream that writes to the
IOException {} specified OutputStream.
Important Methods
Method Description
1) public final void writeObject(Object obj) throws It writes the specified object to the ObjectOutputStream.
IOException {}
2) public void flush() throws IOException {} It flushes the current output stream.
3) public void close() throws IOException {} It closes the current output stream.
CSE4019 - Advanced Java Programming 263
ObjectInputStream class
An ObjectInputStream deserializes objects and primitive data
written using an ObjectOutputStream.
Constructor
1) public ObjectInputStream(InputStream in) throws It creates an ObjectInputStream that reads from the
IOException {} specified InputStream.
Important Methods
Method Description
1) public final Object readObject() throws IOException, It reads an object from the input stream.
ClassNotFoundException{}
2) public void close() throws IOException {} It closes ObjectInputStream.
CSE4019 - Advanced Java Programming 264
Example of Java Serialization
In this example, we are going to serialize the object of Student class from above code. The
writeObject() method of ObjectOutputStream class provides the functionality to serialize the
object. We are saving the state of the object in the file named [Link].
[Link]
[Link] [Link].*;
[Link] Persist{
3. public static void main(String args[]){
4. try{
5. //Creating the object Output:
6. Student s1 =new Student(211,"ravi");
7. //Creating stream and writing the object success
8. FileOutputStream fout=new FileOutputStream("[Link]");
9. ObjectOutputStream out=new ObjectOutputStream(fout);
10. [Link](s1);
11. [Link]();
12. //closing the stream
13. [Link]();
14. [Link]("success");
15. }catch(Exception e){[Link](e);}
•}
1.} CSE4019 - Advanced Java Programming 265
success
Example of Java Deserialization
Deserialization is the process of reconstructing the object from the serialized state. It
is the reverse operation of serialization. Let's see an example where we are
reading the data from a deserialized object.
Deserialization is the process of reconstructing the object from the serialized state. It
is the reverse operation of serialization. Let's see an example where we are
reading the data from a deserialized object.
[Link]
import [Link].*;
class Depersist{
public static void main(String args[]){
try{
//Creating stream to read the object
ObjectInputStream in=new ObjectInputStream(new FileInputStream("[Link]"));
Student s=(Student)[Link]();
//printing the data of the serialized object
[Link]([Link]+" "+[Link]);
//closing the stream Output:
[Link]();
}catch(Exception e){[Link](e);} 211 ravi
}
CSE4019 - Advanced Java Programming 266
}
END
CSE4019 - Advanced Java Programming 267