CONTENTS
Java is a
by Sun Mi
designed t
UNIT - I device that
and operat
1.1 Introduction of Java l toe
1.2 What is JVM 4 1, Pla
1.3. Inheritance j “Write On
" generates
1.4 Exception Handling in Java 2. Ob
1.5. Multithreading in Java ulanguage,
1.6 Java Applet 1 ar
1.7 Socket Overview 20program™
aspects lil
1.8 Java Database Connectivity 24 ar Au
1.9 What is API? 27deallocati
developer:
UNIT - I a
include
2.1 Java ResultSetMetaData Interface 8Bnetworkin
2.2 Setter and Getter Methods in Java 396. Se
2.3 Creation of javabean wee on
. Mu
2.4 Servlet Architecture Al applicatio
2.5 Servlet Interface 4g 2nd tespo
2.6. http get request java 45 mechan
2.7 Session Tracking in Servlets, 4g applicatic
programs
UNIT - II 2 &
which cor
3.1 Introduction to JSP nave
‘
UNIT - Iv oe
4.1 What Is Client-Server Architecture 31
4.2 RMI (Remote Method Invocation) a
4.3 Parameter Passing , dave
44° What is HB oo
66ADVANCED JAVA PROGRAMMING
1.1 INTRODUCTION OF JAVA.
Javan wa widely wed, high-level, object oriented programming language developed
yee Aeragyatenne quan owned by Oracle Corporation) inthe wid-1990s. 1. ve
ae aa to be: platform independent, meaning hat Java programs ean run om any
aoe ial bossy Java Virtual Machine LIVM), regardless of the underlying hardware
sul operating system.
Key Features of Java
4 1. Platform Indepe 1: Java achieves platform independence through it
Write Onee, Ren Anywhere” (WORA) principle, Once a Java prog
aeenne celsteeade, which ean be exceted on any device with a JVM.
13 2 Opject Oriented: Java is primarily an object-oriented programming (OOP)
‘sit follows the prineiples of encapsulation, inheritance,
nd abstraction.
14. language
polymorphism
eee Senta’ ava syntax is largely influenced by C and C++, making it familiar to
9 programmers wth background i these languages, However, Java simplifies certain
Pevects lke memory management by introducing automatie garbage callection
t. Automatic Memory Management: Java manages memory allocation and
27 |deallocation automatically through its garbage collection mechanism, relieving
developers from man Jory management tasks.
Rich Standard Li Java provides a vast ry (Java API) that
includes elasser and methods for a wide range of tasks, from basic VO to advanced
networking and GUI development.
Security: Java has built-in security features, such as bytecode verification,
which ensures that Java programs do not violate security constraints during runtime.
&
7, Multithreading: Java supports multithreading, allowing developers to create
41. applications that can execute multiple threads concurrently, improving performance
and responsiveness.
8. Robustness and Portability strong type system, exception handling
45. mechanism, and striet compile-time checking contribute to the robustness of Java
4a applications. Additionally, its portability across different platforms ensures that Java
programs behave consistently across diverse environments. _
‘9. Community Support: Java has a vast and active community of developers,
which contributes to its ecosystem with libraries, frameworks, and tools,
Java Editions
ot » Java Standard Edition (Java SE): It is the core Java platform used for
‘eveloping desktop, web, and server applications.
« Java Enterprise Edition (Java BE): [tis set of specifieations for developing
‘enterprise-level applications, particularly web applications that run on servers
57 + Java Micro Edition (Java ME): It is a platform for developing applications
60 or mobile devices, embedded systems, and other small-footprint devices.
ry Java Development Tools
+ Java Development Kit (JDK): It includes tools for developing, debugging,
66 ‘ind monitoring Java applications, It contains the Java compiler, runtime
nvironment, and other development tools.
* Integrate lopment Environments (IDEs): Popular Java IDEs
include Eclipse, Intellid IDEA, and NetBeans, which provide features like code
completion, debugging, and project management.Sixth Semester, Advanced J
2-2028
Java's versatility, portability, and extensi
developing a wide range
web services
\ “Hello, World!” is a simple program that outputs Hello, World! on the screen
le program, it’s often used to introduce a new programming
Since it's a very simple program, it's
language to a newbie
Lot's explore how Java “Hello, World!” program works
Java “Hello, World!” Program
Your First Program
classHelloWorld{
public static void main(String[] args)(
System.out.printin(‘Hello, World!”):
Output
Hello, World!
How Java “Hello, World!” Program Works?
Basic features:
Basic features of Java are
ieee 9
of
Java
Simple
J
According to Sun Microsyst
because
* Java syntax is based on C++ (so easier for programme!
* Java has removed many complicated
explicit pointers, operator overloading, etc
‘There is no need to re
nove unreferenced objec
Garbage Collection in Java
of applications, from enterprise
java is very easy to learn, and its syntax is simple, clean and e.
a Programming
ecosystem make it a popular choice
software to mobile apps ang
oe
—
°
sabe Tine
and rarely-used features, for example,
's because there is an Automati¢
to understand,
Java hinguage is a simple programming language
's to learn it after C++),
ol
Ja
Object
jects
ol
lo
B
JavaLP. University-IB:Tech} Akash Book 2023-3
2 Object
DPS and sa
nted
Java is an object-oriented programming language. Everything in Java isan oles
screen, § OS rena mane we argnize ot oftware ax i combination of different type of
objects that incorporate both data and behavior
amming arate oh eee Z
Object-oriented programming (OOPs) is & methodology that simplifies sofware 1
development and maintenance by providing some rules
Basie concepts of OOPS are:
1. Object
2.01
3, Inheritance
4. Polymorphism
5, Abstraction
6, Encapsulation
Platform Independent
Java is platform independent because it is different from other language like €
Cas, ote which are compiled into platform specific machines while Java is write once
vn anywhere language. A platform is the hardware or software environment in which
a program runs
‘There are two types of platforms software-based and hardw are-hased. Java provides
a software-based platform.
‘The Java platform differs’ from most other platforms in the sense that it is a
‘software-based platform that runs on top of other hardware-based platforms. It has two
components:
(a) Runtime Environment
(b) API(Application Programming Interface)
Secured
Java is best known for its security. With Java, we ean develop virus-free systems
Java is secured because:
* No explicit pointer
« Java Programs run inside a virtual machine sandbox
understand.
ng language
t after C++).
ne ¢ the Java Runtime Environment
the Java Virtual Machine
Jkage for the classes of the
* Classloader: Classloader in Java is @ part of
. (JRE) which is used to load Java classes into
n Automatic dynamically. It adds security by separating the pacva Programming
41-2023 sixth Semester, Advanced J
7 that are imported from network sources
ea ae ments for illegal code that can violate
« Bytecode Verifier: It checks the code fra
access rights to objects.
Ti determines what resources a class can access such as
* Security Manager sw
reading and writing to the local dis!
sen : fault. Some security can also be
‘L, JAAS, Cryptography, ete.
es these sect jes by def
Java language provides these securiti It
tion developer explicitly through SS
provided by an applic
Robust
The English mining of Robust is
strong. Java is robust because:
strong memory management
# There is a lack of pointers that avoids security problems,
«+ Java provides automatic garbage collection which runs on the Java Virtual
Machine to get rid of objects which are not being used by a Java application
* Tras
anymore.
« There are exception handling and the type checking mechanism in Java. All
these points make Java robust.
Architecture-neutral
Java is architecture neutral because there are no implementation dependent
features, for example, the 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. However, it occupies 4 bytes of memory
for both 32 and 64-bit architectures in Java.
Portable: Java is portable because it facilitates you to carry the Java bytecode to
any platform. It doesn’t require any implementation.
High-performance: Javais faster than other traditional interpreted programming
languages because Java bytecode is “close” to native code. It is still a little bit slower
than 2 compiled language (e.g., C++). Java is an interpreted language that is why it is
slower than compiled languages, e.g., C, C++, ete. 7
Distributed: Java is distributed because it facilitates users to create distributed
applications in Java, RMI and EJB are used for creating distributed applications. This
cature of Java makes us able to 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
‘ach thread. It shares a common memory area. Threads are important for multi-media
Web applications, ete 2
Dynamic: Java is a dynamic language. It suppoi
It means class
language
s the dynamic loading of classes.
+s are Joaded on demand. It also supports functions from its native
Le, Cand C++
1.2 WHAT IS JVM.
TheJava Virtual Machine (JVM) isacrucialcomponentof the Java Runtime Environment
(JRE) and the Java Development Kit (JDK). It plays a central role in the
Java bytecode, enabling Java programs to run on any d
installed, regardless of the underlying hardware
execution of
evice or platform that has a JVM
rating system. It is:
or opt
1. A spe
implementatic
has been prov
2. An im
Environment)
3. Runti
to run the jav
Functions o
1, Bytee«
platform-inde
for interpretit
2,Memo
including the
by allocating
use, and man
3. Platf;
operating sys
enables Java
device or plat
4. Secur
programs rur
causing harm
access to syst
5. Just-
include a JIT
at runtime fo
native speed,
6. Class
classes into 1
class variabl
7. Exect
and profiling
bottlenecks,
Componen
1. Class
program.
2, Runt
the method <
3. Exec
performs JT1
4. Nati
native code \
Overall,
underlying I
of Java pro;
performancean violate
such as
an also be
raphy, ete.
java Virtual
. application
in Java. All
dependent
.rchitecture
of memory
bytecode to
ogramming
» bit slower
is why it is
distributed
ations. This
ny machine
currently.
ng multiple
memory for
nulti-media,
1g of classes,
n its native
nvironment
xecution of
hasaJVM
|
LP. University-IB.Tech]-Akash Books 2023-5
1. A specification where working of Java Virtual Mach
implementation provider is independent to choo:
has been provided by Oracle and other companies,
2, An implementation Its implementation is known as JRE (Java Runtime
Environment).
is specified. But
the algorithm, Its implementation
Runtime Instance Whenever you write java command on the command prompt
to run the java class, an instance of JVM is created.
Functions of the JVM
1. Bytecode Execution: Wher. a Java program is compiled, itis translated into
platform-independent bytecode instead of native machine code. The JVM is responsible
for interpreting this bytecode and executing it on the target platform.
2, Memory Management: The JVM manages memory allocation and deallocation,
including the automatic garbage collection process. It ensures efficient memory usage
by allocating memory for objects, reclaiming memory from objects that are no longer in
use, and managing memory fragmentation
3. Platform Independence: The JVM abstracts the underlying hardware and
operating system, providing a uniform execution environment for Java programs. This
enables Java applications to be truly platform-independent, as they can run on any
device or platform with a compatible JVM.
4, Security: The JVM enforces various security measures to ensure that Java
programs run safely. It implements bytecode verification to prevent malicious code from
causing harm to the system. Additionally, it provides a security manager that controls
access to system resources based on a set of predefined permissions.
5. Just-In-Time (JIT) Compilation: Many modern JVM implementations
include a JIT compiler, which dynamically compiles bytecode into native machine code
at runtime for improved performance. This allows frequently executed code to run at
native speed, enhancing the overall performance of Java applications.
6. Class Loading and Initialization: The JVM is responsible for loading Java
classes into memory as they are needed during program execution. It also initializes
class variables and static blocks before the first use of a class.
7. Execution Monitoring and Profiling: The JVM provides tools for monitoring
and profiling Java applications, allowing developers to analyze performance, identi
bottlenecks, aind optimize code for better efficiency.
Components of the JVM
1. Class Loader: Loads Java class files into memory aé they are referenced by the
program.
2, Runtime Data Area: Memory area divided into several components, including
the method area, heap, stack, and program counter.
3. Execution Engine: Interprets and executes bytecode, and in some cases,
performs JIT compilation.
4, Native Interface: Provides a mechanism for Java programs to interact with
native code written in languages like C and C++.
Overall, the JVM serves as a critical intermediary between Java bytecode and the
underlying hardware and operating system, enabling platform-independent execution
of Java programs while providing features like memory management, security, and
performance optimization,‘The JVM performs following operation:
* Loads code
* Verifies code
* Executes code
+ Provides runtime environment
JVM Architecture
‘The internal architecture of JVM contains classloader, memory area, execution
engine ete.
() Classloader: Classloader is a subsystem of JVM which is used to load class
files. Whenever we run the java program, it is loaded first by the classloader. There are
three built-in classloaders in Java
(a) Bootstrap ClassLoader: TI
s is the first classloader which is the super class
of Extension classloader. It loads the rt.jar file which contains all class files of Java
Standard Edition like java.lang package clas: ava.net package classe
package classes, java.io package classes, java.sql package classes ete.
(b) Extension ClassLoader: This is the child classloader of Boot:
classloader of System classloader. It loades the jar files located inside
jrefliblext directory.
(c) System/Application ClassLoader: This is the child classloader of Extension
classloader. It loads the classfiles from classpath. By default, classpath is set to current
directory. You can change the classpath using “-cp” or “-classpath” switch. It is also
known as Application classloader.
1. Let's see an example to print the classloader name
2. public class ClassLoaderExample
{
s, java.util
rap and parent
|AVA_HOME/
public static void main(String[] args)
{
// Let's print the classloader name of current class.
WApplication/System classloader will load this class
Class c=ClassLoaderExample.class;
System.out.println(c.getClassLoader());
/Mf we print the classloader name of String, it will print null because it is an
11. /in-built class which is found in rt jar, so it is loaded by Bootstrap classloader
12, System.out.printIn(String.class.getClassLoader());
13.)
14.)
Output:
sun.misc.Launcher$AppClassLoader@4e0e2f2a
null
These are the internal classloaders provided by Java. If you want to create your
own classloader, you need to extend the ClassLoader cla:
OHI AA HE
Ss
(2) Class(Method) Area: Class(Method) Area stores per-class structures such as
the runtime constant pool, field and method data, the code for methods,
(3) I
as
and play
Fa
An
its meth
6)
address
)!
@)
(a)
(b)
(c)
(a)
CLASS
Classes
variablstil
nt
1E/
ion
nt
Iso
ler
ur
LP. University 1B-Tech] Akash Books 2023-7
(3) Heap: I is the runtime data area in which objects are allocated.
(4) Stack: Java Slack stores frames. It holds local variables and partial results,
and plays a part in method invocation and r
ach thread has a private JVM stack, created at the same time as thread
ated each time a method is invoked. A frame is destroyed when
A new frame is er
jon completes.
its method invor
(5) Progra
address of the J
(6)Native
(7) Execution Engine: It cont:
m Counter Register: PC (program counter) register contains the
‘tion currently being executed.
Method Stack: It contains all the native methods used in the application.
(a) A virtual processor
(b) Interpreter
(c) Just-In-Time(JIT) compiler
(d) Java Native Interface
CLASS & OBJECT
Classes are the building blocks of a java application. A class can contain methods,
variables, initialization code and even other classes. We can declare a class with class
keyword
class classname
(
datatype variablename;
return type methodname(argument list)
t
statement block;
i
)
‘Two types of variables can be defined in a class ~ instance variables and static
variable, Every object has its own set of instance variables. If we don't initialize an
instance variable during declaration, then it takes a default value appropriate for its
type.
‘As with variables, methods defined in a class may be instance methods or static
methods.
‘An instance method is associated with an instance of the class, but each instance
does not really have its own copy of the method
(1) Static members: Members that are declared with the static modifier live in the
class and are shared by all instances of the class. Any modification on static variable in
one instance, will affect other instances of the same class. Since static members exist in
the clase itself, independent of any instance, we can also access them directly through
the class.
(2) Method: Method appears inside class bodies. They contain local variable
declaration and statement. A method in a java always specifies a return type. There is
no default return type.
Static method belongs to the class and not to an individual instance of the class. It
can be invoked by name, through the class name, without any objects around. A static‘Advanced Java Programming
Sixth Semester,
lass. It ean not directly see
82023
ly access only other static members of the el
any instance methods.
Java is a two-step process. F
ble does not define an object instead,
Second, we must acquire an actual,
‘able. We can do this using the new
method can direct
any instance variable or call
(3) Object: Creating an object of a class in
must declare a variable of the class type. This varial
it is simply a variable that can refer to an objer
physical copy of the object and assign it to that vari
operator
erthe new operator dynamically allocates memory fo
iss. First we
yr an object and returns a
reference to it
Classnameobjectname = new classname) ;
classname.variablenaine
(4) Array: An array is a group of similar type of data that are referred
common name.
Array of any type can be created and may have one or more dimensions. A specific
clement in an array is accessed by its index. In Java, array index start from zero.
The declaration statement of an array can not allocate any memory space to the
array, We must allocate space to array by using new operator.
(i) One-dimensional array: The general form of one-dimensional array is
(i) Multidimensional array: In Java, multidimensional arrays are actually arrays
of arrays. ‘’he general form is
(5) String: A string is a sequence of characters. Java implements strings as objects
of type String.
to by a
After creating a String object, we can not change its contents. If it is necessary to
modify, then we have to create a new string object.
(6) Vector: The Jave.util package has a class called vector. It permits an array
to store different elements that are of different class. We need to include the import
statement import java.util." to use the vector class.
It is also an expandable array of objects. The array grows larger as more elements
are added to it. The array may also be reduced in size after some of its elements have
been deleted.
We can not directly store simple(primitive) data type in a vector. We can only store
objects,
‘Vector automatically increases its size when needed.
1.3 INHERITANCE
Inheritance is a fundamental conce|
(methods and fields) from another el:
er class (superclass or parent class). Thi
code reuse, modularity, and hierarchical organization of classes, a
Syntax of Inheritance in Java
In Java, inheritance is achieved
y using the a
that inherits from a superclass. The syntax is a follow ent? Create & Subclass
yyntax is as follows:
JavaCopy code
class Superclass
Example:
javaCopy code
class Superelass extends Superclass
Ani
h
‘Type
inter!
inher
of int
A
execuec
we
ad,
ial,
ew
ecific
» the
rays
ects
ray
port
ents
rave
ding
viors
jotes
class
LP. University-1B-Tech|-Akash Books 2023-9
class Animal void make
‘ound —_ “Some generic sound..."); }] class Dog exter
Animal"Canine” void make Sound “Woof!” ee
In this example:
+ Animal is the superclass with a field species and a method makeSound(),
+ Dog is the subclass that extends Animal, It inherits the specie:
overrides the makeSound0 method with its own implementation nn “4
Types of Inheritance in Java
1. Single Inheritance: A subclass inherits from only one superclass.
2, Multilevel Inheritance: A subclass becomes a superclass for another subelass,
¢ a chain of inheritance.
creati
3, Hierarchical Inheritance: Multiple subclasses inherit from a single superclass
4, Multiple Inheritance (through interfaces): A class implements multiple
interfaces, effectively inheriting from all of them. Java does not support multiple
inheritance of classes to avoid the diamond problem, but it supports multiple inheritance
of interfaces.
Access Modifiers and Inheritance:
+ Public: Subclasses can inherit and access public members of the superclass.
* Protected: Subclasses can inherit and access protected members of the
superclass, but only within the same package or through inheritance.
* Default (no modifier): Subclasses can inherit and access default members of
the superclass only if they are in the same package.
+ Private: Subclasses cannot directly inherit or access private members of the
superclass.
Method Overriding:
‘Subclasses can override methods inherited from the superclass by providing a new
implementation. This allows subclasses to customize behavior while still benefiting
from code reuse.
Super Keyword:
‘The super keyword in Java is used to refer to members of the superclass within
the subclass. It can be used to call superclass constructors, access superclass methods
or fields, and differentiate between overridden methods and superclass methods with
the same name.
In summary, inheritance in Java allows classes to inherit properties and behaviors
from other classes, promoting code reuse and facilitating hierarchical organization of
classes. It is a key concept in object-oriented programming and is widely used in Java
programming.
‘Threads in java have five characteristics.
1. Thread body: This is the sequence of instructions for the thread to perform.
We create a thread by instantiating an object of type Thread. Java defines two ways in
which this ean be accomplished:
(i) We can implement the Runnable interface: Runnable abstracts a unit of
executable code. To implement Runnable, a class need only implement a single method
called runt }.
abstract class classname
{10-2023 Sixth Semester,
abstract returntypemethod!)
i
)
Class classname
i
final returntypemethod! )
i
statement;
’
1
final class classname
{ tha
returntypemethod( ) i
{
statement;
1
ay created Runnable Blocked thr:
Dead Will
Start()
Stop) grou
Run()
ends
Stop()
Run)
ends
V/O blocking
Resume( )
Notify()
Sleep time out vo
VO finished
Stop()
Run() cee
ends oon
will eae ), we will define the code that constitutes the new thread. This ora
run( ) returns. oon
ii) We can extend the Thread class, itself.: We can extend the Thread css!
create a new thread. Then cr i ji
crea anew thr reate a instance (object) of that class. The extending OH and
run( i
coene ‘un( ) method. We must also call start( ) to begin execution of tt
2. Thread States:
| be in one of the four st:
The:
E
very thread, after creation and before destruction, will"
ates —
's newly created, runnable, blocked and dead. hasash bOOKS 2023-11
(i) Newly ¢
ted: A thread enters the newly created b
is in the new state or born state immediately after creation,
(ii) Runnable: Once we invoke the
(iii) Blocked: The blocked state is ¢
when call the suspend( ) method
by using a new operator. It
rt( ) method, the thread is runnable.
tered when one of the following events occurs -
(b) call for wait( ) method
(c) waiting for VO operation
(d) the thread will join( ) another thread
(iv) Dead: A thread is dead for any one of the two reasons:
(a) it dies a natural death b
b) it dies abruptly because an uncaught exception terminates the run method.
3. Thread priority: Every thread in java is assigned a priority value. When more
than onethread is competing for CPU time, the thread with highest priority value is
given preference. Wecan also use the Thread class constants as follows
Thread. MIN_PRIORITY = 1
‘Thread. MAX_PRIORITY = 10
Thread.NORM_PRIORITY = 5
4. Daemon Thread: This denotes that a thread is a “server” thread. A server
thread is a thread that services client request. They normally enter an endless loop
waiting for clients requesting services.
5. Thread Group: Java allows us to group similar threads and manage them as a
group. Every thread instance is a member of exactly one thread group.
Methods of Thread class: The Thread class defines several methods as follows:
1. getName -> Obtain a thread’s name
2. getPriority -> Obtain a thread’s priority
3. isAlive -> Determine if a thread is still running
4. join -> wait for a thread to terminate
5. run -> Entry point for the thread
6. sleep -> Suspend a thread for a period of time
7. start -> Start f thread by calling its run method.
VO IN JAVA
UO Basie:
Streams: java programs perform I/O through streams. A stream is a flow of data
or a channel of communication. A stream is an abstraction that either produces or
consumes information. A stream is linked to a physical device by the java I/O system.
An input stream can abstract many different kinds of input from a disk file, a keyboard,
or a network socket. An output stream may refer to the console, a disk file or a network
connection. Java implements streams within class hierarchies defined in the java.io
package.
Byte Streams and Character Streams: - Java defines two types of streams ~ byte
and character.
Byte streams provide a convenient means for handling input and output of bytes.
‘These are used for reading or writing binary data.
Character streams provide a convenient means for handling input and output of
characters
cause the run method exits normallygr
Java Programming
fi y using two cla
are defined by using ay
TnputStream and OutputStrean
face different devices liky
thods are read( ) anq
2-2028 sixth Semester, Advanced
(i) The Byte Stream Classes: By!
hiorarchies. At the top are two abstract CU
Each of these abstract classes has several su
disk files, network connection ete. two of the
Write( ) for reading and writing bytes of data.
(ii) The Character Stream Class
class hierarchies.
: d
‘Mt the top are two abstract classes, Reader an ;
Unicode character streams, These classes define several key methods 0%
read( )and write( ) to read and write characters of data. .
The Predefined Streams: Al] java programs ees
i is system cl
package. This package defines a class called System. sys
predefined stream variables —in, out and err. These fields are declared as public,
and final within system. 7 1"
System.out refers to the standard output stream. By default, this is the console
System.in refers to standard input, which is the keyboard by default. System-err
refers to the standard error stream, which also is the console by default.
‘System in is an object of type InputStream, System.out and System.err are objects
of type PrintStream. .
Reading Console Input: In java, console input is accomplished by reading from
To obtain a character-based stream that is attached to the console, wrap
System.in ina
BufferedReader object. This object supports a buffered input stream. Its most
commonly used constructor is
BufferedReader(Reader inputReader)
Here Reader is an abstract class. One ofits subclasses is InputStreamReader whick
converts bytes to characters. To obtain an InputStreamReader object, we have to us
the following constructor
InputStreamReader(InputStreaminputStream)
The main statement is
BufferedReaderbr = new BufferedReader (new InputStreamReader( System. in);
Reading characters: - Characters from keyboard can be read as follows:
BufferedReaderbr = new BufferedReader (new InputStreamReader( System.in))
Char ¢ = (char) br.read();
Each time the read( ) is called, it reads a chara
aS it as an integer value, We are using
sading String: To read a stri :
readLine( ) which is the member of the from the keyboard, we can use the version!
a , er of the BufferedReader class.
String readLine( ) throws IOException
The statement is :
BufferedReaderbr
ew BufferedRi .
String str; feader (new InputStreamReader( System.
Str = br.readLinet );
Reading and Writi
riting Fil :
all 8 Files: Java provi
ow to ead and witt files. Inova oh ee ides a number of classes and methods
are byte-oriented,
belasses to handle
most important met
aracter streams are defined by using two
Writer. These classes handle
yut of which are
import the java.lang
Jass contains three
static
cter from the input stream at
(char) to convert it to character type.
Pwo
FileOutput
create an «
the constr
Fileln.
FileO\
Here
an input s
output str
When
Readit
Int re:
Each |
as an intes
syntax is
Writi
Void v
This 1
declared a
Closi:
Filein
fin = n
int x =
File.
fin =n
fout..
Void «
Exception
file not fo
programs
them app:
Key
1. Ex
that are ¢
checked
*Ch
by the me
such as fil
FileNotF
* Un
do not nee
errors, suvd
wo
le
are
ree
atic
cole,
err
cts
om
ap
ost.
ich
LP. University-1B-Techl-Akash Book
FikeOutpuiStrcnm, which crate byte ssa hake gp elaputseeam and
create an object of one of these classes, specify thence dg Te open a file
the constructor. The general form is
2028-18
we simply
me of the file as an argument to
FileInputStream(String filename) throw
ileNotPoundException
FileOutputStream(String filename) throws FileNotFoundxcept
‘oundxception
Here, filename specifies the na
an input stre:
of the file that we want to open. When we creat
When an output file is op existing file by the same name is destroyed,
le:- To read from a file, we can use a version of read( )
Int read( ) throws IOException
am, if the file does not ex
ned, any pre
Reading from Fi
ng as follows:
Each time that it is called, it reads a single byte from and returns the
as.an integer value. Tho endl) returns 1 when the end af the fle lsenemeeved te
syntax is
} Writing to file: To write to a file, we can use the write( ) method as follows
Void write(int byteval)throws IOException
This method writes the byte specified by byteval to the file. Although byteval is
declared as an integer, only the low-order eight bits are written to the file, The syntax is,
Closing a file: We can close a file by using close( ) method. The syntax is
FileInputStream fin;
fin
new FileInputStream(“filename”);
int x = fin.read( );
FileOutputStreamfout;
fin = new FileQutputStream(“filename”);
fout.write(integer value };
Void close( ) throws IOException;
1.4 EXCEPTION HANDLING IN JAVA
Exception handling in Java is a mechanism used to deal with runtime errors or
exceptional conditions that occur during the execution of a program. These exceptional
conditions, also known as exceptions, can include situations such as divide by zero,
file not found, null pointer dereference, etc. Proper exception handling ensures that
programs can gracefully recover from such errors and continue execution or handle
them appropriately.
Key Concepts in Exception Handling:
1. Exception Classes: Exceptions in Java are represented as objects of classes
that are derived from the Throwable class. ‘There are two main types of exception:
checked exceptions and unchecked exceptions.
* Checked Exceptions: These are exceptions that must be eaught or declared
by the method in which they may occur. They are usually related to external factors
such as file /O errors or network connectivity issues. Examples include 1OException,
FileNotFoundException, etc.
* Unchecked Exceptions: Also known as runtime exceptions, these exceptions
do not need to be explicitly caught or declared. They typically arise from programming
crrors, such as attempting to access a mull object or dividing by zero. Examples includemming
ester, Advanced Java Prog!
Sixth Sem
14 2028
ticExeeption, cte
w handling in Java is typically done using (7c
NullPointerException, Arithme
9, try-cateh Blocks: Exceptio
Docks
«eho try block contains the code that might generate 20 exception.
the exception if it occurs. Multiple cate,
block catches and handles
blocks ean be used to handle different types of exceptions
+ vs finally block (optional) is used to execute code that must be run regardless of
whether an exception is thrown or not (e.g. closing resources)
rns can also be explicitly thrown using
3. Throwing Exceptions: In Java, exceptio
as occurred under
tho throw keyword, This is typically done to indicate that an error hy
conditions.
4. Exception Propagation: If an exception is not c:
propagated up the call stack to the calling method. If the exception is not
til it reaches the top-level method (e.g., main
spe
aught within a method, it is
caught there,
at runtime.
it continues to propagate v
Advantage of Exception Handling
‘The core advantage of exception handl
application. An exception normally disrupts the normal flow of the
why we need to handle exceptions. Let's consider a scenario:
statement 1;
Jing is to maintain the normal flow of the
application; that is
statement 2;
statement 3;
statement 4;
statement 5y/exception occurs
statement 6;
statement 7;
statement 8;
9. statement 9;
10. statement 10;
sen uPeene her ae 10 statements in Java program and an exception occurs
: : 6 ext
be executed fratello handing, ee 7 will not
will be executed. Tha’ is why we use exception handling in Java. a
1.5 MULTITHREADING IN JAVA
Multithreading is a programming concept in whi
Mii pt in which the applicati :
tial ew pr We ao a
2.
3.
5.
6.