Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
57 views

Core Java

The document provides an overview of the Java programming language, including its history, types of applications that can be created with Java, platforms and editions of Java, features of Java, and components of the Java platform. It covers topics such as the Java Virtual Machine, classes, objects, inheritance, and polymorphism.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views

Core Java

The document provides an overview of the Java programming language, including its history, types of applications that can be created with Java, platforms and editions of Java, features of Java, and components of the Java platform. It covers topics such as the Java Virtual Machine, classes, objects, inheritance, and polymorphism.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 287

Sr.

No content Page No
1 Introduction to JAVA

2 OOPs & its Implementation using JAVA Programs:


Classes, Objects, Inheritance, Polymorphism, Abstraction,
Encapsulation
3 Fundamentals of Java Programming: Keywords, Data
Types & Programming Constructs
4 Fundamental Classes: Package Overview

5 String, String Buffer

6 Exception Handling Techniques -

7 Reflections

8 Advanced I/O Streams: File, Byte Streams, Character


Streams, Random Access File, and Object Serialization
9 JDBC: Advantages, Database Connectivity Using SQL
Server, Types of Drivers, Statements, Prepared Remote
Interfaces
10 Multi-Threading.

11 Collection Framework: Collection, Map

12 Date & Calendar

13 Enumeration

14 Iterator.
Chapter 1: Introduction to JAVA

What is Java?

 Java is a high-level programming language that was developed by James


Gosling in the year 1982. It is based on the principles of object-oriented
programming and can be used to develop large-scale applications.
 Java was developed by Sun Microsystems (which is now the subsidiary of
Oracle) in the year 1995.
 James Gosling is known as the father of Java. Before Java, its name was
Oak. Since Oak was already a registered company, so James Gosling and
his team changed the name from Oak to Java.

Why Java Programming named "Java"?

 The team gathered to choose a new name. The suggested words were
"dynamic", "revolutionary", "Silk", "jolt", "DNA", etc. They wanted
something that reflected the essence of the technology: revolutionary,
dynamic, lively, cool, unique, and easy to spell and fun to say.
 According to James Gosling, "Java was one of the top choices along with
Silk". Since Java was so unique, most of the team members preferred
Java than other names. Java is an island of Indonesia where first coffee
was produced (called java coffee).
 Logo: The blue coffee cup with red steam and a red wordmark.(The
name of the programming language is written in a title case, with as it
were "J" promoted.)

Types of Java Applications

There are mainly 4 types of applications that can be created using Java
programming:

1) Standalone Application

Standalone applications are also known as desktop applications or window-


based applications. These are traditional software that we need to install on
every machine. Examples of standalone application are Media player, antivirus,
etc. AWT and Swing are used in Java for creating standalone applications.
2) Web Application

An application that runs on the server side and creates a dynamic page is called
a web application. Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc.
technologies are used for creating web applications in Java.

3) Enterprise Application

An application that is distributed in nature, such as banking applications, etc. is


called an enterprise application. It has advantages like high-level security, load
balancing, and clustering. In Java, EJB is used for creating enterprise
applications.

4) Mobile Application

An application which is created for mobile devices is called a mobile


application. Currently, Android and Java ME are used for creating mobile
applications.

According to Sun, 3 billion devices run Java. There are many devices where
Java is currently used. Some of them are as follows:

1. Desktop Applications such as acrobat reader, media player, antivirus, etc.


2. Web Applications such as irctc.co.in, javatpoint.com, etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games, etc.
Java Platforms / Editions

There are 4 platforms or editions of Java:

1) Java SE (Java Standard Edition)

It is a Java programming platform. It includes Java programming APIs such as


java.lang, java.io, java.net, java.util, java.sql, java.math etc. It includes core
topics like OOPs, String, Regex, Exception, Inner classes, Multithreading, I/O
Stream, Networking, AWT, Swing, Reflection, Collection, etc.

2) Java EE (Java Enterprise Edition)

It is an enterprise platform that is mainly used to develop web and enterprise


applications. It is built on top of the Java SE platform. It includes topics like
Servlet, JSP, Web Services, EJB, JPA, etc.

3) Java ME (Java Micro Edition)

It is a micro platform that is dedicated to mobile applications.

4) JavaFX

It is used to develop rich internet applications. It uses a lightweight user


interface API.

Features of Java:

The java features given below are simple and easy to understand. They are also
known as java

buzzwords.

1)Simple:
1. Java is Simple to write and more readable and eye-catching. It has a
concise, cohesive set of features that makes it easy to learn and use.
2. Syntax of Java is based on C++ (so Java is easier for programmers to
learn it after C++).
3. Many confusing and/or rarely-used features are removed. For example,
explicit pointers,operator overloading etc.

2) Secure

 Java program cannot harm another system thus making it safe. It provides
a reliable
 means of creating Internet applications and a secure way to access web
applications.
 No explicit pointer.
 Java Programs run inside virtual machine sandbox.

3. Portable:

 Java programs can execute in any environment for which there is a Java
run-timesystem (JVM).
 Java code can be run on multiple platforms, for example, Windows,
Linux, Sun Solaris, Mac/OS, etc.
 Java code is compiled by the compiler and converted into bytecode. This
bytecode is platform-independent code because it can be run on multiple
platforms, i.e., Write Once and Run Anywhere(WORA).
4. Object-oriented:

 Java programming is an object-oriented programming language. Like

C++

 Java provides most of the object oriented features. Java is OOP


Language.

5. Robust:

 Java encourages error-free programming by being strictly typed and


performing run-time checks.
 There is lack of pointers that avoids security problem, automatic garbage
collection, exception handling and type checking mechanism in java. All
these points make java robust.

6. Multithreaded:

 Java is a multi-threaded programming language which means we can


develop multi-threaded program using Java.
 A multi-threaded program contains two or more parts that can run
concurrently and each part can handle different task at the same time
making optimal use of the available resources.
7. Architecture-neutral:

 Now talking about C, C++ they are a platform dependent language's as


the file which compiler of C, C++ forms is an .exe (executable) file which
is operating system dependent.
 The C++ program is controlled by the operating system whereas, the
execution of a Java program is controlled by JVM (Java Virtual Machine)

8)Interpreted:
 The interpreted feature in C++ is very slow because it is interpreted line
byline, and makes the system a slower way of running a program than
one that has been compiled.

9)High performance:

 Since C++ is platform dependent, the performance of C++ is not that


much noted. Byte codes are highly optimized. JVM can execute them
much faster.

10)Distributed:

 Java was designed with the distributed environment. Java can be


transmitted,run over the internet. RMI and EJB are used for creating
distributed applications.

11) Dynamic:

 Java programs carry with them large amounts of run-time type


information that is used to confirm and resolve accesses to objects at run
time.
Components of Java

Java platform is a software or collection of programs that help us to


execute applications written in Java programming language. A Java platform
consists of a Java compiler, a set of libraries, and an execution engine.Java
platform is independent of any particular OS which makes Java programming
language a platform-independent language.

Java platform consists of the following components.

 Java language
 The Java Development Kit (JDK)
 The Java Runtime Environment (JRE)
 The Java Compiler
 The Java Virtual Machine (JVM)

Apart from the above main components, the Java platform also contains
garbage collectors, a set of libraries and other additional components and tools
that are required to efficiently run the Java applications.

Let’s consider the following diagram that depicts the relationship between
all these components.
So from the above diagram, we can conclude that,

JRE = JVM + library classes.


JDK = JRE + Developer tools.
 In Java, there is a process of compilation and interpretation.
 The code written in Java, is converted into byte codes which is done by
the Java Compiler.
 The byte codes, then are converted into machine code by the JVM.
 The Machine code is executed directly by the machine.

Java Virtual Machine (JVM)

Java Virtual Machine – enables the computer to run Java program. It


reads and interprets .class files and executes the program’s instruction into the
native hardware platform. JVM is platform

independent (obtainable for many hardware and software platforms). In the Java
virtual machine specification, the behaviour of a virtual machine instance is
described in terms of subsystems, memory areas, data types and instructions.
These components describe an abstract inner architecture for the abstract Java
virtual machine. The purpose of these components is not so much to dictate an
inner architecture for implementations. It is more to provide a way to strictly
define the external behaviour of implementations. The specification defines the
required behaviour of any Java virtual machine implementation regarding these
abstract components and their interactions

what does JVM performs?

 It is used to load the code.


 It Verifies and executes the code.
 And it provides run time environment.

Components of JVM:

Java Virtual Machine (JVM) in Java is the heart of the entire execution
process of the Java program.It is basically a program that provides the runtime
environment necessary for Java programs to execute.In other words, Java
Virtual Machine (JVM) is an abstract computer machine that is responsible for
executing Java bytecode (a highly optimized set of instructions) on a particular
hardware platform. It is also called Java run-time system.

The specification of JVM is provided by Sun Microsystem whose


implementation provides a runtime environment to execute our Java
applications. JVM implementation is known as Java Runtime Environment
(JRE).

As you can observe in the above figure, JVM contains the following main
components that are as follows:

1. Class loader sub system


2. Runtime data areas
3. Execution engine
4. Native method interface
5. Java native libraries
6. Operating system

Runtime data areas consist of the following sub-components that are as follows:

1. Method area
2. Heap
3. Java stacks
4. PC register
5. Native method stacks

How JVM works Internally?

Java Virtual Machine performs the following operations for execution of the
program. They are as follows:

a) Load the code into memory.

b) Verifies the code.

c) Executes the code

d) Provides runtime environment.

When we make a program in Java, .java program code is converted into


a .class file consisting of byte code instructions by the Java compiler. This Java
compiler is outside of JVM.

Now, Java Virtual Machine performs the following operations that are as
follows:

1. This .class file is transferred to the class loader sub system of JVM as shown
in the above figure.
n JVM, class loader sub system is a module or program that performs the
following functions:

a) First of all, the class loader sub system loads .class file into the memory.

b) Then bytecode verifier verifies whether all byte code instructions are proper
or not. If it finds any instruction suspicious, the further execution process is
rejected immediately.

c) If byte code instructions are proper, it allots the necessary memory to execute
the program.

This memory is divided into 5 separates parts that is called run-time data areas.
It contains the data and results during the execution of the program. These areas
are as follows:
1. Class (Method) Area: Class (Method) area is a block of memory that stores
the class code, code of variables, and methods of the Java program. Here
methods mean functions declared in the class.

2. Heap: This is the runtime data area where objects are created. When JVM
loads a class, a method and a heap area are immediately built in it.

3. Stacks: Method code is stored in the Method area. But during the execution
of a method, it requires some more memory to store the data and results. This
memory is allocated on Java stacks. Java stacks are those memory areas where
Java methods are executed. In Java stacks, a separate frame is created where the
method is executed. Each time a method is called, a new frame is created into
the stack. When method invocation is completed, a frame associated with it is
destroyed.JVM always creates a separate thread (or process) to execute each
method.

4. PC Register:PC (Program Counter) registers are those registers (memory


areas) that contain the memory address of JVM instructions currently being
executed.

5. Native Method Stack:Methods of Java program are executed on Java stacks.


Similarly, native methods used in the program or application are executed on
Native method stacks.Generally, to execute the native methods, Java native
method libraries are needed. These header files are located and connected to
JVM by a program, known as Native method interface.

6.Execution Engine

Execution engine consists of two parts: Interpreter and JIT (Just In Time)
compiler. They convert the byte code instructions into machine code so that the
processor can execute them.In Java, JVM implementation uses both interpreter
and JIT compiler simultaneously to convert byte code into machine code. This
technique is called adaptive optimizer.
Generally, any programming language (like C/C++, Fortran, COBOL,
etc.) will use either an interpreter or a compiler to convert the source code
stream into a machine code.JIT compiler in Java is the part of JVM that is used
to increase the speed of execution of a Java program.In other words, it is used to
improve the performance of the execution of the program. It helps to reduce the
amount of time needed for the execution of the program.

Software requirements for Java:

To run other users' Java programs, a user must have the JRE (Java Runtime
Environment). Theuser must have the JDK (Java Development Kit) to write and
run the Java programs, which issometimes called the System Development Kit
(SDK).Do not get both JDK and JRE because JDK includes JRE and both are
the same.

The user needs a text editor with which to write programs. Recommended
editors are Text Pad on Windows and BBEdit on the Macintosh. However, most
IDEs include a text editor. An Integrated Development Environment (IDE) is a
single program that lets a user to edit, compile, run, test and debugs programs,
all in one place. If a user does not have an IDE, he needs to learn how to
compile and run Java programs from the command line which is not a difficult
task, just less convenient.

There are various softwares for users:

• JRE (Java Runtime Environment): The JRE provides the libraries, the java
virtual

machine and components to run applets and application written in the Java

programming language.
• JDK (Java Development Kit): JDK is the official development kit for the Java

programming language. JDK contains the software and tools that user needs to

compile, debug and run applets and applications written using the java
programming language.

• Eclipse: It is an excellent and very popular IDE. Eclipse is a software designed


tomanage IDE for Java language. It is helpful for programming applications for
Window platforms.

• NetBeans: It is Sun's IDE and catching up with Eclipse. The main advantage
of NetBeans is that it can be downloaded along with the JDK. It also provides a
visual GUI builder, but that relies on some packages that must be included with
the program if it is to run outside the NetBeans environment

How to set path to run a program?

The path is required to be set for using tools such as javac, java etc. If user is
saving the java source file inside the jdk/bin directory, path is not required to be
set because all the tools will be available in the current directory. But if user
having his java file outside the jdk/bin folder,it is necessary to set path of JDK.

There are two ways to set java path:

1. Temporary

2. Permanent

How to set Temporary Path of JDK in windows?

To set the temporary path of JDK, user needs to follow following steps:

1. Open command prompt


2. Copy the path of jdk/bin directory

3. Write in command prompt: setpath=copied_path

For example:

set path=C:\Program Files\Java\jdk1.7.0_03\bin

How to set Permanent Path of JDK in windows?

For setting the permanent path of JDK, user needs to follow these steps:

Go to My Computer properties -> advanced tab -> environment variables ->new


tab of user

variable -> write path in variable name ->write path of bin folder in variable
value -> Click ok-

> ok->ok

For Example:

Step 1: Go to My computer properties


Step 2: Click on the advance tab

Step 3: Click on the environment variables


Step 4: Click on new tab of user variables

Step 4: Click on new tab of user variables


Step 5: Write path in variable name

Step 6: Copy the path of bin folder


Step 7: Paste path of bin folder in variable value

Step 8: Click on OK Button


Step 9: Click on OK button

Now the permanent path is set. User can execute any program of java from any
drive
Simple Java Program:

 Java is a general-purpose programming language. Like any programming


language, Java also has its syntax, structure and programming paradigm
to build a robust, reusable and maintainable applications programs.
 Java programs are executed in its development environments such as Java
Development Kit (JDK) and Eclipse IDE. Programmatically, Java is a
derivative of C++language.
 The Syntax of Java looks similar like C.Code blocks are modularised into
methods and delimited by braces ({ }) and variables are declared before
they are used.
 Java program starts with a package where the package can be defined as a
namespace mechanism. It helps to maintain the hierarchical file system,
manage file system and class system.

Example program
/*First java program*/

class Hello //save as Hello.java {

Public static void main (string args[]) // program entry point {

System.out.println (“Hello world!!!”); // print message

} //end of main

} //end of First Program class

Output of this program: Hello world!!!


Chapter 2: OOPs & its Implementation using
JAVA Programs

Paradigms of Programming:

Programming paradigms are fundamental styles or approaches to writing


computer programs. They offer distinct ways of thinking about and structuring
code. Here are some of the main programming paradigms:

These are the two paradigms:

1)procedure-oriented model

2)object-oriented programming

1)Procedure oriented Programming:

In this approach, the problem is always considered as a sequence of tasks


to be done. A number of functions are written to accomplish these attention on
data.There are many high level languages like COBOL, FORTRAN, PASCAL,
C used for conventional programming commonly known as POP.
POP basically consists of writing a list of instructions for the computer to
follow, and organizingthese instructions into groups known as functions.

A typical POP structure is shown in below:

A flowchart is used to organize these actions and represent the flow of


control logically sequential flow from one to another. In a multi-function
program, many important data items are placed as global so that they may be
accessed by all the functions. Each function may have its own local data. Global
data are more vulnerable to an in advent change by a function. In a large
program it is difficult to identify what data is used by which function.

Drawback: It does not model real world problems very well, because functions
are action
oriented and do not really corresponding to the elements of the problem.

2) Object Oriented Programming Concepts

Java is an Object Oriented language. It provides the feature to implement


an Object Oriented model, where it is organised around objects and logic rather
than data it is used at the beginning of software lifecycle and also used to
develop other applications. Simula is considered as the first object-oriented
programming language. The programming paradigm where everything is
represented as an object is known as truly object-oriented programming
language.Smalltalk is considered as the first truly object-oriented programming
language

Object Oriented Programming is a technique in which programs are


written on the basis of objects for example, (Java) where it adopts a concept that
views everything as an object and implements a logic about it. Let’s see the
concepts of Object Oriented Programming in detail with a real time example.
2.1 Object

 An object is nothing but a matter of thing what we find in everyday life.


Technically, Java is a software bundle of related state and behaviour.
 An object has a state or properties (information such as size, height,
colour, position, etc.) for
 example,

Figure 1.1.1: Object with its Attributes

2.2 Class

 In Java programming, the class is defined as a blueprint from which


objects are created. It models and describes the state and behaviour of an
object.
 For example, consider a car with several properties like the clutch,
steering, break, etc.
2.3 Inheritance-
 Inheritance is a property by which state and behaviour of one class (super
class) can be inherited to its sub-class. It is a powerful and a natural
mechanism for organising and structuring a software.
 Let’s take a realtime example to understand inheritance process. In the
below figure, course is a parent class from which two child classes
professional and non-professional courses are derived.
The courses B.Sc, B.Com, and BA are child classes that are derived from a non-
professional course class. Similarly, B.Tech, MBA, and MBBS are child classes
derived from professional course class as shown in the below figure.

2.4 Abstraction
Hiding the implementation details from the user is called as the abstraction.
Here, only the functionality will be provided. In Java, abstraction can be
achieved by the abstract class and interface.A class with an abstract keyword is
called as abstraction.
2.5 Interface – blueprint of a class.
Full abstraction can be achieved using this mechanism. Interfaces in Java are
one of the ways to achieve data abstraction, which means showing up only
essential information by hiding unnecessary details. Secondly, we have
interfaces because we can’t implement multiple inheritances using classes. It
helps to implement multiple inheritances in Java. Moreover, interfaces work as
a stage that lets other classes rebuild its method as per their requirement.

In the above example, the class MobilePhone and Landline implements the
interface Phone. The classes redefined the abstract methods dial_number() and
disconnectCall() as per their requirements. Moreover, We can’t create an object
for the interface. So, we can access the redefined methods in implemented
classes

2.6 Encapsulation-Encapsulation is one of the fundamental concept of OOP.


Mechanism of binding the data and function together in a single unit is called as
encapsulation.
For example, Medicine hidden by a capsule. Where medicine is an important
component which is hidden by a capsule.
2.7 Polymorphism-Polymorphism is an ability of an object to take many forms.
It reacts differently in different situation. In Java, polymorphism is used to
reduce code complexities. Methods or function of a class implies the behaviour
of polymorphism. In Java, all Java objects are polymorphic.
OOPs Concepts in Java with Examples:

 Class Example: class Car { String color; void accelerate() { ... } }


 Object Example: Car myCar = new Car();
 Inheritance Example: class ElectricCar extends Car { ... }
 Polymorphism Example: Method overloading and overriding.
 Abstraction Example: Abstract classes and interfaces.
 Encapsulation Example: Private fields with public getters and setters.

Advantage/Benefit of OOPs Concepts in Java

OOPs concept in Java offers several advantages that are not available in
procedural programming like C, Pascal, etc. Some of the major benefits of
object-oriented programming in java are as follows:
1. Security: In OOP, data is encapsulated with methods in the class so that data
is protected and secured from accidental modification by other external non-
member methods.

2. Reusability: Through inheritance, we can use the features of an existing class


in a new class without repeating existing code that saves a lot of time for
developers, and also increases productivity.

3. Effective communication: In OOP, objects can communicate via message


passing technique that makes interface descriptions with outside systems much
simpler.

4. Developing complex software: OOPs is the most suitable approach for


developing complex software because it minimizes the complexity through the
feature of inheritance.

5. Easily upgraded: Object-oriented system can be easily upgraded from small


to large systems because OOP uses bottom-up approach.
6. Easy partition of work: It is easy to partition complicated work in a project
based on objects.

7. Maintenance: The maintenance of object-oriented code is easier.

8. Efficiency: The concepts of OOP provide better efficiency and an easy


development process.
Chapter 3 :Fundamentals of Java Programming: Keywords,
Data Types & Programming Constructs
The smallest individual unit in a Java program is called a Token in Java.
Java has 5 tokens

1.Java Keywords

 A keyword is a reserved word that conveys special meaning to the Java


compiler.
 These are reserved for special purposes and we cannot use them as
identifier names otherwise the compiler will give an error.
 There are 51 keywords, but 2 of them are not used which are-goto and
const.
 These keywords form the basic building blocks of Java programs,
allowing developers to define classes, control flow, handle exceptions,
and manage various aspects of their code.
 Only 49 keywords are A list of Java keywords or reserved words are
given below:
Java :Data Type

Data types specify the different sizes and values that can be stored in the
variable. There are two types of data types in Java:

a. Primitive data types: The primitive data types include boolean, char,
byte, short, int, long, float and double.

b. Non-primitive data types: The non-primitive data types include Classes,


Interfaces, and Arrays.

a. Primitive Data Types

In Java language, primitive data types are the building blocks of data
manipulation. These are the most basic data types available in Java language.

There are 8 types of primitive data types:

 boolean data type


 byte data type
 char data type
 short data type
 int data type
 long data type
 float data type
 double data type

Boolean Data Type


 The Boolean data type is used to store only two possible values: true and
false. This data type is used for simple flags that track true/false
conditions.
 The Boolean data type specifies one bit of information, but its "size" can't
be defined precisely.
 Example: Boolean one = false

Byte Data Type

 The byte data type is an example of primitive data type.


 It is an 8-bit signed two's complement integer.
 Its value-range lies between -128 to 127 (inclusive). Its minimum value is
-128 and maximum value is 127. Its default value is 0.
 The byte data type is used to save memory in large arrays where the
memory savings is most required. It saves space because a byte is 4 times
smaller than an integer. It can also be used in place of "int" data type.

 Example: byte a = 10, byte b = -20

Short Data Type

 The short data type is a 16-bit signed two's complement integer.


 Its value-range lies between -32,768 to 32,767 (inclusive).
 Its minimum value is -32,768 and maximum value is 32,767.
 Its default value is 0.
 The short data type can also be used to save memory just like byte data
type.
 A short data type is 2 times smaller than an integer.
 Example:

 short s = 10000, short r = -5000


Int Data Type

 The int data type is a 32-bit signed two's complement integer.


 Its value-range lies between - 2,147,483,648 (-2^31) to 2,147,483,647
(2^31 -1) (inclusive).
 Its minimum value is - 2,147,483,648and maximum value is
2,147,483,647.
 Its default value is 0.
 The int data type is generally used as a default data type for integral
values unless if there is no problem about memory.
 Example: int a = 100000, int b = -200000

Long Data Type

 The long data type is a 64-bit two's complement integer.


 Its value-range lies between -9,223,372,036,854,775,808(-2^63) to
9,223,372,036,854,775,807(2^63 -1)(inclusive).
 Its minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807.
 Its default value is 0.
 The long data type is used when you need a range of values more than
those provided by int.
 Example: long a = 100000L, long b = -200000L

Float Data Type

 The float data type is a single-precision 32-bit IEEE 754 floating point.
 Its value range is unlimited.
 It is recommended to use a float (instead of double) if you need to save
memory in large arrays of floating point numbers.
 The float data type should never be used for precise values, such as
currency.
 Its default value is 0.0F.
 Example:float f1 = 234.5f

Double Data Type

 The double data type is a double-precision 64-bit IEEE 754 floating


point.
 Its value range is unlimited.
 The double data type is generally used for decimal values just like float.
 The double data type also should never be used for precise values, such as
currency.
 Its default value is 0.0d.
 Example: double d1 = 12.3

Char Data Type

 The char data type is a single 16-bit Unicode character.


 Its value-range lies between '\u0000' (or 0) to '\uffff' (or 65,535
inclusive).
 The char data type is used to store characters.
 Example: char letterA = 'A'
Programming Constructs

Java supports various programming constructs that allow you to structure and
control the flow of your programs. Here are some essential Java programming
constructs:

1.Variables and Data Types: Declare and initialize variables to store data. Use
different data types like int, double, String, etc.

Example:1) int age = 25;


2) double salary = 50000.50;
3) String name = "John Doe";

2. Operators:

Use operators for arithmetic, comparison, logical operations, etc.

Example: int x = 5;
int y = 10;
int sum = x + y;
boolean isGreaterThan = x > y;

3)Control Flow Statements:

a) if-else Statements:

int number = 7;
if (number % 2 == 0)
{
System.out.println("Even");
}
else
{
System.out.println("Odd");
}

b)Switch Statement:

int dayOfWeek = 3;
switch (dayOfWeek)
{
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
// ...
default:
System.out.println("Invalid day");
}

c)for Loop:

for (int i = 1; i <= 5; i++)


{
System.out.println("Iteration " + i);
}

d)while Loop:
int count = 0;
while (count < 5)
{
System.out.println("Count: " + count);
count++;
}

e)do-while Loop:

int i = 1;

do {
System.out.println("Value of i: " + i);
i++;
} while (i <= 5);

Arrays:

 Declare and initialize arrays to store multiple values of the same type.

Example:
 int[] numbers = {1, 2, 3, 4, 5};

Methods (Functions):

 Define and call methods to group code into reusable blocks.

Example: public static int add(int a, int b) {


return a + b;
}

int result = add(3, 4);

Classes and Objects:

 Define classes to encapsulate data and behaviour. Create objects to


instantiate and use those classes.

 public class Person {


String name;
int age;

public Person(String name, int age) {


this.name = name;
this.age = age;
}

public void displayInfo() {


System.out.println("Name: " + name + ", Age: " + age);
}
}

Person person1 = new Person("Alice", 30);


person1.displayInfo();

Inheritance:
 Create a hierarchy of classes, allowing a subclass to inherit properties and
methods from a superclass.

public class Animal {


void eat() {
System.out.println("Animal is eating");
}
}

public class Dog extends Animal {


void bark() {
System.out.println("Dog is barking");
}
}

Interfaces:

 Define interfaces to provide a contract for classes implementing them.

public interface Shape {


double calculateArea();
}

public class Circle implements Shape {


double radius;

@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}

These are fundamental constructs in Java that you'll encounter when writing
Java programs. They help in organizing code, making it more readable,
maintainable, and reusable.

Here's a simple Java program that prints "Hello, World!" to the console:

public class HelloWorld


{
public static void main(String[] args)
{
System.out.println("Hello, World!");
}
}

This is a basic "Hello, World!" program in Java. Here's a breakdown of the


code:

 public class HelloWorld: Declares a class named HelloWorld. In Java,


every application consists of at least one class, and the main method is the
entry point.
 public static void main(String[] args): This is the main method. It is the
starting point for the execution of the program. The String[] args
parameter allows you to pass command-line arguments, although this
program doesn't use them.
 System.out.println("Hello, World!");: This line prints the string "Hello,
World!" to the console. The println method is used to print a line and
move the cursor to the next line.

To run this program, save it in a file named HelloWorld.java and then compile
and execute it using a Java compiler and the Java Virtual Machine (JVM).
Chapter 4: Java -fundamental classes

A class is a blueprint for the object. Before we create an object, we first


need to define the class.

We can think of the class as a sketch (prototype) of a house. It contains all the
details about the floors, doors, windows, etc. Based on these descriptions we
build the house. House is the object.

Since many houses can be made from the same description, we can create many
objects from a class.

How to Create a Class In Java?

 We can define a typical class in Java using the following syntax:

<Access Specifier> class <class name>{ //Body }

 Example: public class Student{


String Name;
int rollno;
String section;
}

Rules for Creating Classes

The following rules are mandatory when you’re working with Java classes:

 The keyword “class” must be used to declare a class


 Every class name should start with an upper case character, and if you
intend to include multiple words in a class name, make sure you use the
camel case
 A Java project can contain any number of default classes but should not
hold more than one public class

 You should not use special characters when naming classes

 You can implement multiple interfaces by writing their names in front of


the class, separated by commas
 You should expect a Java class to inherit only one parent class

 Java Object Class is basically the parent class of all classes. In other
words, it is the topmost class of java. By Default, It extends to every class
of java. Object class comes under the java.lang package.
 Lang package has included by default.
 If any Java class does not extend any other class then it is a direct child
class of Object and if extends other class then it is indirectly derived.
 Therefore we can easily
 use all the methods of Object class. Object class has many inbuilt
methods that we can use to fulfill the requirement.

 Object Class Methods: Java Object class has many inbuilt methods.
These methods are very commonly used in programming. But we do
not know exactly which method belongs to Object Class. There are
list of all methods of Object Class.
Objects and Classes in Java

we design a program using objects and classes.An object in Java is the physical
as well as a logical entity, whereas, a class in Java is a logical entity only. An
entity that has state and behavior is known as an object e.g., chair, bike, marker,
pen, table, car, etc. It can be physical or logical (tangible and intangible). The
example of an intangible object is the banking system.

An object has three characteristics:

 State: represents the data (value) of an object.


 Behavior: represents the behavior (functionality) of an object such as
deposit, withdraw, etc.
 Identity: An object identity is typically implemented via a unique ID.
The value of the ID is not visible to the external user. However, it is used
internally by the JVM to identify each object uniquely.

For Example, Pen is an object. Its name is Reynolds; color is white, known as
its state. It is used to write, so writing is its behavior.

An object is an instance of a class. A class is a template or blueprint from


which objects are created. So, an object is the instance(result) of a class.

Object Definitions:

 An object is a real-world entity.


 An object is a runtime entity.
 The object is an entity which has state and behavior.
 The object is an instance of a class.

A class is a group of objects which have common properties. It is a template or


blueprint from which objects are created. It is a logical entity. It can't be
physical.

A class in Java can contain:

 Fields
 Methods
 Constructors
 Blocks
 Nested class and interface
Object and Class Example: main within the class
In this example, we have created a Student class which has two data members id
and name. We are creating the object of the Student class by new keyword and
printing the object's value.

Here, we are creating a main() method inside the class.

File: Student.java

//Java Program to illustrate how to define a class and fields

//Defining a Student class.

class Student{

//defining fields

int id;//field or data member or instance variable

String name;

//creating main method inside the Student class

public static void main(String args[]){

//Creating an object or instance

Student s1=new Student();//creating an object of Student

//Printing values of the object

System.out.println(s1.id);//accessing member through reference variable

System.out.println(s1.name);

}
Object and Class Example: main outside the class

In real time development, we create classes and use it from another class. It is a
better approach than previous one. Let's see a simple example, where we are
having main() method in another class.

We can have multiple classes in different Java files or single Java file. If you
define multiple classes in a single Java source file, it is a good idea to save the
file name with the class name which has main() method.

File: TestStudent1.java

//Java Program to demonstrate having the main method in

//another class

//Creating Student class.

class Student{

int id;

String name;

//Creating another class TestStudent1 which contains the main method

class TestStudent1{

public static void main(String args[]){

Student s1=new Student();


System.out.println(s1.id);

System.out.println(s1.name);

3 Ways to initialize object

There are 3 ways to initialize object in Java.

1. By reference variable
2. By method
3. By constructor

1) Object and Class Example: Initialization through reference

Initializing an object means storing data into the object. Let's see a simple
example where we are going to initialize the object through a reference variable.

class Student

int id;

String name;

}
class TestStudent2{

public static void main(String args[]){

Student s1=new Student();

s1.id=101;

s1.name="Sonoo";

System.out.println(s1.id+" "+s1.name);//printing members with a white


space

Output:

101 Sonoo

2) Object and Class Example: Initialization through method

In this example, we are creating the two objects of Student class and initializing
the value to these objects by invoking the insertRecord method. Here, we are
displaying the state (data) of the objects by invoking the displayInformation()
method.

class Student{

int rollno;
String name;

void insertRecord(int r, String n){

rollno=r;

name=n;

void displayInformation(){System.out.println(rollno+" "+name);}

class TestStudent4{

public static void main(String args[]){

Student s1=new Student();

Student s2=new Student();

s1.insertRecord(111,"Karan");

s2.insertRecord(222,"Aryan");

s1.displayInformation();

s2.displayInformation();

Output:
111 Karan
222 Aryan

As you can see in the above figure, object gets the memory in heap memory
area. The reference variable refers to the object allocated in the heap memory
area. Here, s1 and s2 both are reference variables that refer to the objects
allocated in memory.

3) Object and Class Example: Initialization through a constructor


n object-oriented programming, a class is a blueprint for creating objects, and
objects are instances of a class. Constructors are special methods in a class that
are used for initializing the attributes of an object when it is created.

public class Car {

// Class attributes

String make;

String model;

int year;
boolean isRunning;

// Constructor

public Car(String make, String model, int year) {

this.make = make;

this.model = model;

this.year = year;

this.isRunning = false;

// Method to start the engine

public void startEngine() {

System.out.println("The " + year + " " + make + " " + model + "'s engine is
now running.");

isRunning = true;

// Method to stop the engine

public void stopEngine() {

System.out.println("The " + year + " " + make + " " + model + "'s engine is
now stopped.");

isRunning = false;
}

public static void main(String[] args) {

// Creating an instance of the Car class

Car myCar = new Car("Toyota", "Camry", 2022);

// Accessing and printing attributes

System.out.println("My car: " + myCar.year + " " + myCar.make + " " +


myCar.model);

System.out.println("Is the engine running? " + myCar.isRunning);

// Starting the engine

myCar.startEngine();

System.out.println("Is the engine running? " + myCar.isRunning);

// Stopping the engine

myCar.stopEngine();

System.out.println("Is the engine running? " + myCar.isRunning);

In this Java example, the Car class has a constructor that takes three parameters
(make, model, and year) and initializes the corresponding attributes of the class.
The startEngine and stopEngine methods demonstrate how you can perform
actions on the object.

When you run this Java program, you will see output indicating the state of the
car's engine as it is started and stopped.

Package overview
 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.

What Are Packages in Java?

 A set of classes and interfaces grouped together are known as Packages in


JAVA.
 The name itself defines that pack (group) of related types such as classes,
sub-packages, enumeration, annotations, and interfaces that provide
name-space management.
 Every class is a part of a certain package.
 When you need to use an existing class, you need to add the package
within the Java program.
 The package keyword is used to create a package in java.
 Example:

package mypack;
public class Simple{

public static void main(String args[])

{ System.out.println("Welcome to package");

} }

Why Are They Used For?

The benefits of using Packages in Java are as follows:

 The packages organize the group of classes into a single API unit
 It will control the naming conflicts
 The access protection will be easier. Protected and default are the access
level control to the package
 Easy to locate the related classes
 Reuse the existing classes in packages

You can categorize packages into:

 Built-in Packages
 User-defined Packages
The built-in packages are from the Java API. The JAVA API is the library of
pre-defined classes available in the Java Development Environment. Few built-
in packages are below:

 Java.lang–Bundles the fundamental classes


 Java.io - Bundle of input and output function classes
 Java.awt–Bundle of abstract window toolkit classes
 Java.swing–Bundle of windows application GUI toolkit classes
 Java.net–Bundle of network infrastructure classes
 Java.util–Bundle of collection framework classes
 Java.applet–Bundle of creating applet classes
 Java.sql -Bundle of related data processing classes

The built-in packages are again categorized into extension packages. These
extension packages start with javax. This is for all the Java languages, which
have lightweight component classes.
 Javax.swing
 Javax.servlet
 Javax.sql

Note: The default package imported with no declaration is java.lang package.

Naming Conventions

Package names are written in all lower case to avoid conflict with the names of
classes or interfaces.

Companies use their reversed Internet domain name to begin their package
names—for example, com.example.mypackage for a package named
mypackage created by a programmer at example.com.

packagemypack;
public class Simple{

public static void main(String args[]){

System.out.println("Welcome to package");

}}

How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

javac -d directory javafilename

How to run java package program

To Compile: javac -d . Simple.java

To Run: java mypack.Simple


Chapter 5: Java string
 string is basically an object that represents sequence of char values. An
array of characters works same as java string.
 For example:
o char[] ch={'j','a','v','a','t','p','o','i','n','t'};
o String s=new String(ch);ssame as:
o Strings="javatpoint";
 Java String class provides a lot of methods to perform operations on
string such as compare(),concat(), equals(), split(), length(), replace(),
compareTo(), intern(), substring() etc.
 The java.lang.String class implements Serializable, Comparable and
CharSequenceinterface

 The CharSequence interface is used to represent sequence of characters.


It is implemented by String,StringBuffer and StringBuilder classes. It
means, we can create string in java by using these 3 classes.
 The java String is immutable i.e. it cannot be changed. Whenever we
change any string, a new instance is created. For mutable string, you can
use StringBuffer and StringBuilderclasses.
 There are two ways to create String object:
1) By stringliteral
 Java String literal is created by using double quotes.
For Example:String s="welcome";
 Each time you create a string literal, the JVM checks the string constant
pool first. If the string already exists in the pool, a reference to the pooled
instance is returned. If string doesn't exist in the pool, a new
 string instance is created and placed in the pool.
For example:
o Strings1="Welcome";
o String s2="Welcome";//will not create newinstance

 In the above example, only one object will be created.


 Firstly, JVM will not find any string object with the value "Welcome" in
string constant pool that is why it will create a new object. After that it
will find the string with the value "Welcome" in the pool, it will not
create a new object but will return the reference to the same instance.
2. By newkeyword

 Example: String s=new String("Welcome"); //creates two objects and one


reference variable
 In such case, JVM will create a new string object in normal (non pool)
heap memory and the literal
 "Welcome" will be placed in the string constant pool. The variable s will
refer to the object in heap (non pool).

public class StringExample{

public static void main(String args[]){

String s1="java";//creating string by java string literal

charch[]={'s','t','r','i','n','g','s'};

String s2=new String(ch);//converting char array to string

String s3=new String("example");//creating java string by new


keywordSystem.out.println(s1);

System.out.println(s2);System.out.println(s3);

}}

OUTPUT:

java
strings
example
Immutable String in Java

 A String is an unavoidable type of variable while writing any application


program.
 String references are used to store various attributes like username,
password, etc.
 In Java, String objects are immutable. Immutable simply means
unmodifiable or unchangeable.Once String object is created its data or
state can't be changed but a new String object is created.
 Let's try to understand the concept of immutability by the example given
below:

class Testimmutablestring

public static void main(String args[]){

String s="Sachin";

s.concat(" Tendulkar"); //concat() method appends the string at the end

System.out.println(s);
//will print Sachin because strings are immutable objects

Output:Sachin
Now it can be understood by the diagram given below. Here Sachin is not
changed but a new object is created with Sachin Tendulkar. That is why
String is known as immutable.

As you can see in the above figure that two objects are created but reference
variable still refers to "Sachin" not to "Sachin Tendulkar".

 But if we explicitly assign it to the reference variable, it will refer to


"Sachin Tendulkar" object.
Why String objects are immutable in Java?

As Java uses the concept of String literal. Suppose there are 5 reference
variables, all refer to one object "Sachin". If one reference variable changes the
value of the object, it will be affected by all the reference variables. That is why
String objects are immutable in Java.

Following are some features of String which makes String objects immutable.

1. ClassLoader:

A ClassLoader in Java uses a String object as an argument. Consider, if the


String object is modifiable, the value might be changed and the class that is
supposed to be loaded might be different. To avoid this kind of
misinterpretation, String is immutable.

2. Thread Safe:

As the String object is immutable we don't have to take care of the


synchronization that is required while sharing an object across multiple threads.

3. Security:

As we have seen in class loading, immutable String objects avoid further errors
by loading the correct class. This leads to making the application program more
secure. Consider an example of banking software. The username and password
cannot be modified by any intruder because String objects are immutable. This
can make the application program more secure.

4. Heap Space:

The immutability of String helps to minimize the usage in the heap memory.
When we try to declare a new String object, the JVM checks whether the value
already exists in the String pool or not. If it exists, the same value is assigned to
the new object. This feature allows Java to use the heap space efficiently.

Why String class is Final in Java?

The reason behind the String class being final is because no one can override
the methods of the String class. So that it can provide the same features to the
new String objects as well as to the old ones.

Java String compare

 We can compare String in Java on the basis of content and reference.


 It is used in authentication (by equals() method), sorting (by
compareTo() method), reference matching (by == operator) etc.

 There are three ways to compare String in Java:

1) By Using equals() Method

2) By Using == Operator

3) By compareTo() Method
1) By Using equals() Method

The String class equals() method compares the original content of the string. It
compares values of string for equality. String class provides the following two
methods:

 public boolean equals(Object another) compares this string to the


specified object.
 public boolean equalsIgnoreCase(String another) compares this string
to another string, ignoring case.

class Teststringcomparison1{

public static void main(String args[]){

String s1="Sachin";

String s2="Sachin";

String s3=new String("Sachin");

String s4="Saurav";

System.out.println(s1.equals(s2));//true

System.out.println(s1.equals(s3));//true

System.out.println(s1.equals(s4));//false
}

Output: true
true
false

In the above code, two strings are compared using equals() method of String
class. And the result is printed as boolean values, true or false.

2) By Using == operator

The == operator compares references not values.

class Teststringcomparison3{

public static void main(String args[]){

String s1="Sachin";

String s2="Sachin";

String s3=new String("Sachin");

System.out.println(s1==s2);//true (because both refer to same instance)

System.out.println(s1==s3);//false(because s3 refers to instance created in


nonpool)
}

Output: true
false

3) By Using compareTo() method

The String class compareTo() method compares values lexicographically and


returns an integer value that describes if first string is less than, equal to or
greater than second string.

Suppose s1 and s2 are two String objects. If:

 s1 == s2 : The method returns 0.


 s1 > s2 : The method returns a positive value.
 s1 < s2 : The method returns a negative value.

class Teststringcomparison4{

public static void main(String args[]){

String s1="Sachin";

String s2="Sachin";

String s3="Ratan";
System.out.println(s1.compareTo(s2));//0

System.out.println(s1.compareTo(s3));//1(because s1>s3)

System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )

Output:

0
1

-1
String methods:

Java String class methods

The java.lang.String class provides many useful methods to perform operations


on sequence of char values.
String Length

A String in Java is actually an object, which contain methods that can perform
certain operations on strings. For example, the length of a string can be found
with the length() method:

Example
public class Main
{
public static void main(String[] args)
{
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println("The length of the txt string is: " + txt.length());
}
}

Output:The length of the txt string is: 26

2)

public class Main {

public static void main(String[] args) {

String txt = "Hello World";

System.out.println(txt.toUpperCase());

System.out.println(txt.toLowerCase());

}}

Output: HELLO WORLD


hello world

3) Finding a Character in a String

Java counts positions from zero.0 is the first position in a string, 1 is the second,
2 is the third ...The indexOf() method returns the index (the position) of the first
occurrence of a specified text in a string (including whitespace):

public class Main {


public static void main(String[] args) {

String txt = "Please locate where 'locate' occurs!";

System.out.println(txt.indexOf("locate"));

Output:7

String Concatenation

The + operator can be used between strings to combine them. This is called
concatenation:

public class Main {

public static void main(String args[]) {

String firstName = "John";

String lastName = "Doe";

System.out.println(firstName + " " + lastName);

Output: public class Main {


public static void main(String args[]) {
String firstName = "John";
String lastName = "Doe";
System.out.println(firstName + " " + lastName);
}
}

Output:John Doe

Note that we have added an empty text (" ") to create a space between firstName
and lastName on print.You can also use the concat() method to concatenate two
strings:

public class Main {

public static void main(String[] args) {

String firstName = "John ";

String lastName = "Doe";

System.out.println(firstName.concat(lastName));

Output: John Doe

Adding Numbers and Strings

Java uses the + operator for both addition and concatenation.

Numbers are added. Strings are concatenated.

If you add two numbers, the result will be a number:


public class Main {

public static void main(String[] args) {

int x = 10;

int y = 20;

int z = x + y;

System.out.println(z);

Output:30

If you add two strings, the result will be a string concatenation:

public class Main {

public static void main(String[] args) {

String x = "10";

String y = "20";

String z = x + y;

System.out.println(z);

Output:1020
If you add a number and a string, the result will be a string concatenation:

public class Main {

public static void main(String[] args) {

String x = "10";

int y = 20;

String z = x + y;

System.out.println(z);

Output:1020

Strings - Special Characters

ecause strings must be written within quotes, Java will misunderstand this
string, and generate an error:

String txt = "We are the so-called "Vikings" from the north.";

The solution to avoid this problem, is to use the backslash escape character.

The backslash (\) escape character turns special characters into string characters:

The sequence \" inserts a double quote in a string:


public class Main {

public static void main(String[] args) {

String txt = "We are the so-called \"Vikings\" from the north.";

System.out.println(txt);

Output:

We are the so-called "Vikings" from the north.

The sequence \' inserts a single quote in a string:

public class Main {

public static void main(String[] args) {

String txt = "It\'s alright.";

System.out.println(txt);

Output: It's alright.

The sequence \\ inserts a single backslash in a string: public class Main {

public static void main(String[] args) {

String txt = "The character \\ is called backslash.";


System.out.println(txt);

Output: The character \ is called backslash.

Other common escape sequences that are valid in Java are:

Java StringBuffer Class

Java StringBuffer class is used to create mutable (modifiable) String objects.


The StringBuffer class in Java is the same as String class except it is mutable
i.e. it can be changed.

Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously. So it is safe and will result in an order.
Important Constructors of StringBuffer Class
Important methods of StringBuffer class
What is a mutable String?

A String that can be modified or changed is known as mutable String.


StringBuffer and StringBuilder classes are used for creating mutable strings.

1) StringBuffer Class append() Method

The append() method concatenates the given argument with this String.

StringBufferExample.java

class StringBufferExample{

public static void main(String args[]){

StringBuffer sb=new StringBuffer("Hello ");

sb.append("Java");//now original string is changed


System.out.println(sb);//prints Hello Java

Output:

Hello Java

2) StringBuffer insert() Method

The insert() method inserts the given String with this string at the given
position.

StringBufferExample2.java

class StringBufferExample2{

public static void main(String args[]){

StringBuffer sb=new StringBuffer("Hello ");

sb.insert(1,"Java");//now original string is changed

System.out.println(sb);//prints HJavaello

Output:

HJavaello
3) StringBuffer replace() Method

The replace() method replaces the given String from the specified beginIndex
and endIndex.

StringBufferExample3.java

class StringBufferExample3{

public static void main(String args[]){

StringBuffer sb=new StringBuffer("Hello");

sb.replace(1,3,"Java");

System.out.println(sb);//prints HJavalo

Output:

HJavalo

4) StringBuffer delete() Method

The delete() method of the StringBuffer class deletes the String from the
specified beginIndex to endIndex.

StringBufferExample4.java

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

StringBuffer sb=new StringBuffer("Hello");

sb.delete(1,3);

System.out.println(sb);//prints Hlo

Output:

Hlo

5) StringBuffer reverse() Method

The reverse() method of the StringBuilder class reverses the current String.

StringBufferExample5.java

class StringBufferExample5{

public static void main(String args[]){

StringBuffer sb=new StringBuffer("Hello");

sb.reverse();

System.out.println(sb);//prints olleH

}
}

Output:

olleH

6) StringBuffer capacity() Method

The capacity() method of the StringBuffer class returns the current capacity of
the buffer. The default capacity of the buffer is 16. If the number of character
increases from its current capacity, it increases the capacity by
(oldcapacity*2)+2. For example if your current capacity is 16, it will be
(16*2)+2=34.

StringBufferExample6.java

class StringBufferExample6{

public static void main(String args[]){

StringBuffer sb=new StringBuffer();

System.out.println(sb.capacity());//default 16

sb.append("Hello");

System.out.println(sb.capacity());//now 16

sb.append("java is my favourite language");


System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2

Output:

16

16

34

7) StringBuffer ensureCapacity() method

The ensureCapacity() method of the StringBuffer class ensures that the given
capacity is the minimum to the current capacity. If it is greater than the current
capacity, it increases the capacity by (oldcapacity*2)+2. For example if your
current capacity is 16, it will be (16*2)+2=34.

StringBufferExample7.java
class StringBufferExample7{

public static void main(String args[]){

StringBuffer sb=new StringBuffer();

System.out.println(sb.capacity());//default 16

sb.append("Hello");

System.out.println(sb.capacity());//now 16

sb.append("java is my favourite language");

System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2

sb.ensureCapacity(10);//now no change

System.out.println(sb.capacity());//now 34

sb.ensureCapacity(50);//now (34*2)+2

System.out.println(sb.capacity());//now 70

Output:

16
16
34
34
70
Java StringBuilder Class
Java StringBuilder class is used to create mutable (modifiable) String. The Java
StringBuilder class is same as StringBuffer class except that it is non-
synchronized. It is available since JDK 1.5.

Important Constructors of StringBuilder class

Important methods of StringBuilder class


Java StringBuilder Examples

Let's see the examples of different methods of StringBuilder class.

1) StringBuilder append() method

The StringBuilder append() method concatenates the given argument with this
String.

StringBuilderExample.java

1. class StringBuilderExample{
2. public static void main(String args[]){

3. StringBuilder sb=new StringBuilder("Hello ");


4. sb.append("Java");//now original string is changed

5. System.out.println(sb);//prints Hello Java


6. }

7. }

Output:

Hello Java

2) StringBuilder insert() method

The StringBuilder insert() method inserts the given string with this string at the
given position.

StringBuilderExample2.java
1. class StringBuilderExample2{
2. public static void main(String args[]){

3. StringBuilder sb=new StringBuilder("Hello ");


4. sb.insert(1,"Java");//now original string is changed

5. System.out.println(sb);//prints HJavaello
6. }

7. }

Output:

HJavaello
3) StringBuilder replace() method

The StringBuilder replace() method replaces the given string from the specified
beginIndex and endIndex.

StringBuilderExample3.java

1. class StringBuilderExample3{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.replace(1,3,"Java");
5. System.out.println(sb);//prints HJavalo
6. }
7. }

Output:

HJavalo
4) StringBuilder delete() method

The delete() method of StringBuilder class deletes the string from the specified
beginIndex to endIndex.

StringBuilderExample4.java

1. class StringBuilderExample4{
2. public static void main(String args[]){

3. StringBuilder sb=new StringBuilder("Hello");


4. sb.delete(1,3);

5. System.out.println(sb);//prints Hlo
6. }

7. }

Output:

Hlo

5) StringBuilder reverse() method

The reverse() method of StringBuilder class reverses the current string.

StringBuilderExample5.java

1. class StringBuilderExample5{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.reverse();

5. System.out.println(sb);//prints olleH
6. }

7. }

Output:

olleH

6) StringBuilder capacity() method

The capacity() method of StringBuilder class returns the current capacity of the
Builder. The default capacity of the Builder is 16. If the number of character
increases from its current capacity, it increases the capacity by
(oldcapacity*2)+2. For example if your current capacity is 16, it will be
(16*2)+2=34.

StringBuilderExample6.java

class StringBuilderExample6{

public static void main(String args[]){

StringBuilder sb=new StringBuilder();

System.out.println(sb.capacity());//default 16

sb.append("Hello");

System.out.println(sb.capacity());//now 16
sb.append("Java is my favourite language");

System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+


2

Output:

16
16
34

7) StringBuilder ensureCapacity() method

The ensureCapacity() method of StringBuilder class ensures that the given


capacity is the minimum to the current capacity. If it is greater than the current
capacity, it increases the capacity by (oldcapacity*2)+2. For example if your
current capacity is 16, it will be (16*2)+2=34.

StringBuilderExample7.java

class StringBuilderExample7{

public static void main(String args[]){

StringBuilder sb=new StringBuilder();

System.out.println(sb.capacity());//default 16

sb.append("Hello");
System.out.println(sb.capacity());//now 16

sb.append("Java is my favourite language");

System.out.println(sb.capacity());
//now (16*2)+2=34 i.e (oldcapacity*2)+2

sb.ensureCapacity(10);//now no change

System.out.println(sb.capacity());//now 34

sb.ensureCapacity(50);//now (34*2)+2

System.out.println(sb.capacity());//now 70

Output:

16

16

34

34

70
Difference between String and StringBuffer

There are many differences between String and StringBuffer. A list of


differences between String and StringBuffer are given below:
Difference between StringBuffer and StringBuilder

Java provides three classes to represent a sequence of characters: String,


StringBuffer, and StringBuilder. The String class is an immutable class whereas
StringBuffer and StringBuilder classes are mutable. There are many differences
between StringBuffer and StringBuilder. The StringBuilder class is introduced
since JDK 1.5.

A list of differences between StringBuffer and StringBuilder is given below:


Chapter 6: Exception handling in java
The Exception Handling in Java is one of the powerful mechanism to
handle the runtime errors so that the normal flow of the application can be
maintained.

 What is Exception in Java?


Dictionary Meaning: Exception is an abnormal condition.In Java, an
exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.

 What is Exception Handling?

Exception Handling is a mechanism to handle runtime errors such as


ClassNotFoundException, IOException, SQLException,
RemoteException, etc.

 Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal


flow of the application. An exception normally disrupts the normal flow of the
application; that is why we need to handle exceptions. Let's consider a scenario:

1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10.statement 10;

Suppose there are 10 statements in a Java program and an exception occurs at


statement 5; the rest of the code will not be executed, i.e., statements 6 to 10
will not be executed. However, when we perform exception handling, the rest of
the statements will be executed. That is why we use exception handling in Java.

Hierarchy of Java Exception classes

The java.lang.Throwable class is the root class of Java Exception hierarchy


inherited by two subclasses: Exception and Error. The hierarchy of Java
Exception classes is given below:

Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked. An error is
considered as the unchecked exception. However, according to Oracle, there are
three types of exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error

Difference between Checked and Unchecked Exceptions

1) Checked Exception

The classes that directly inherit the Throwable class except RuntimeException
and Error are known as checked exceptions. For example, IOException,
SQLException, etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception

The classes that inherit the RuntimeException are known as unchecked


exceptions. For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked
at compile-time, but they are checked at runtime.

3) Error

Error is irrecoverable. Some example of errors are OutOfMemoryError,


VirtualMachineError, AssertionError etc.

Java Exception Keywords

Java provides five keywords that are used to handle the exception. The
following table describes each.
Java Exception Handling Example

Let's see an example of Java Exception Handling in which we are using a try-
catch statement to handle the exception.

public class JavaExceptionExample{

public static void main(String args[]){

try{

int data=100/0;

}catch(ArithmeticException e){System.out.println(e);}

System.out.println("rest of the code...");

Output:

Exception in thread main java.lang.ArithmeticException:/ by zero


rest of the code...
In the above example, 100/0 raises an ArithmeticException which is
handled by a try-catch block.

Common Scenarios of Java Exceptions

There are given some scenarios where unchecked exceptions may occur. They
are as follows:
1) A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

1. int a=50/0;//ArithmeticException

2) A scenario where NullPointerException occurs

If we have a null value in any variable, performing any operation on the


variable throws a NullPointerException.

1. String s=null;
2. System.out.println(s.length());//NullPointerException

3) A scenario where NumberFormatException occurs

If the formatting of any variable or number is mismatched, it may result into


NumberFormatException. Suppose we have a string variable that has
characters; converting this variable into digit will cause
NumberFormatException.

String s="abc";

int i=Integer.parseInt(s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs

When an array exceeds to it's size, the ArrayIndexOutOfBoundsException


occurs. there may be other reasons to occur ArrayIndexOutOfBoundsException.
Consider the following statements.

int a[]=new int[5];


Java Try-Catch Block: Java try block

Java try block is used to enclose the code that might throw an exception. It must
be used within the method.

If an exception occurs at the particular statement in the try block, the rest of the
block code will not execute. So, it is recommended not to keep the code in try
block that will not throw an exception.

Java try block must be followed by either catch or finally block.

Syntax of Java try-catch

try{

//code that may throw an exception

}catch(Exception_class_Name ref){}

Syntax of try-finally block

try{

//code that may throw an exception

}finally{}

Java catch block

 Java catch block is used to handle the Exception by declaring the type of
exception within the parameter.
 The declared exception must be the parent class exception ( i.e.,
Exception) or the generated exception type. However, the good approach
is to declare the generated type of exception.
 The catch block must be used after the try block only. You can use
multiple catch block with a single try block.

Internal Working of Java try-catch block

The JVM firstly checks whether the exception is handled or not. If exception is
not handled, JVM provides a default exception handler that performs the
following tasks:

1. Prints out exception description.


2. Prints the stack trace (Hierarchy of methods where the exception
occurred).
3. Causes the program to terminate.

But if the application programmer handles the exception, the normal flow of the
application is maintained, i.e., rest of the code is executed.
Problem without exception handling

Let's try to understand the problem if we don't use a try-catch block.

Example 1

public class TryCatchExample1 {

public static void main(String[] args) {

int data=50/0; //may throw exception

System.out.println("rest of the code");

Output: Exception in thread "main" java.lang.ArithmeticException: / by zero

As displayed in the above example, the rest of the code is not executed
(in such case, the rest of the code statement is not printed).There might be 100
lines of code after the exception. If the exception is not handled, all the code
below the exception won't be executed.

Solution by exception handling:

Let's see the solution of the above problem by a java try-catch block.

TryCatchExample2.java

public class TryCatchExample2 {


public static void main(String[] args) {

try

int data=50/0; //may throw exception

//handling the exception

catch(ArithmeticException e)

System.out.println(e);

System.out.println("rest of the code");

Output:

java.lang.ArithmeticException: / by zero

rest of the code


As displayed in the above example, the rest of the code is executed, i.e., the
rest of the code statement is printed.

Java Multi-catch block

A try block can be followed by one or more catch blocks. Each catch block
must contain a different exception handler. So, if you have to perform different
tasks at the occurrence of different exceptions, use java multi-catch block.

Points to remember

1. At a time only one exception occurs and at a time only one catch block is
executed.
2. All catch blocks must be ordered from most specific to most general, i.e.
catch for ArithmeticException must come before catch for Exception.
Flowchart of Multi-catch Block

Let's see a simple example of java multi-catch block.

MultipleCatchBlock1.java

public class MultipleCatchBlock1 {

public static void main(String[] args) {

try{

int a[]=new int[5];

a[5]=30/0;

catch(ArithmeticException e)
{

System.out.println("Arithmetic Exception occurs");

catch(ArrayIndexOutOfBoundsException e)

System.out.println("ArrayIndexOutOfBounds
Exception occurs");

catch(Exception e)

System.out.println("Parent Exception occurs");

System.out.println("rest of the code");

Output: Arithmetic Exception occurs


rest of the code
Java Nested try block

In Java, using a try block inside another try block is permitted. It is called as
nested try block. Every statement that we enter a statement in try block, context
of that exception is pushed onto the stack.

For example, the inner try block can be used to handle


ArrayIndexOutOfBoundsException while the outer try block can handle the
ArithemeticException (division by zero).

Why use nested try block

Sometimes a situation may arise where a part of a block may cause one error
and the entire block itself may cause another error. In such cases, exception
handlers have to be nested.
Syntax: ....
//main try block
try
{
statement 1;
statement 2;
//try catch block within another try block
try
{
statement 3;
statement 4;
//try catch block within nested try block
try
{
statement 5;
statement 6;
}
catch(Exception e2)
{
//exception message
}

}
catch(Exception e1)
{
//exception message
}
}
//catch block of parent (outer) try block
catch(Exception e3)
{
//exception message
}
....
Java Nested try Example

Example 1

Let's see an example where we place a try block within another try block for
two different exceptions. public class NestedTryBlock{

public static void main(String args[]){

//outer try block

try{

//inner try block 1

try{

System.out.println("going to divide by 0");

int b =39/0;

//catch block of inner try block 1

catch(ArithmeticException e)

System.out.println(e);
}

//inner try block 2

try{

int a[]=new int[5];

//assigning the value out of array bounds

a[5]=4;

//catch block of inner try block 2

catch(ArrayIndexOutOfBoundsException e)

System.out.println(e);

System.out.println("other statement");

//catch block of outer try block

catch(Exception e)

System.out.println("handled the exception (outer catch)");

System.out.println("normal flow..");
}

Output:

When any try block does not have a catch block for a particular
exception, then the catch block of the outer (parent) try block are checked for
that exception, and if it matches, the catch block of outer try block is executed.

If none of the catch block specified in the code is unable to handle the
exception, then the Java runtime system will handle the exception. Then it
displays the system generated message for that exception.

Java finally block

Java finally block is a block used to execute important code such as closing the
connection, etc.

Java finally block is always executed whether an exception is handled or not.


Therefore, it contains all the necessary statements that need to be printed
regardless of the exception occurs or not.

The finally block follows the try-catch block.

Flowchart of finally block


Why use Java finally block?

1. finally block in Java can be used to put "cleanup" code such as


closing a file, closing connection, etc.
2. The important statements to be printed can be placed in the finally
block.
Usage of Java finally

Let's see the different cases where Java finally block can be used.

Case 1: When an exception does not occur

Let's see the below example where the Java program does not throw any
exception, and the finally block is executed after the try block.

TestFinallyBlock.java

class TestFinallyBlock {

public static void main(String args[]){

try{

//below code do not throw any exception

int data=25/5;

System.out.println(data);

//catch won't be executed

catch(NullPointerException e){

System.out.println(e);

//executed regardless of exception occurred or not


finally {

System.out.println("finally block is always executed");

System.out.println("rest of phe code..."); } }

Output:

Java finally block

Case 2: When an exception occurr but not handled by the catch block

Let's see the the fillowing example. Here, the code throws an exception however
the catch block cannot handle it. Despite this, the finally block is executed after
the try block and then the program terminates abnormally.

TestFinallyBlock1.java

public class TestFinallyBlock1{

public static void main(String args[]){

try {

System.out.println("Inside the try block");

//below code throws divide by zero exception

int data=25/0;
System.out.println(data);

//cannot handle Arithmetic type exception

//can only accept Null Pointer type exception

catch(NullPointerException e){

System.out.println(e);

//executes regardless of exception occured or not

finally {

System.out.println("finally block is always executed");

System.out.println("rest of the code...");

Output:

Java finally block


Case 3: When an exception occurs and is handled by the catch block

Example:

Let's see the following example where the Java code throws an exception and
the catch block handles the exception. Later the finally block is executed after
the try-catch block. Further, the rest of the code is also executed normally.

TestFinallyBlock2.java

public class TestFinallyBlock2{

public static void main(String args[]){

try {

System.out.println("Inside try block");

//below code throws divide by zero exception

int data=25/0;

System.out.println(data);

//handles the Arithmetic Exception / Divide by zero exception

catch(ArithmeticException e){
System.out.println("Exception handled");

System.out.println(e);

//executes regardless of exception occured or not

finally {

System.out.println("finally block is always executed");

System.out.println("rest of the code...");

Output:

Java finally block


Java throw Exception

In Java, exceptions allows us to write good quality codes where the errors are
checked at the compile time instead of runtime and we can create custom
exceptions making the code recovery and debugging easier.

Java throw keyword

 The Java throw keyword is used to throw an exception explicitly.


 We specify the exception object which is to be thrown. The Exception
has some message with it that provides the error description. These
exceptions may be related to user inputs, server, etc.
 We can throw either checked or unchecked exceptions in Java by throw
keyword. It is mainly used to throw a custom exception. We will discuss
custom exceptions later in this section.
 We can also define our own set of conditions and throw an exception
explicitly using throw keyword. For example, we can throw
ArithmeticException if we divide a number by another number. Here, we
just need to set the condition and throw exception using throw keyword.
 The syntax of the Java throw keyword is given below.throw Instance i.e.,

 throw new exception_class("error message");

Let's see the example of throw IOException.

 throw new IOException("sorry device error");

Where the Instance must be of type Throwable or subclass of Throwable. For


example, Exception is the sub class of Throwable and the user-defined
exceptions usually extend the Exception class.
Java throw keyword Example

Example 1: Throwing Unchecked Exception

In this example, we have created a method named validate() that accepts an


integer as a parameter. If the age is less than 18, we are throwing the
ArithmeticException otherwise print a message welcome to vote.

TestThrow1.java

In this example, we have created the validate method that takes integer value as
a parameter. If the age is less than 18, we are throwing the ArithmeticException
otherwise print a message welcome to vote.

public class TestThrow1 {

//function to check if person is eligible to vote or not

public static void validate(int age) {

if(age<18) {

//throw Arithmetic exception if not eligible to vote

throw new ArithmeticException("Person is not eligible to vote");

else {
System.out.println("Person is eligible to vote!!");

//main method

public static void main(String args[]){

//calling the function

validate(13);

System.out.println("rest of the code...");

Output:

Java throw keyword

The above code throw an unchecked exception. Similarly, we can also throw
unchecked and user defined exceptions.
Example 2: Throwing Checked Exception
Note: Every subclass of Error and RuntimeException is an unchecked exception
in Java. A checked exception is everything else under the Throwable class.

TestThrow2.java

import java.io.*;

public class TestThrow2 {

//function to check if person is eligible to vote or not

public static void method() throws FileNotFoundException {

FileReader file = new FileReader("C:\\Users\\Anurati\\Desktop\\


abc.txt");

BufferedReader fileInput = new BufferedReader(file);

throw new FileNotFoundException();

//main method
public static void main(String args[]){

try

method();

catch (FileNotFoundException e)

e.printStackTrace();

System.out.println("rest of the code...");

Output:
Example 3: Throwing User-defined Exception
exception is everything else under the Throwable class.

TestThrow3.java

// class represents user-defined exception

class UserDefinedException extends Exception

public UserDefinedException(String str)

// Calling constructor of parent Exception

super(str);

// Class that uses above MyException

public class TestThrow3

public static void main(String args[])

{
try

// throw an object of user defined exception

throw new UserDefinedException("This is user-defined exception


");

catch (UserDefinedException ude)

System.out.println("Caught the exception");

// Print the message from MyException object

System.out.println(ude.getMessage());

Output:
Java Exception Propagation

An exception is first thrown from the top of the stack and if it is not caught, it
drops down the call stack to the previous method. If not caught there, the
exception again drops down to the previous method, and so on until they are
caught or until they reach the very bottom of the call stack. This is called
exception propagation.

Note: By default Unchecked Exceptions are forwarded in calling chain


(propagated).

Exception Propagation Example

class TestExceptionPropagation1{

void m(){

int data=50/0;

void n(){

m();

void p(){

try{

n();
}catch(Exception e){System.out.println("exception
handled");}

public static void main(String args[]){

TestExceptionPropagation1 obj=new
TestExceptionPropagation1();

obj.p();

System.out.println("normal flow...");

Output:

exception handled

normal flow...

In the above example exception occurs in the m() method where it is not
handled, so it is propagated to the previous n() method where it is not handled,
again it is propagated to the p() method where exception is handled.
Exception can be handled in any method in call stack either in the main()
method, p() method, n() method or m() method.

Note: By default, Checked Exceptions are not forwarded in calling chain


(propagated).

Exception Propagation Example

class TestExceptionPropagation2{

void m(){

throw new java.io.IOException("device error");//checked


exception

void n(){

m();

void p(){

try{

n();

}catch(Exception e){System.out.println("exception
handeled");}

public static void main(String args[]){


TestExceptionPropagation2 obj=new
TestExceptionPropagation2();

obj.p();

System.out.println("normal flow");

Compile Time Error Java throws keyword

The Java throws keyword is used to declare an exception. It gives an


information to the programmer that there may occur an exception. So, it is
better for the programmer to provide the exception handling code so that the
normal flow of the program can be maintained.

Exception Handling is mainly used to handle the checked exceptions. If there


occurs any unchecked exception such as NullPointerException, it is
programmers' fault that he is not checking the code before it being used.

Syntax of Java throws

 return_type method_name() throws exception_class_name{


 //method code

 }

Which exception should be declared?

Ans: Checked exception only, because:


1. unchecked exception: under our control so we can correct our code.
2. error: beyond our control. For example, we are unable to do anything if
there occurs VirtualMachineError or StackOverflowError.
3.

Advantage of Java throws keyword

Now Checked Exception can be propagated (forwarded in call stack).

It provides information to the caller of the method about the exception.

Java throws Example

Let's see the example of Java throws clause which describes that checked
exceptions can be propagated by throws keyword.

Testthrows1.java

import java.io.IOException;

class Testthrows1{

void m()throws IOException{

throw new IOException("device error");//checked exception

void n()throws IOException{

m();

void p(){
try{

n();

}catch(Exception e){System.out.println("exception handled");}

public static void main(String args[]){

Testthrows1 obj=new Testthrows1();

obj.p();

System.out.println("normal flow...");

Output:

exception handled
normal flow...
Rule: If we are calling a method that declares an exception, we must either
caught or declare the exception.

There are two cases:

1. Case 1: We have caught the exception i.e. we have handled the exception
using try/catch block.
2. Case 2: We have declared the exception i.e. specified throws keyword
with the method.

Case 1: Handle Exception Using try-catch block

In case we handle the exception, the code will be executed fine whether
exception occurs during the program or not.

Testthrows2.java

import java.io.*;

class M{

void method()throws IOException{

throw new IOException("device error");

public class Testthrows2{

public static void main(String args[]){

try{

M m=new M();

m.method();

}catch(Exception e){System.out.println("exception handled");}


System.out.println("normal flow...");

Output:

exception handled
normal flow...

Case 2: Declare Exception

1. In case we declare the exception, if exception does not occur, the code
will be executed fine.
2. In case we declare the exception and the exception occurs, it will be
thrown at runtime because throws does not handle the exception.

Let's see examples for both the scenario.

A) If exception does not occur

Testthrows3.java

import java.io.*;

class M{

void method()throws IOException{

System.out.println("device operation performed");

}
}

class Testthrows3{

public static void main(String args[])throws IOException{//declare exce


ption

M m=new M();

m.method();

System.out.println("normal flow...");

Output:

device operation performed


normal flow...

B) If exception occurs

Testthrows4.java

import java.io.*;

class M{

void method()throws IOException{


throw new IOException("device error");

class Testthrows4{

public static void main(String args[])throws IOException{//declare exce


ption

M m=new M();

m.method();

System.out.println("normal flow...");

Output:

Can we rethrow an exception?

Yes, by throwing same exception in catch block.


Difference between throw and throws in Java

The throw and throws is the concept of exception handling where the throw
keyword throw the exception explicitly from a method or a block of code
whereas the throws keyword is used in signature of the method.

There are many differences between throw and throws keywords. A list of
differences between throw and throws are given below:
Java throw Example

TestThrow.java
public class TestThrow {

//defining a method

public static void checkNum(int num) {

if (num < 1) {

throw new ArithmeticException("\nNumber is negative,


cannot calculate square");

else {

System.out.println("Square of " + num + " is " +


(num*num));

//main method

public static void main(String[] args) {

TestThrow obj = new TestThrow();

obj.checkNum(-3);

System.out.println("Rest of the code..");

}
Difference between throw and throws in Java

TestThrows.java

public class TestThrows {

//defining a method

public static int divideNum(int m, int n) throws


ArithmeticException {

int div = m / n;

return div;

//main method

public static void main(String[] args) {

TestThrows obj = new TestThrows();

try {

System.out.println(obj.divideNum(45, 0));

catch (ArithmeticException e){

System.out.println("\nNumber cannot be divided by 0");

}
System.out.println("Rest of the code..");

Output:

Difference between final, finally and finalize

The final, finally, and finalize are keywords in Java that are used in exception
handling. Each of these keywords has a different functionality. The basic
difference between final, finally and finalize is that the final is an access
modifier, finally is the block in Exception Handling and finalize is the method
of object class.

Along with this, there are many differences between final, finally and finalize.
A list of differences between final, finally and finalize are given below:
Java final Example

Let's consider the following example where we declare final variable age. Once
declared it cannot be modified.

public class FinalExampleTest {

//declaring final variable

final int age = 18;

void display() {

// reassigning value to age variable

// gives compile time error

age = 55;
}

public static void main(String[] args) {

FinalExampleTest obj = new FinalExampleTest();

// gives compile time error

obj.display();

Output:

In the above example, we have declared a variable final. Similarly, we can


declare the methods and classes final using the final keyword.

Java finally Example

Let's see the below example where the Java code throws an exception and the
catch block handles that exception. Later the finally block is executed after the
try-catch block. Further, the rest of the code is also executed normally.

FinallyExample.java

public class FinallyExample {


public static void main(String args[]){

try {

System.out.println("Inside try block");

// below code throws divide by zero exception

int data=25/0;

System.out.println(data); }

// handles the Arithmetic Exception / Divide by zero exception

catch (ArithmeticException e){

System.out.println("Exception handled");

System.out.println(e);

// executes regardless of exception occurred or not

finally {

System.out.println("finally block is always executed");

System.out.println("rest of the code...");

}
Output:

Java finalize Example

FinalizeExample.java

public class FinalizeExample {

public static void main(String[] args)

FinalizeExample obj = new FinalizeExample();

// printing the hashcode

System.out.println("Hashcode is: " + obj.hashCode());

obj = null;

// calling the garbage collector using gc()

System.gc();

System.out.println("End of the garbage collection");

// defining the finalize method

protected void finalize()


{

System.out.println("Called the finalize() method");

Exception Handling with Method Overriding in Java

There are many rules if we talk about method overriding with exception
handling.

Some of the rules are listed below:

1. If the superclass method does not declare an exception


1. If the superclass method does not declare an exception, subclass
overridden method cannot declare the checked exception but it can
declare unchecked exception.
2. If the superclass method declares an exception
1. If the superclass method declares an exception, subclass overridden
method can declare same, subclass exception or no exception but
cannot declare parent exception.

If the superclass method does not declare an exception


Rule 1: If the superclass method does not declare an exception, subclass
overridden method cannot declare the checked exception.

Let's consider following example based on the above rule.

import java.io.*;
class Parent{

// defining the method

void msg() {

System.out.println("parent method");

public class TestExceptionChild extends Parent{

// overriding the method in child class

// gives compile time error

void msg() throws IOException {

System.out.println("TestExceptionChild");

public static void main(String args[]) {

Parent p = new TestExceptionChild();

p.msg();
}

Output:

Exception Handling with Method Overriding in Java

Rule 2: If the superclass method does not declare an exception, subclass


overridden method cannot declare the checked exception but can declare
unchecked exception.

TestExceptionChild1.java

import java.io.*;

class Parent{

void msg() {

System.out.println("parent method");

}
class TestExceptionChild1 extends Parent{

void msg()throws ArithmeticException {

System.out.println("child method");

public static void main(String args[]) {

Parent p = new TestExceptionChild1();

p.msg();

Exception Handling with Method Overriding in Java

If the superclass method declares an exception

Rule 1: If the superclass method declares an exception, subclass overridden


method can declare the same subclass exception or no exception but cannot
declare parent exception.

Example in case subclass overridden method declares parent exception

import java.io.*;

class Parent{
void msg()throws ArithmeticException {

System.out.println("parent method");

public class TestExceptionChild2 extends Parent{

void msg()throws Exception {

System.out.println("child method");

public static void main(String args[]) {

Parent p = new TestExceptionChild2();

try {

p.msg();

catch (Exception e){}

}
}

Java Custom Exception

 In Java, we can create our own exceptions that are derived classes of the
Exception class.
 Creating our own Exception is known as custom exception or user-
defined exception.
 Basically, Java custom exceptions are used to customize the exception
according to user need.
 Using the custom exception, we can have your own exception and
message. Here, we have passed a string to the constructor of superclass
i.e. Exception class that can be obtained using getMessage() method on
the object we have created.

Why use custom exceptions?

Java exceptions cover almost all the general type of exceptions that may occur
in the programming. However, we sometimes need to create custom exceptions.

Following are few of the reasons to use custom exceptions:

 To catch and provide specific treatment to a subset of existing Java


exceptions.
 Business logic exceptions: These are the exceptions related to business
logic and workflow. It is useful for the application users or the developers
to understand the exact problem.
 In order to create custom exception, we need to extend Exception class
that belongs to java.lang package.

Consider the following example, where we create a custom exception named


WrongFileNameException:

public class WrongFileNameException extends Exception {

public WrongFileNameException(String errorMessage) {

super(errorMessage);

Note: We need to write the constructor that takes the String as the error message
and it is called parent class constructor.

Example 1:

Let's see a simple example of Java custom exception. In the following code,
constructor of InvalidAgeException takes a string as an argument. This string is
passed to constructor of parent class Exception using the super() method. Also
the constructor of Exception class can be called without using a parameter and
calling super() method is not mandatory.
TestCustomException1.java

// class representing custom exception

class InvalidAgeException extends Exception

public InvalidAgeException (String str)

// calling the constructor of parent Exception

super(str);

// class that uses custom exception InvalidAgeException

public class TestCustomException1

// method to check the age

static void validate (int age) throws InvalidAgeException{


if(age < 18){

// throw an object of user defined exception

throw new InvalidAgeException("age is not valid to vote");

else {

System.out.println("welcome to vote");

// main method

public static void main(String args[])

try

// calling the method

validate(13);

catch (InvalidAgeException ex)


{

System.out.println("Caught the exception");

// printing the message from InvalidAgeException object

System.out.println("Exception occured: " + ex);

System.out.println("rest of the code...");

Output:

Java Custom Exception

Example 2:

TestCustomException2.java

// class representing custom exception

class MyCustomException extends Exception


{

// class that uses custom exception MyCustomException

public class TestCustomException2

// main method

public static void main(String args[])

try

// throw an object of user defined exception

throw new MyCustomException();

catch (MyCustomException ex)

System.out.println("Caught the exception");

System.out.println(ex.getMessage());
}

System.out.println("rest of the code...");

Output:

Java Custom Exception


Chapter 7:Reflections in java

 Java programming language provides a feature called “Reflection” that


allows us to modify the runtime behavior of a class or field or method at
runtime.
 Thus a Reflection can be defined as a “technique of inspecting and
modifying the runtime behavior of an unknown object at run time.
An object can be a class, a field, or a method.”
 Reflection is an “Application Programming Interface” (API) provided by
Java.
 The “Reflection” process is depicted below.

 In the above representation, we can see that we have an unknown object.


Then we use the Reflection API on this object. As a result, we can modify
the behaviour of this object at runtime.
 Thus we can use Reflection API in our programs for the purpose of
modifying the object’s behaviour. The objects can be anything like
methods, interfaces, classes, etc. We inspect these objects and then
change their behaviour at runtime using reflection API.
 In Java, the “java.lang” and “java.lang.reflect” are the two packages that
provide classes for reflection. The special class “java.lang.Class”
provides the methods and properties to extract metadata using which we
can inspect and modify the class behavior.
 We use Reflection API provided by the above packages to modify the
class and its members including fields, methods, constructors, etc. at
runtime. A distinguishing feature of Reflection API is that we can also
manipulate the private data members or methods of the class.

The Reflection API is mainly used in:

1. Reflection is mainly used in debugging tools, JUnit, and frameworks to


inspect and change the behaviour at runtime.
2. IDE (Integrated Development Environment) E.g. Eclipse IDE, NetBeans,
etc.
3. Test Tools etc.
4. It is used, when your application has third-party libraries and when you
want to know about the classes and methods available.

Reflection API In Java

Using Reflection API, we can implement the reflection on the following


entities:

1. Field: The Field class has information that we use to declare a variable or
a field like a datatype (int, double, String, etc.), access modifier (private,
public, protected, etc.), name (identifier) and value.
2. Method: The Method class can help us to extract information like access
modifier of the method, method return type, method name, method
parameter types, and exception types raised by the method.
3. Constructor: Constructor class gives information about class constructor
that includes constructor access modifier, constructor name, and
parameter types.
4. Modifier: Modifier class gives us information about a specific access
modifier.

All the above classes are a part of java.lang.reflect package. Next, we will
discuss each of these classes and use programming examples to demonstrate the
reflection on these classes.

Let’s first start with the class java.lang.Class.


java.lang.Class Class

The java.lang.The class holds all the information and data about classes and
objects at runtime. This is the main class used for reflection.

The class java.lang.Class provides:

 Methods to retrieve class metadata at run time.


 Methods to inspect and modify the behavior of a class at run time.

Create java.lang.Class Objects

We can create objects of java.lang.Class using one of the following options.

#1) .class extension

The first option to create an object of Class is by using the .class extension.

For example, if Test is a class, then we can create a Class object as follows:

Class obj_test = Test.class;

Then we can use the obj_test to perform reflection as this object will have all
the information about the class Test.

#2) forName() method

forName () method takes the name of the class as an argument and returns the
Class object.

For example, the object of the Test class can be created as follows:

class obj_test = Class.forName (“Test”);

#3) getClas () method


getClass() method uses object of a class to get the java.lang.Class object.

For example, consider the following piece of code:

Test obj = new Test ();


Class obj_test = obj.getClass ();

In the first line, we created an object of Test class. Then using this object we
called the “getClass ()” method to get an object obj_test of java.lang.Class.

Get Super Class & Access Modifiers

java.lang.class provides a method “getSuperClass()” that is used to get the


superclass of any class.

Similarly, it provides a method getModifier() that returns the access modifier of


the class.

import java.lang.Class;

import java.lang.reflect.*;

//define Person interface

interface Person {

public void display();

//declare class Student that implements Person

class Student implements Person {


//define interface method display

public void display() {

System.out.println("I am a Student");

class Main {

public static void main(String[] args) {

try {

// create an object of Student class

Student s1 = new Student();

// get Class object using getClass()

Class obj = s1.getClass();

// get the superclass of Student

Class superClass = obj.getSuperclass();

System.out.println("Superclass of Student Class: " +


superClass.getName());
}

catch(Exception e) {

e.printStackTrace();

Output:

In the above programming example, an interface Person is defined with a lone


method ‘display ()’. Then we define a Student class implementing the person
interface. In the main method, we use the getClass () method to retrieve the
Class object and then access the parent or superclass of Student object using the
getSuperClass () method.

Get Interfaces

If the class implements some interfaces, then we can get these interfaces names
using the getInterfaces() method of the java.lang.Class. For this, we have to
perform a reflection on the Java class.

The below programming example depicts the use of the getInterfaces () method
in Java Reflection.

import java.lang.Class;
import java.lang.reflect.*;

//define Interface Animals and PetAnimals


interface Animals {
public void display();
}

interface PetAnimals {
public void makeSound();
}

//define a class Dog that implements above interfaces


class Dog implements Animals, PetAnimals {
//define interface method display
public void display() {
System.out.println("This is a PetAnimal::Dog");
}

//define interface method makeSound


public void makeSound() {
System.out.println("Dog makes sound::Bark bark");
}
}
class Main {
public static void main(String[] args) {
try {
// create an object of Dog class
Dog dog = new Dog();
// get class object
Class obj = dog.getClass();
// get the interfaces implemented by Dog
Class[] objInterface = obj.getInterfaces();
System.out.println("Class Dog implements following interfaces:");
//print all the interfaces implemented by class Dog
for(Class citem : objInterface) {
System.out.println("Interface Name: " + citem.getName());
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}

Output

Output

In the above program, we have defined two interfaces i.e. Animals and
PetAnimals. Then we define a class Dog, that implements both these interfaces.

In the main method, we retrieve the object of class Dog in java.lang.Class to


perform reflection. Then we use the getInterfaces () method to retrieve the
interfaces that are implemented by the class Dog.
Reflection: Get Field Value

As already mentioned the package java.lang.reflect provides the Field class that
helps us to reflect the field or data members of the class.

Enlisted below are the methods provided by the Field class for Reflection of
a field.

Method Description

Returns all the public fields (both for class &


getFields()
superclass).

getDeclaredFields() Retrieves all the fields of the class.

Returns integer representation of access


getModifier()
modifier of the field.

set(classObject, value) Assigns the specified value to the field.

get(classObject) Retrieves field value.

setAccessible(boolean) Make private field accessible by passing true.

Returns the field (public) with a specified field


getField("fieldName")
name.

getDeclaredField("fieldName") Returns the field with a specified name.

Given below are two reflection examples that demonstrate the reflection on the
public and private field.

The Java program below demonstrates the reflection on a public field.

import java.lang.Class;
import java.lang.reflect.*;

class Student {

public String StudentName;

class Main {

public static void main(String[] args) {

try{

Student student = new Student();

// get an object of the class Class

Class obj = student.getClass();

// provide field name and get the field info

Field student_field = obj.getField("StudentName");

System.out.println("Details of StudentName class field:");

// set the value of field

student_field.set(student, "Lacey");

// get the access modifier of StudentName

int mod1 = student_field.getModifiers();


String modifier1 = Modifier.toString(mod1);

System.out.println("StudentName Modifier::" + modifier1);

// get the value of field by converting in String

String typeValue = (String)student_field.get(student);

System.out.println("StudentName Value::" + typeValue);

catch(Exception e) {

e.printStackTrace();

Output

In this program, we have declared a class “Student” having a public field


StudentName. Then using the API interface of the Field class, we perform
reflection on the field StudentName and retrieve its access modifier and value.

The next program performs reflection on a private field of the class. The
operations are similar except that there is one extra function call made for the
private field. We have to call setAccessible (true) for the private field. Then we
perform reflection on this field in a similar manner as the public field.

import java.lang.Class;
import java.lang.reflect.*;
class Student {
private String rollNo;
}

class Main {
public static void main(String[] args) {
try {
Student student = new Student();
// get the object for class Student in a Class.
Class obj = student.getClass(); // access the private field
Field field2 = obj.getDeclaredField("rollNo");
// make the private field accessible
field2.setAccessible(true);
// set the value of rollNo
field2.set(student, "27");
System.out.println("Field Information of rollNo:");
// get the access modifier of rollNo
int mod2 = field2.getModifiers();
String modifier2 = Modifier.toString(mod2);
System.out.println("rollNo modifier::" + modifier2);
// get the value of rollNo converting in String
String rollNoValue = (String)field2.get(student);
System.out.println("rollNo Value::" + rollNoValue);
} catch(Exception e) {
e.printStackTrace();
}
}
}

Output

Reflection: Method

Similar to the fields of the class, we can also perform reflection on class
methods and modify their behavior at run time. For this, we use the Method
class of java.lang.reflect package.

Enlisted below are the functions provided by the Method class for
Reflection of the class method.

Method Description

Retrieves all public methods defined in the class and its


getMethods()
superclass.

getDeclaredMethod() Returns methods declared in the class.

getName() Returns the method names.

getModifiers() Returns integer representation of method’s access


Method Description

modifier.

getReturnType() Returns the method return type.

Reflection: Constructor

We can use the “Constructor” class of java.lang.reflect package to inspect and


modify the constructors of a Java class.

The constructor class provides the following methods for this purpose.

Method Description

Returns all the constructors declared in class and its


getConstructors()
superclass.

getDeclaredConstructor() Returns all the declared constructors.

getName() Retrieves the name of the constructor.

Returns the integer representation of access modifier


getModifiers()
of constructors.

Returns the total number of parameters for a


getParameterCount()
constructors.

The reflection example below demonstrates the reflection of constructors of a


class in Java. Like method reflection, here also getDeclaredConstructors method
returns an array of constructors for a class. Then we traverse through this
constructor array to display information about each constructor.
Drawbacks Of Reflection

Reflection is powerful, but should not be used indiscriminately. If it is possible


to operate without using reflection, then it is preferable to avoid using it.

Enlisted below are few drawbacks of Reflection:

 Performance Overhead: Though reflection is a powerful feature,


reflective operations still have slower performance than non- reflective
operations. Hence we should avoid using reflections in performance-
critical applications.

1. Security Restrictions: As reflection is a runtime feature, it might require


run-time permissions. So for the applications that require the code to be
executed in a restricted security setting, then reflection may be of no use.

1. Exposure of Internals: By using reflection, we can access private fields


and methods in a class. Thus reflection breaks abstraction that might
render code unportable and dysfunctional.

Frequently Asked Questions

Q #1) Why is Reflection used in Java?

Answer: Using reflection we can inspect classes, interfaces, constructors,


fields, and methods at runtime, even if they are anonymous at compile time.
This inspection allows us to modify the behavior of these entities at runtime.

Q #2) Where is Reflection used?


Answer: Reflection is used in writing frameworks that interoperate with user-
defined classes, wherein the programmer doesn’t even know what the classes or
other entities will be.

Q #3) Is Java Reflection slow?

Answer: Yes, it is slower than the non-reflection code.

Q #4) Is Java Reflection bad?

Answer: In a way, yes. First of all, we lose compile-time safety. Without


compile-time safety, we might get run time errors that may affect end users. It
will also be difficult to debug the error.

Q #5) How do you stop a Reflection in Java?

Answer: We simply avoid using reflection by writing non-reflection operations.


Or maybe we can use some generic mechanisms like a custom validation with
reflection.

More About Java Reflection

java.lang.reflect package has the classes and interfaces to do reflection. And the
java.lang.class can be used as an entry point for the reflection.

How to get the class objects:

1. If you have instance of an object,

class c=obj.getclass();

2. If you know the type of the class,


class c =type.getClass();

3. If you know the class name,

Class c = Class.forName(“com.demo.Mydemoclass”);

How to get the class members:


Class members are fields (class variables) and methods.

1. getFields() – Used to get all the fields except the private fields.
2. getDeclaredField() – Used to get the private fields.
3. getDeclaredFields() – Used to get the private and public fields.
4. getMethods()– Used to get all the methods except the private methods.
5. getDeclaredMethods() –Used to get the public and private methods.

Demo Programs:

ReflectionHelper.java:

This is the class where we are going to inspect using the reflection API.

class ReflectionHelper {

private int age;

private String name;

public String deptName;

public int empID;

public int getAge() {


return age;

public void setAge(int age)

this.age = age;

public String getName()

return name;

public void setName(String name) {

this.name = name;

public String getDeptName() {

return deptName;

public void setDeptName(String deptName)


{

this.deptName = deptName;

}
Reflection: Method

Similar to the fields of the class, we can also perform reflection on class
methods and modify their behavior at run time. For this, we use the Method
class of java.lang.reflect package.

Enlisted below are the functions provided by the Method class for
Reflection of the class method.

Method Description

Retrieves all public methods defined in the class and its


getMethods()
superclass.

getDeclaredMethod() Returns methods declared in the class.

getName() Returns the method names.

Returns integer representation of method’s access


getModifiers()
modifier.

getReturnType() Returns the method return type.

Reflection: Constructor

We can use the “Constructor” class of java.lang.reflect package to inspect and


modify the constructors of a Java class.

The constructor class provides the following methods for this purpose.

Method Description

getConstructors() Returns all the constructors declared in class and its


Method Description

superclass.

getDeclaredConstructor() Returns all the declared constructors.

getName() Retrieves the name of the constructor.

Returns the integer representation of access modifier


getModifiers()
of constructors.

Returns the total number of parameters for a


getParameterCount()
constructors.

The reflection example below demonstrates the reflection of constructors of a


class in Java. Like method reflection, here also getDeclaredConstructors method
returns an array of constructors for a class. Then we traverse through this
constructor array to display information about each constructor.

import java.lang.Class

import java.lang.reflect.*//declare a class Person with three constructors

class Person {

public Person() { } //constructor with no parameters

public Person(String name) { } //constructor with 1 parameter

private Person(String name, int age) {} //constructor with 2 parameters

}class Main {

public static void main(String[] args) {

try {

Person person = new Person();


Class obj = person.getClass();

// get array of constructors in a class using getDeclaredConstructor()

Constructor[] constructors = obj.getDeclaredConstructors();

System.out.println("Constructors for Person Class:");

for(Constructor c : constructors) {

// get names of constructors

System.out.println("Constructor Name: " + c.getName());

// get access modifier of constructors

int modifier = c.getModifiers();

System.out.print ("Modifier: " + Modifier.toString(modifier) + " ");

// get the number of parameters in constructors

System.out.println("Parameters: " + c.getParameterCount());

//if there are parameters, get parameter type of each parameter

if(c.getParameterCount() &gt; 0){

Class[] paramList=c.getParameterTypes();
System.out.print ("Constructor parameter types :");

for (Class class1 : paramList) {

System.out.print(class1.getName() +" ");

System.out.println("\n");

catch(Exception e) {

e.printStackTrace();

Output
Drawbacks Of Reflection

Reflection is powerful, but should not be used indiscriminately. If it is possible


to operate without using reflection, then it is preferable to avoid using it.

Enlisted below are few drawbacks of Reflection:

1. Performance Overhead: Though reflection is a powerful feature,


reflective operations still have slower performance than non- reflective
operations. Hence we should avoid using reflections in performance-
critical applications.

1. Security Restrictions: As reflection is a runtime feature, it might require


run-time permissions. So for the applications that require the code to be
executed in a restricted security setting, then reflection may be of no use.
1. Exposure of Internals: By using reflection, we can access private fields
and methods in a class. Thus reflection breaks abstraction that might
render code unportable and dysfunctional

Chapter 8: Advanced I/O Streams: File, Byte


Streams, Character Streams, Random Access File

Java I/O (Input/Output) streams are a fundamental part of the Java


programming language, used for reading from and writing to data sources such
as files, network connections, and other I/O devices. The Java I/O API is
organized around two main types of streams: byte streams and character
streams.

Java files

Java has several methods for creating, reading, updating, and deleting files.

Java File Handling


 The File class from the java.io package, allows us to work with files.
 To use the File class, create an object of the class, and specify the
filename or directory name:

import java.io.File; // Import the File class

File myObj = new File("filename.txt"); // Specify the filename

 The File class has many useful methods for creating and getting
information about files. For example:

Create a File

To create a file in Java, you can use the createNewFile() method. This method returns a
boolean value: true if the file was successfully created, and false if the file already exists.
Note that the method is enclosed in a try...catch block. This is necessary because it throws
an IOException if an error occurs (if the file cannot be created for some reason):

import java.io.File; // Import the File class


import java.io.IOException; // Import the IOException class to handle
errors

public class CreateFile {


public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}

The output will be:

File created: filename.txt

To create a file in a specific directory (requires permission), specify the path of the file and
use double backslashes to escape the "\" character (for Windows). On Mac and Linux you
can just write the path, like: /Users/name/filename.txt

Example
File myObj = new File("C:\\Users\\MyName\\filename.txt");
Write To a File

In the following example, we use the FileWriter class together with its write()
method to write some text to the file we created in the example above. Note that
when you are done writing to the file, you should close it with the close()
method:

Example

import java.io.FileWriter; // Import the FileWriter class


import java.io.IOException; // Import the IOException class to handle
errors

public class WriteToFile {


public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Files in Java might be tricky, but it is fun enough!");
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
The output will be:
Successfully wrote to the file.

Read a File

In the previous chapter, you learned how to create and write to a file.

In the following example, we use the Scanner class to read the contents of the text file we
created in the previous chapter:

ExampleGet your own Java Server


import java.io.File; // Import the File class
import java.io.FileNotFoundException; // Import this class to handle
errors
import java.util.Scanner; // Import the Scanner class to read text files

public class ReadFile {


public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}

The output will be:


Files in Java might be tricky, but it is fun enough!

Get File Information

To get more information about a file, use any of the File methods:

Example

import java.io.File; // Import the File class

public class GetFileInfo {

public static void main(String[] args) {


File myObj = new File("filename.txt");
if (myObj.exists()) {
System.out.println("File name: " + myObj.getName());
System.out.println("Absolute path: " + myObj.getAbsolutePath());
System.out.println("Writeable: " + myObj.canWrite());
System.out.println("Readable " + myObj.canRead());
System.out.println("File size in bytes " + myObj.length());
} else {
System.out.println("The file does not exist.");
}
}
}

The output will be:


File name: filename.txt
Absolute path: C:\Users\MyName\filename.txt
Writeable: true
Readable: true
File size in bytes: 0

Delete a File

To delete a file in Java, use the delete() method:

Example
import java.io.File; // Import the File class

public class DeleteFile {


public static void main(String[] args) {
File myObj = new File("filename.txt");
if (myObj.delete()) {
System.out.println("Deleted the file: " + myObj.getName());
} else {
System.out.println("Failed to delete the file.");
}
}
}

The output will be:

Deleted the file: filename.txt

Delete a Folder
You can also delete a folder. However, it must be empty:

Example:

import java.io.File;

public class DeleteFolder {

public static void main(String[] args) {


File myObj = new File("C:\\Users\\MyName\\Test");

if (myObj.delete()) {

System.out.println("Deleted the folder: " + myObj.getName());

} else {

System.out.println("Failed to delete the folder.");

The output will be:

Deleted the folder: Test

Byte Streams in java

Programs use byte streams to perform input and output of 8-bit bytes. All byte stream classes
are descended from InputStream and OutputStream.

Byte streams should only be used for the most primitive I/O. It represents a kind of low-level
I/O so you should avoid in case complicated data types like text or graphics.

A ByteArrayInputStream class provides an internal buffer for the bytes read from input
stream.

Commonly used constructors of ByteArrayInputStream:

1. ByteArrayInputStream(byte[] buf):Creates a ByteArrayInputStream so that it uses buf as


its buffer array.

2. ByteArrayInputStream(byte[] buf, int offset, int length): Creates ByteArrayInputStream


that uses buf as its buffer array.
Commonly used methods of ByteArrayInputStream:

1. public int read() This method reads the next byte of data from the InputStream. Returns an
int as the next byte of data. If it is end of file then it returns -1.

Example:

import java.io.ByteArrayInputStream;

/**

* This program is used to read byte array

* input using ByteArrayInputStream.

* @author w3spoint

*/

class IOTest{

String str = "www.w3spoint.com";

public void readFile(){

try {

//Converting string into byte array.

byte b[] = str.getBytes();

//Creating ByteArrayInputStream object.

ByteArrayInputStream bais =
new ByteArrayInputStream(b);

int i;

//read file.

while((i=bais.read())!=-1){

System.out.print((char)i);

} catch (Exception e) {

e.printStackTrace();

public class ByteArrayInputStreamExample {

public static void main(String args[]){

//creating IOTest object.

IOTest obj = new IOTest();

//method call.

obj.readFile();

}
}

ByteArrayOutputStream:

ByteArrayOutputStream class uses byte array to write data. The buffer automatically grows
as data is written to it.

Commonly used to constructors of ByteArrayOutputStream:

1. ByteArrayOutputStream ()

Creates a new byte array output stream.

2. ByteArrayOutputStream (int size)

Creates a new byte array output stream, with a buffer capacity of the specified size, in bytes.

Commonly used methods of ByteArrayOutputStream:

1. public void writeTo(OutputStream outSt) Writes the entire content of this Stream to the
specified stream argument.

Example:

import java.io.ByteArrayOutputStream;

import java.io.FileOutputStream;
/**

* This program is used to write data into

* a file using ByteArrayOutputStream.

* @author w3spoint

*/

class IOTest{

String str = "Hello www.w3spoint.com";

public void writeFile(){

try {

//Creating FileOutputStream object.

//It will create a new file before writing if not exist.

FileOutputStream fos =

new FileOutputStream("F:\\New folder\\data5.txt");

//Creating ByteArrayOutputStream object.

ByteArrayOutputStream baos=new ByteArrayOutputStream();

baos.write(str.getBytes());

baos.writeTo(fos);
baos.flush();

//Close file after write operation.

baos.close();

System.out.println("Contents written successfully.");

} catch (Exception e) {

e.printStackTrace();

public class ByteArrayOutputStreamExample {

public static void main(String args[]){

//Creating IOTest object.

IOTest obj = new IOTest();

//method call

obj.writeFile();

}
Character stream

A character stream is a sequence of characters used to handle input and output


operations in various programming environments. It is primarily used for
reading and writing text data. Character streams are particularly important in
high-level programming languages such as Java, Python, and C++ where text
handling is a common requirement. Here's a deeper look into how character
streams function and their applications:

Key Concepts

 Character Encoding:
o Character streams often rely on specific encoding standards like UTF-8,
UTF-16, or ASCII to interpret bytes as characters.
o The encoding determines how character data is represented and how
many bytes are used for each character.

 Input Streams:
o An input character stream reads data from a source, such as a file,
network socket, or console input.
o In Java, examples include FileReader, BufferedReader, and
InputStreamReader.

 Output Streams:
o An output character stream writes data to a destination, such as a file or a
network socket.
o In Java, examples include FileWriter, BufferedWriter, and PrintWriter.
 Buffered Streams:
o Buffered streams improve performance by reducing the number of read
and write operations by temporarily storing data in a buffer.
o Examples in Java are BufferedReader and BufferedWriter.

Usage in Programming

Java Example

In Java, character streams are part of the java.io package:


import java.io.*;

public class CharacterStreamExample {


public static void main(String[] args) {
// Writing to a file using FileWriter and BufferedWriter
try (FileWriter writer = new FileWriter("output.txt");
BufferedWriter bufferedWriter = new BufferedWriter(writer)) {
bufferedWriter.write("Hello, World!");
} catch (IOException e) {
e.printStackTrace();
}

// Reading from a file using FileReader and BufferedReader


try (FileReader reader = new FileReader("output.txt");
BufferedReader bufferedReader = new BufferedReader(reader)) {
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Applications

 File I/O: Reading from and writing to text files.


 Network Communication: Sending and receiving text-based data
over a network.
 User Input: Handling input from users in console applications.
 Data Processing: Parsing and generating text data such as logs,
configuration files, and reports.

Advantages of Character Streams

 Platform Independence: By abstracting character encoding,


character streams allow for consistent handling of text data across
different platforms and locales.
 Ease of Use: Higher-level abstraction makes it easier to work with
text data compared to byte streams.

Random Access File
In Java, the RandomAccessFile class allows you to read from and
write to a file at any location. Unlike sequential file processing, where
you read or write data sequentially, RandomAccessFile supports non-
sequential, random access to a file's contents.
This is particularly useful for applications that require frequent
read/write operations at arbitrary positions within a file, such as databases
and file systems.

Key Features of RandomAccessFile

 Random Access: You can move to any position within the file to
read or write data.
 Read and Write Modes: Supports both read-only and read-write
modes.
 File Pointer: Maintains a file pointer that can be moved to any
location within the file.

Creating a RandomAccessFile

To create a RandomAccessFile, you need to specify the file name and the
mode. The mode can be "r" for read-only or "rw" for read and write.

RandomAccessFile file = new RandomAccessFile("example.txt", "rw");

Common Methods

 seek(long pos): Moves the file pointer to the specified position.


 read(): Reads a byte of data from the file.
 read(byte[] b): Reads bytes from the file into a byte array.
 write(int b): Writes a byte of data to the file.
 write(byte[] b): Writes bytes from a byte array to the file.
 getFilePointer(): Returns the current position of the file pointer.
 length(): Returns the length of the file.

Example Usage

Below is an example demonstrating how to use RandomAccessFile to


write data to specific positions and read data from those positions:
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessFileExample {


public static void main(String[] args) {
try (RandomAccessFile raf = new
RandomAccessFile("example.txt", "rw")) {
// Writing data to the file
raf.writeUTF("Hello, RandomAccessFile!");
raf.writeInt(12345);
raf.writeDouble(3.14159);

// Move the file pointer to the beginning


raf.seek(0);

// Reading data from the file


String str = raf.readUTF();
int intValue = raf.readInt();
double doubleValue = raf.readDouble();

System.out.println("String read: " + str);


System.out.println("Integer read: " + intValue);
System.out.println("Double read: " + doubleValue);

// Move the file pointer to a specific position to read the integer


value
raf.seek(raf.getFilePointer() - 12); // Move back to the position
before the int value
intValue = raf.readInt();
System.out.println("Integer read at specific position: " +
intValue);

} catch (IOException e) {
e.printStackTrace();
}
}
}

Explanation of the Example

 Creating RandomAccessFile: The file is opened in read-write mode


("rw").
 Writing Data:
writeUTF(String s): Writes a string in UTF-8 format.
writeInt(int v): Writes an integer.
writeDouble(double v): Writes a double.
Setting File Pointer:
 seek(long pos): Moves the file pointer to the beginning of the file.
 Reading Data:
 readUTF(): Reads a string in UTF-8 format.
 readInt(): Reads an integer.
 readDouble(): Reads a double.
 Moving File Pointer to Specific Position:
 seek(long pos): Moves the file pointer to a position before the
integer value, allowing it to be read again.

RandomAccessFile is useful in scenarios such as:

 Implementing file-based databases.


 Creating custom file formats where random access is necessary.
 Editing specific parts of a large file without loading it entirely into
memory.
 By using RandomAccessFile, you gain flexibility in file handling,
allowing efficient read and write operations at any location within
the file.
Serialization and Deserialization in java

In java serialization is way used to convert an object into a byte stream


which can be transported to any other running JVM through a network or can be
persisted into disk and that object can be rebuilt again. Java provides
serialization API for this.

How to make a class serializable in java?

To make a java class Serializable implements java.io.Serializable interface.


JVM will take care of serializing objects.

What is Serializable interface?

Serializable interface is a marker interface. A marker interface doesn’t


have any method i.e. Serializable interface doesn’t have any method, it
gives indication to compiler that use Java Serialization mechanism to
serialize this object.
Example:

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectOutputStream;

import java.io.Serializable;

/**

* This program is used to show the serialization process.

* @author w3spoint

*/

class Student implements Serializable{

//Serial Version UID.

private static final long serialVersionUID = 1L;

String name;

String className;

String rollNo;

//Constructor.
Student(String name, String className, String rollNo){

this.name = name;

this.className = className;

this.rollNo = rollNo;

class Test{

//Write serialized object into objectoutputstream.

public void objectSerialization(Student stu){

try

//Creating FileOutputStream object.

FileOutputStream fos =

new FileOutputStream("F:\\New folder\\student.ser");

//Creating ObjectOutputStream object.

ObjectOutputStream oos = new ObjectOutputStream(fos);


//write object.

oos.writeObject(stu);

//close streams.

oos.close();

fos.close();

System.out.println("Serialized data is saved in " +

"F:\\New folder\\student.ser");

}catch(IOException e)

System.out.println(e);

public class SerializationExample {


public static void main(String args[]){

//Creating Student object.

Student stu =

new Student("Parmander", "MCA", "MCA/07/27");

//Creating Test object.

Test obj = new Test();

//Method call.

obj.objectSerialization(stu);

Output:

Serialized data is saved in F:\New folder\student.ser

Deserialization:

Deserialization is the reverse process of serialization. It is the process of rebuilding object


from serialized state.

Example:

DeSerializationExample.java
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.Serializable;

/**
* This program is used to show the deserialization process.
* @author w3spoint
*/
class Student implements Serializable{
//Serial Version UID.
private static final long serialVersionUID = 1L;
String name;
String className;
String rollNo;

//Constructor.
Student(String name, String className, String rollNo){
this.name = name;
this.className = className;
this.rollNo = rollNo;
}
}

class Test{
//Deserialize a serialize object.
public void objectDeSerialization(){
try
{
Student stu = null;
//Creating FileOutputStream object.
FileInputStream fis =
new FileInputStream("F:\\New folder\\student.ser");

//Creating ObjectOutputStream object.


ObjectInputStream ois = new ObjectInputStream(fis);

//write object.
stu = (Student) ois.readObject();

//close streams.
ois.close();
fis.close();

System.out.println("Name = " + stu.name);


System.out.println("Class Name = " + stu.className);
System.out.println("RollNo = " + stu.rollNo);
}catch(Exception e)
{
System.out.println(e);
}
}
}

public class DeSerializationExample {


public static void main(String args[]){
//Creating Test object.
Test obj = new Test();
//Method call.
obj.objectDeSerialization();
}
}

Output:

Name = Parmander
Class Name = MCA
RollNo = MCA/07/27

What is the difference between Serializable and


Externalizable interface in Java?

Serializable Externalizable
1. Serializable interface is a marker 1. Externalizable interface is not a
interface. marker interface.
2. Serializable interface write state of 2. Externalizable interface writes state
an object in non-compress format. of an object in compress format.
Chapter 9: JDBC: Advantages, Database Connectivity
Using SQL Server, Types of Drivers, Statements,
Prepared Remote Interfaces

What is JDBC?

JDBC refers to the Java Database Connectivity. It provides java API that
allows Java programs to access database management systems (relational
database). The JDBC API consists of a set of interfaces and classes which
enables java programs to execute SQL statements. Interfaces and classes in
JDBC API are written in java.

JDBC core components:

The JDBC API consists of the following core components:

1. JDBC Drivers: JDBC driver is a collection of classes which implements


interfaces defined in the JDBC API for opening database connections,
interacting with database and closing database connections.
2. Connections: Before performing any database operation via JDBC, we have
to open a database connection. To open a database connection we can call
getConnection() method of DriverManager class. Syntax:

Connection connection = DriverManager.getConnection(url, user, password)

3. Statements:

The JDBC statements are used to execute the SQL or PL/SQL queries against
the database. We need a statement for every single query. JDBC API defines the
Statement, CallableStatement, and PreparedStatement types of statements.

4. ResultSets: A query returns the data in the form of ResultSet. To read the
query result date ResultSet provides a cursor that points to the current row in the
result set.

JDBC Driver
JDBC Driver is a software component that enables java application to interact with the database.
There are 4 types of JDBC drivers:

1. JDBC-ODBC bridge driver


2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)

1) JDBC-ODBC bridge driver


The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge
driver converts JDBC method calls into the ODBC function calls. This is now discouraged because of
thin driver.
In Java 8, the JDBC-ODBC Bridge has been removed.

Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you
use JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC
Bridge.

Advantages:

o easy to use.
o can be easily connected to any database.

Disadvantages:

o Performance degraded because JDBC method call is converted into the


ODBC function calls.
o The ODBC driver needs to be installed on the client machine.

2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts JDBC method
calls into native calls of the database API. It is not written entirely in java.
Advantage: performance upgraded than JDBC-ODBC bridge driver.

Disadvantage: The Native driver needs to be installed on the each client


machine. The Vendor client library needs to be installed on client machine.

3) Network Protocol driver

The Network Protocol driver uses middleware (application server) that converts
JDBC calls directly or indirectly into the vendor-specific database protocol. It is
fully written in java.

Advantage: No client side library is required because of application server that


can perform many tasks like auditing, load balancing, logging etc.

Disadvantages: Network support is required on client machine.


Requires database-specific coding to be done in the middle tier.

Maintenance of Network Protocol driver becomes costly because it requires


database-specific coding to be done in the middle tier.

4) Thin driver

The thin driver converts JDBC calls directly into the vendor-specific database
protocol. That is why it is known as thin driver. It is fully written in Java
language.

Advantages

o Better performance than all other drivers.


o No software is required at client side or server side.

Disadvantage:

o Drivers depend on the Database.

Why Should We Use JDBC

Before JDBC, ODBC API was the database API to connect and execute the
query with the database. But, ODBC API uses ODBC driver which is written in
C language (i.e. platform dependent and unsecured). That is why Java has
defined its own API (JDBC API) that uses JDBC drivers (written in Java
language).

We can use JDBC API to handle database using Java program and can perform
the following activities:
 Connect to the database
 Execute queries and update statements to the database
 Retrieve the result received from the database.

Java Database Connectivity with MySQL

To connect Java application with the MySQL database, we need to follow 5 following steps.

In this example we are using MySql as the database. So we need to know following
informations for the mysql database:

o Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
o Connection URL: The connection URL for the mysql database is
jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database, localhost is
the server name on which mysql is running, we may also use IP address, 3306 is the port
number and sonoo is the database name. We may use any database, in such case, we need
to replace the sonoo with our database name.
o Username: The default username for the mysql database is root.
o Password: It is the password given by the user at the time of installing the mysql database. In
this example, we are going to use root as the password.

Let's first create a table in the mysql database, but before creating table, we need to create
database first.

1. create database sonoo;


2. use sonoo;

3. create table emp(id int(10),name varchar(40),age int(3));

Example to Connect Java Application with mysql database

In this example, sonoo is the database name, root is the username and password both.
import java.sql.*;

class MysqlCon{

public static void main(String args[]){

try{

Class.forName("com.mysql.jdbc.Driver");

Connection con=DriverManager.getConnection(

"jdbc:mysql://localhost:3306/sonoo","root","root");

//here sonoo is database name, root is username and password

Statement stmt=con.createStatement();

ResultSet rs=stmt.executeQuery("select * from emp");

while(rs.next())

System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));

con.close();

}catch(Exception e){ System.out.println(e);}

To connect java application with the mysql database, mysqlconnector.jar file is


required to be loaded.

Two ways to load the jar file:

1) Paste the mysqlconnector.jar file in jre/lib/ext folder


2) Set classpath

1) Paste the mysqlconnector.jar file in JRE/lib/ext folder:

Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the jar
file here.

2) Set classpath:

There are two ways to set the classpath:

o temporary
o permanent

How to set the temporary classpath

open command prompt and write:

C:>set classpath=c:\folder\mysql-connector-java-5.0.8-bin.jar;.;

How to set the permanent classpath

Go to environment variable then click on new tab. In variable name write


classpath and in variable value paste the path to the mysqlconnector.jar file by
appending mysqlconnector.jar;.; as C:\folder\mysql-connector-java-5.0.8-
bin.jar;.;

PreparedStatement interface

The PreparedStatement interface is a subinterface of Statement. It is used to execute


parameterized query.
Let's see the example of parameterized query:

1. String sql="insert into emp values(?,?,?)";

As you can see, we are passing parameter (?) for the values. Its value will be set by calling
the setter methods of PreparedStatement.

Why use PreparedStatement?

Improves performance: The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once.

How to get the instance of PreparedStatement?

The prepareStatement() method of Connection interface is used to return the


object of PreparedStatement.

Syntax:

public PreparedStatement prepareStatement(String query)throws


SQLException{}

Methods of PreparedStatement interface

The important methods of PreparedStatement interface are given below:


Example of PreparedStatement interface that inserts the record

First of all create table as given below:

create table emp(id number(10),name varchar2(50));

Now insert records in this table by the code given below:

import java.sql.*;

class InsertPrepared{

public static void main(String args[]){

try{

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","syst
em","oracle");

PreparedStatement stmt=con.prepareStatement("insert into Emp


values(?,?)");

stmt.setInt(1,101);//1 specifies the first parameter in the query

stmt.setString(2,"Ratan");

int i=stmt.executeUpdate();

System.out.println(i+" records inserted");

con.close();

}catch(Exception e){ System.out.println(e);}

}
Example of PreparedStatement interface that updates the record

1. PreparedStatement stmt=con.prepareStatement("update emp set name=? where id=?")


;
2. stmt.setString(1,"Sonoo");//1 specifies the first parameter in the query i.e. name

3. stmt.setInt(2,101);
4.

5. int i=stmt.executeUpdate();
6. System.out.println(i+" records updated");
Chapter 10: Multithreading in Java

o Multithreading in Java is a process of executing multiple threads simultaneously.


o A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing
and multithreading, both are used to achieve multitasking.
o However, we use multithreading than multiprocessing because threads use a shared
memory area. They don't allocate separate memory area so saves memory, and
context-switching between the threads takes less time than process.
o Java Multithreading is mostly used in games, animation, etc.

Advantages of Java Multithreading

1) It doesn't block the user because threads are independent and you can
perform multiple operations at the same time.

2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn't affect other threads if an exception


occurs in a single thread.

Multitasking

Multitasking is a process of executing multiple tasks simultaneously. We use


multitasking to utilize the CPU. Multitasking can be achieved in two ways:

1) Process-based Multitasking (Multiprocessing)

o Each process has an address in memory. In other words, each process


allocates a separate memory area.
o A process is heavyweight.
o Cost of communication between the process is high.
o Switching from one process to another requires some time for saving and
loading registers, memory maps, updating lists, etc.
2) Thread-based Multitasking (Multithreading)

o Threads share the same address space.


o A thread is lightweight.
o Cost of communication between the thread is low.

What is Thread in java ?

A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of


execution.

Threads are independent. If there occurs exception in one thread, it doesn't affect other
threads. It uses a shared memory area.
As shown in the above figure, a thread is executed inside the process. There is
context-switching between the threads. There can be multiple processes inside
the OS, and one process can have multiple threads.

Java Thread class

Java provides Thread class to achieve thread programming. Thread class


provides constructors and methods to create and perform operations on a thread.
Thread class extends Object class and implements Runnable interface.
Chapter 11: Collection Framework: Collection,
Map, Date & Calendar, Enumeration, and Iterator.
The Collection in Java is a framework that provides an architecture to store and manipulate
the group of objects.

Java Collections can achieve all the operations that you perform on a data such as searching,
sorting, insertion, manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList,
PriorityQueue, HashSet, LinkedHashSet, TreeSet).

What is Collection in Java

A Collection represents a single unit of objects, i.e., a group.

What is a framework in Java

It provides readymade architecture.

It represents a set of classes and interfaces.


It is optional.

What is Collection framework

The Collection framework represents a unified architecture for storing and manipulating a
group of objects. It has:

1. Interfaces and its implementations, i.e., classes


2. Algorithm

Hierarchy of Collection Framework

Let us see the hierarchy of Collection framework. The java.util package


contains all the classes and interfaces for the Collection framework.

Methods of Collection interface

There are many methods declared in the Collection interface. They are as follows:
Iterator interface

Iterator interface provides the facility of iterating the elements in a forward


direction only.

Methods of Iterator interfaceThere are only three methods in the Iterator


interface. They are:

Iterable Interface
The Iterable interface is the root interface for all the collection classes. The Collection
interface extends the Iterable interface and therefore all the subclasses of Collection interface
also implement the Iterable interface.

It contains only one abstract method. i.e.,

1. Iterator<T> iterator()

It returns the iterator over the elements of type T

Collection Interface

The Collection interface is the interface which is implemented by all the classes in the
collection framework. It declares the methods that every collection will have. In other words,
we can say that the Collection interface builds the foundation on which the collection
framework depends.

Some of the methods of Collection interface are Boolean add ( Object obj), Boolean addAll
( Collection c), void clear(), etc. which are implemented by all the subclasses of Collection
interface.

List Interface

List interface is the child interface of Collection interface. It inhibits a list type data structure
in which we can store the ordered collection of objects. It can have duplicate values.

List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.

To instantiate the List interface, we must use :

1. List <data-type> list1= new ArrayList();


2. List <data-type> list2 = new LinkedList();
3. List <data-type> list3 = new Vector();
4. List <data-type> list4 = new Stack();

There are various methods in List interface that can be used to insert, delete, and access the
elements from the list.

ArrayList

The ArrayList class implements the List interface. It uses a dynamic array to store the
duplicate element of different data types. The ArrayList class maintains the insertion order
and is non-synchronized. The elements stored in the ArrayList class can be randomly
accessed. Consider the following example.

import java.util.*;

class TestJavaCollection1{

public static void main(String args[]){

ArrayList<String> list=new ArrayList<String>();//Creating arraylist

list.add("Ravi");//Adding object in arraylist

list.add("Vijay");

list.add("Ravi");

list.add("Ajay");

//Traversing list through Iterator

Iterator itr=list.iterator();

while(itr.hasNext()){

System.out.println(itr.next());

}
}

Output:

Ravi

Vijay

Ravi

Ajay

LinkedList

LinkedList implements the Collection interface. It uses a doubly linked list internally to store
the elements. It can store the duplicate elements. It maintains the insertion order and is not
synchronized. In LinkedList, the manipulation is fast because no shifting is required.

Consider the following example.

import java.util.*;

public class TestJavaCollection2{

public static void main(String args[]){

LinkedList<String> al=new LinkedList<String>();

al.add("Ravi");
al.add("Vijay");

al.add("Ravi");

al.add("Ajay");

Iterator<String> itr=al.iterator();

while(itr.hasNext()){

System.out.println(itr.next());

Output:

Ravi

Vijay

Ravi

Ajay
Vector

Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However, It
is synchronized and contains many methods that are not the part of Collection framework.

Consider the following example.

import java.util.*;

public class TestJavaCollection3{

public static void main(String args[]){

Vector<String> v=new Vector<String>();

v.add("Ayush");

v.add("Amit");

v.add("Ashish");

v.add("Garima");

Iterator<String> itr=v.iterator();

while(itr.hasNext()){

System.out.println(itr.next());

}
Output:

Ayush

Amit

Ashish

Garima

Stack

The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e.,
Stack. The stack contains all of the methods of Vector class and also provides its methods
like boolean push(), boolean peek(), boolean push(object o), which defines its properties.

Consider the following example.

import java.util.*;

public class TestJavaCollection4{

public static void main(String args[]){

Stack<String> stack = new Stack<String>();

stack.push("Ayush");

stack.push("Garvit");

stack.push("Amit");

stack.push("Ashish");
stack.push("Garima");

stack.pop();

Iterator<String> itr=stack.iterator();

while(itr.hasNext()){

System.out.println(itr.next());

Output:

Ayush

Garvit

Amit

Ashish

Queue Interface

Queue interface maintains the first-in-first-out order. It can be defined as an ordered list that
is used to hold the elements which are about to be processed. There are various classes like
PriorityQueue, Deque, and ArrayDeque which implements the Queue interface.

Queue interface can be instantiated as:


Queue<String> q1 = new PriorityQueue();

Queue<String> q2 = new ArrayDeque();

There are various classes that implement the Queue interface, some of them are given below.

PriorityQueue

The PriorityQueue class implements the Queue interface. It holds the elements or objects
which are to be processed by their priorities. PriorityQueue doesn't allow null values to be
stored in the queue.

Consider the following example.

import java.util.*;

public class TestJavaCollection5{

public static void main(String args[]){

PriorityQueue<String> queue=new PriorityQueue<String>();

queue.add("Amit Sharma");

queue.add("Vijay Raj");

queue.add("JaiShankar");

queue.add("Raj");

System.out.println("head:"+queue.element());

System.out.println("head:"+queue.peek());

System.out.println("iterating the queue elements:");

Iterator itr=queue.iterator();
while(itr.hasNext()){

System.out.println(itr.next());

queue.remove();

queue.poll();

System.out.println("after removing two elements:");

Iterator<String> itr2=queue.iterator();

while(itr2.hasNext()){

System.out.println(itr2.next());

Output:

head:Amit Sharma

head:Amit Sharma

iterating the queue elements:

Amit Sharma

Raj

JaiShankar
Vijay Raj

after removing two elements:

Raj

Vijay Raj

Deque Interface

Deque interface extends the Queue interface. In Deque, we can remove and add the elements
from both the side. Deque stands for a double-ended queue which enables us to perform the
operations at both the ends.

Deque can be instantiated as:

Deque d = new ArrayDeque();

ArrayDeque

ArrayDeque class implements the Deque interface. It facilitates us to use the Deque. Unlike
queue, we can add or delete the elements from both the ends.

ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.

Consider the following example.

import java.util.*;

public class TestJavaCollection6{

public static void main(String[] args) {

//Creating Deque and adding elements


Deque<String> deque = new ArrayDeque<String>();

deque.add("Gautam");

deque.add("Karan");

deque.add("Ajay");

//Traversing elements

for (String str : deque) {

System.out.println(str);

Output:

Gautam

Karan

Ajay

Set Interface

Set Interface in Java is present in java.util package. It extends the Collection interface. It
represents the unordered set of elements which doesn't allow us to store the duplicate items.
We can store at most one null value in Set. Set is implemented by HashSet, LinkedHashSet,
and TreeSet.

Set can be instantiated as:

Set<data-type> s1 = new HashSet<data-type>();

Set<data-type> s2 = new LinkedHashSet<data-type>();

Set<data-type> s3 = new TreeSet<data-type>();

HashSet

HashSet class implements Set Interface. It represents the collection that uses a hash table for
storage. Hashing is used to store the elements in the HashSet. It contains unique items.

Consider the following example.

import java.util.*;

public class TestJavaCollection7{

public static void main(String args[]){

//Creating HashSet and adding elements

HashSet<String> set=new HashSet<String>();

set.add("Ravi");

set.add("Vijay");

set.add("Ravi");

set.add("Ajay");
//Traversing elements

Iterator<String> itr=set.iterator();

while(itr.hasNext()){

System.out.println(itr.next());

Output:

Vijay

Ravi

Ajay

LinkedHashSet

LinkedHashSet class represents the LinkedList implementation of Set Interface. It extends the
HashSet class and implements Set interface. Like HashSet, It also contains unique elements.
It maintains the insertion order and permits null elements.

Consider the following example.

import java.util.*;

public class TestJavaCollection8{

public static void main(String args[]){


LinkedHashSet<String> set=new LinkedHashSet<String>();

set.add("Ravi");

set.add("Vijay");

set.add("Ravi");

set.add("Ajay");

Iterator<String> itr=set.iterator();

while(itr.hasNext()){

System.out.println(itr.next());

Output:

Ravi

Vijay

Ajay
SortedSet Interface

SortedSet is the alternate of Set interface that provides a total ordering on its elements. The
elements of the SortedSet are arranged in the increasing (ascending) order. The SortedSet
provides the additional methods that inhibit the natural ordering of the elements.

The SortedSet can be instantiated as:

SortedSet<data-type> set = new TreeSet();

TreeSet

Java TreeSet class implements the Set interface that uses a tree for storage. Like HashSet,
TreeSet also contains unique elements. However, the access and retrieval time of TreeSet is
quite fast. The elements in TreeSet stored in ascending order.

Consider the following example:

import java.util.*;

public class TestJavaCollection9{

public static void main(String args[]){

//Creating and adding elements

TreeSet<String> set=new TreeSet<String>();

set.add("Ravi");

set.add("Vijay");

set.add("Ravi");

set.add("Ajay");
//traversing elements

Iterator<String> itr=set.iterator();

while(itr.hasNext()){

System.out.println(itr.next());

Output:

Ajay

Ravi

Vijay

Java Map Interface

A map contains values on the basis of key, i.e. key and value pair. Each key and value pair is
known as an entry. A Map contains unique keys.

A Map is useful if you have to search, update or delete elements on the basis of a key.
Java Map Hierarchy

There are two interfaces for implementing Map in java: Map and SortedMap, and three
classes: HashMap, LinkedHashMap, and TreeMap. The hierarchy of Java Map is given
below:

A Map doesn't allow duplicate keys, but you can have duplicate values. HashMap and
LinkedHashMap allow null keys and values, but TreeMap doesn't allow any null key or
value.
A Map can't be traversed, so you need to convert it into Set using keySet() or entrySet()
method.

Useful methods of Map interface


Map.Entry Interface

Entry is the subinterface of Map. So we will be accessed it by Map.Entry name. It returns a


collection-view of the map, whose elements are of this class. It provides methods to get key
and value.

Methods of Map.Entry interface

Java Map Example: Non-Generic (Old Style)


//Non-generic

import java.util.*;

public class MapExample1 {

public static void main(String[] args) {

Map map=new HashMap();

//Adding elements to map

map.put(1,"Amit");

map.put(5,"Rahul");

map.put(2,"Jai");

map.put(6,"Amit");

//Traversing Map

Set set=map.entrySet();//Converting to Set so that we can traverse

Iterator itr=set.iterator();

while(itr.hasNext()){

//Converting to Map.Entry so that we can get key and value separately

Map.Entry entry=(Map.Entry)itr.next();

System.out.println(entry.getKey()+" "+entry.getValue());

}
Output:

1 Amit

2 Jai

5 Rahul

6 Amit

import java.util.*;

class MapExample2{

public static void main(String args[]){

Map<Integer,String> map=new HashMap<Integer,String>();

map.put(100,"Amit");

map.put(101,"Vijay");

map.put(102,"Rahul");

//Elements can traverse in any order

for(Map.Entry m:map.entrySet()){

System.out.println(m.getKey()+" "+m.getValue());

}
Output:

102 Rahul

100 Amit

101 Vijay

Java Map Example: comparingByKey()

import java.util.*;

class MapExample3{

public static void main(String args[]){

Map<Integer,String> map=new HashMap<Integer,String>();

map.put(100,"Amit");

map.put(101,"Vijay");

map.put(102,"Rahul");

//Returns a Set view of the mappings contained in this map

map.entrySet()

//Returns a sequential Stream with this collection as its source

.stream()

//Sorted according to the provided Comparator

.sorted(Map.Entry.comparingByKey())
//Performs an action for each element of this stream

.forEach(System.out::println);

Output:

100=Amit

101=Vijay

102=Rahul

Java Map Example: comparingByKey() in Descending Order

import java.util.*;

class MapExample4{

public static void main(String args[]){

Map<Integer,String> map=new HashMap<Integer,String>();

map.put(100,"Amit");

map.put(101,"Vijay");

map.put(102,"Rahul");

//Returns a Set view of the mappings contained in this map


map.entrySet()

//Returns a sequential Stream with this collection as its source

.stream()

//Sorted according to the provided Comparator

.sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))

//Performs an action for each element of this stream

.forEach(System.out::println);

Output:

102=Rahul

101=Vijay

100=Amit

Java Map Example: comparingByValue()

import java.util.*;

class MapExample5{

public static void main(String args[]){

Map<Integer,String> map=new HashMap<Integer,String>();


map.put(100,"Amit");

map.put(101,"Vijay");

map.put(102,"Rahul");

//Returns a Set view of the mappings contained in this map

map.entrySet()

//Returns a sequential Stream with this collection as its source

.stream()

//Sorted according to the provided Comparator

.sorted(Map.Entry.comparingByValue())

//Performs an action for each element of this stream

.forEach(System.out::println);

Output:

100=Amit

102=Rahul

101=Vijay
Java Map Example: comparingByValue() in Descending Order

import java.util.*;

class MapExample6{

public static void main(String args[]){

Map<Integer,String> map=new HashMap<Integer,String>();

map.put(100,"Amit");

map.put(101,"Vijay");

map.put(102,"Rahul");

//Returns a Set view of the mappings contained in this map

map.entrySet()

//Returns a sequential Stream with this collection as its source

.stream()

//Sorted according to the provided Comparator

.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))

//Performs an action for each element of this stream

.forEach(System.out::println);

}
Output:

101=Vijay

102=Rahul

100=Amit
Chapter 12:Java Date and Time

The java.time, java.util, java.sql and java.text packages contains classes for representing date
and time. Following classes are important for dealing with date in Java.

Java 8 Date/Time API

Java has introduced a new Date and Time API since Java 8. The java.time package contains
Java 8 Date and Time classes.

o java.time.LocalDate class
o java.time.LocalTime class
o java.time.LocalDateTime class
o java.time.MonthDay class
o java.time.OffsetTime class
o java.time.OffsetDateTime class
o java.time.Clock class
o java.time.ZonedDateTime class
o java.time.ZoneId class
o java.time.ZoneOffset class
o java.time.Year class
o java.time.YearMonth class
o java.time.Period class
o java.time.Duration class
o java.time.Instant class
o java.time.DayOfWeek enum
o java.time.Month enum

Classical Date/Time API

But classical or old Java Date API is also useful. Let's see the list of classical Date and Time
classes.

 java.util.Date class
 java.sql.Date class
 java.util.Calendar class
 java.util.GregorianCalendar class
 java.util.TimeZone class
 java.sql.Time class
 java.sql.Timestamp class

Formatting Date and Time

We can format date and time in Java by using the following classes:

 java.text.DateFormat class
 java.text.SimpleDateFormat class

Java Date and Time APIs

Java provide the date and time functionality with the help of two packages java.time and
java.util. The package java.time is introduced in Java 8, and the newly introduced classes
tries to overcome the shortcomings of the legacy java.util.Date and java.util.Calendar classes.

Classical Date Time API Classes

The primary classes before Java 8 release were:

Java.lang.System: The class provides the currentTimeMillis() method that returns the
current time in milliseconds. It shows the current date and time in milliseconds from January
1st 1970.

java.util.Date: It is used to show specific instant of time, with unit of millisecond.

java.util.Calendar: It is an abstract class that provides methods for converting between


instances and manipulating the calendar fields in different ways.

java.text.SimpleDateFormat: It is a class that is used to format and parse the dates in a


predefined manner or user defined pattern.

java.util.TimeZone: It represents a time zone offset, and also figures out daylight savings.

Drawbacks of existing Date/Time API's

1. Thread safety: The existing classes such as Date and Calendar does not provide thread safety.
Hence it leads to hard-to-debug concurrency issues that are needed to be taken care by
developers. The new Date and Time APIs of Java 8 provide thread safety and are immutable,
hence avoiding the concurrency issue from developers.
2. Bad API designing: The classic Date and Calendar APIs does not provide methods to perform
basic day-to-day functionalities. The Date and Time classes introduced in Java 8 are ISO-
centric and provides number of different methods for performing operations regarding date,
time, duration and periods.
3. Difficult time zone handling: To handle the time-zone using classic Date and Calendar classes
is difficult because the developers were supposed to write the logic for it. With the new APIs,
the time-zone handling can be easily done with Local and ZonedDate/Time APIs.

New Date Time API in Java 8

The new date API helps to overcome the drawbacks mentioned above with the legacy classes.
It includes the following classes:

java.time.LocalDate: It represents a year-month-day in the ISO calendar and is useful for


representing a date without a time. It can be used to represent a date only information such as
a birth date or wedding date.

java.time.LocalTime: It deals in time only. It is useful for representing human-based time of


day, such as movie times, or the opening and closing times of the local library.

java.time.LocalDateTime: It handles both date and time, without a time zone. It is a


combination of LocalDate with LocalTime.

java.time.ZonedDateTime: It combines the LocalDateTime class with the zone information


given in ZoneId class. It represent a complete date time stamp along with timezone
information.

java.time.OffsetTime: It handles time with a corresponding time zone offset from


Greenwich/UTC, without a time zone ID.

java.time.OffsetDateTime: It handles a date and time with a corresponding time zone offset
from Greenwich/UTC, without a time zone ID.
java.time.Clock : It provides access to the current instant, date and time in any given time-
zone. Although the use of the Clock class is optional, this feature allows us to test your code
for other time zones, or by using a fixed clock, where time does not change.

java.time.Instant : It represents the start of a nanosecond on the timeline (since EPOCH)


and useful for generating a timestamp to represent machine time. An instant that occurs
before the epoch has a negative value, and an instant that occurs after the epoch has a positive
value.

java.time.Duration : Difference between two instants and measured in seconds or


nanoseconds and does not use date-based constructs such as years, months, and days, though
the class provides methods that convert to days, hours, and minutes.

java.time.Period : It is used to define the difference between dates in date-based values


(years, months, days).

java.time.ZoneId : It states a time zone identifier and provides rules for converting between
an Instant and a LocalDateTime.

java.time.ZoneOffset : It describe a time zone offset from Greenwich/UTC time.

java.time.format.DateTimeFormatter : It comes up with various predefined formatter, or


we can define our own. It has parse() or format() method for parsing and formatting the date
time values.
Chapter 13:Java Enums

o The Enum in Java is a data type which contains a fixed set of constants.
o It can be used for days of the week (SUNDAY, MONDAY, TUESDAY,
WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY) , directions (NORTH,
SOUTH, EAST, and WEST), season (SPRING, SUMMER, WINTER, and
AUTUMN or FALL), colors (RED, YELLOW, BLUE, GREEN, WHITE, and
BLACK) etc. According to the Java naming conventions, we should have all
constants in capital letters. So, we have enum constants in capital letters.
o Java Enums can be thought of as classes which have a fixed set of constants (a
variable that does not change). The Java enum constants are static and final implicitly.
It is available since JDK 1.5.
o Enums are used to create our own data type like classes. The enum data type (also
known as Enumerated Data Type) is used to define an enum in Java. Unlike C/C++,
enum in Java is more powerful. Here, we can define an enum either inside the class or
outside the class.
o Java Enum internally inherits the Enum class, so it cannot inherit any other class, but
it can implement many interfaces. We can have fields, constructors, methods, and
main methods in Java enum.

Points to remember for Java Enum

 Enum improves type safety


 Enum can be easily used in switch
 Enum can be traversed
 Enum can have fields, constructors and methods
 Enum may implement many interfaces but cannot extend any class because it internally
extends Enum class
Simple Example of Java Enum

class EnumExample1{

//defining the enum inside the class

public enum Season { WINTER, SPRING, SUMMER, FALL }

//main method

public static void main(String[] args) {

//traversing the enum

for (Season s : Season.values())

System.out.println(s); }}

Output:
WINTER
SPRING
SUMMER
FALL

Chapter 14:Java Iterator

An Iterator is an object that can be used to loop through collections, like ArrayList and
HashSet. It is called an "iterator" because "iterating" is the technical term for looping.

To use an Iterator, you must import it from the java.util package.

Getting an Iterator

The iterator() method can be used to get an Iterator for any collection:

ExampleGet your own Java Server


// Import the ArrayList class and the Iterator class
import java.util.ArrayList;
import java.util.Iterator;

public class Main {


public static void main(String[] args) {
// Make a collection
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");

// Get the iterator


Iterator<String> it = cars.iterator();

// Print the first item


System.out.println(it.next());
}
}

Looping Through a Collection

To loop through a collection, use the hasNext() and next() methods of the Iterator:

Example
while(it.hasNext()) {
System.out.println(it.next());
}

ADVERTISEMENT

Removing Items from a Collection

Iterators are designed to easily change the collections that they loop through. The remove()
method can remove items from a collection while looping.

Example

Use an iterator to remove numbers less than 10 from a collection:

import java.util.ArrayList;
import java.util.Iterator;

public class Main {


public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(12);
numbers.add(8);
numbers.add(2);
numbers.add(23);
Iterator<Integer> it = numbers.iterator();
while(it.hasNext()) {
Integer i = it.next();
if(i < 10) {
it.remove();
}
}
System.out.println(numbers);
}
}

Output: [12, 23]

You might also like