Core Java
Core Java
No content Page No
1 Introduction to JAVA
7 Reflections
13 Enumeration
14 Iterator.
Chapter 1: Introduction to JAVA
What is 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.)
There are mainly 4 types of applications that can be created using Java
programming:
1) Standalone 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
4) Mobile Application
According to Sun, 3 billion devices run Java. There are many devices where
Java is currently used. Some of them are as follows:
4) JavaFX
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:
C++
5. Robust:
6. Multithreaded:
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:
10)Distributed:
11) Dynamic:
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,
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
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.
As you can observe in the above figure, JVM contains the following main
components that are as follows:
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
Java Virtual Machine performs the following operations for execution of the
program. They are as follows:
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.
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.
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.
• 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.
• 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
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.
1. Temporary
2. Permanent
To set the temporary path of JDK, user needs to follow following steps:
For example:
For setting the permanent path of JDK, user needs to follow these steps:
variable -> write path in variable name ->write path of bin folder in variable
value -> Click ok-
> ok->ok
For Example:
Now the permanent path is set. User can execute any program of java from any
drive
Simple Java Program:
Example program
/*First java program*/
} //end of main
Paradigms of Programming:
1)procedure-oriented model
2)object-oriented programming
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.2 Class
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
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.
1.Java Keywords
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.
In Java language, primitive data types are the building blocks of data
manipulation. These are the most basic data types available in Java language.
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
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.
2. Operators:
Example: int x = 5;
int y = 10;
int sum = x + y;
boolean isGreaterThan = x > y;
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:
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):
Inheritance:
Create a hierarchy of classes, allowing a subclass to inherit properties and
methods from a superclass.
Interfaces:
@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:
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
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.
The following rules are mandatory when you’re working with Java classes:
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.
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.
Object Definitions:
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.
File: Student.java
class Student{
//defining fields
String name;
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
//another class
class Student{
int id;
String name;
class TestStudent1{
System.out.println(s1.name);
1. By reference variable
2. By method
3. By constructor
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{
s1.id=101;
s1.name="Sonoo";
Output:
101 Sonoo
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;
rollno=r;
name=n;
class TestStudent4{
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.
// Class attributes
String make;
String model;
int year;
boolean isRunning;
// Constructor
this.make = make;
this.model = model;
this.year = year;
this.isRunning = false;
System.out.println("The " + year + " " + make + " " + model + "'s engine is
now running.");
isRunning = true;
System.out.println("The " + year + " " + make + " " + model + "'s engine is
now stopped.");
isRunning = false;
}
myCar.startEngine();
myCar.stopEngine();
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.
package mypack;
public class Simple{
{ System.out.println("Welcome to package");
} }
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
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:
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
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{
System.out.println("Welcome to package");
}}
If you are not using any IDE, you need to follow the syntax given below:
charch[]={'s','t','r','i','n','g','s'};
System.out.println(s2);System.out.println(s3);
}}
OUTPUT:
java
strings
example
Immutable String in Java
class Testimmutablestring
String s="Sachin";
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".
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:
2. Thread Safe:
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.
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.
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:
class Teststringcomparison1{
String s1="Sachin";
String s2="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
class Teststringcomparison3{
String s1="Sachin";
String s2="Sachin";
Output: true
false
class Teststringcomparison4{
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:
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());
}
}
2)
System.out.println(txt.toUpperCase());
System.out.println(txt.toLowerCase());
}}
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):
System.out.println(txt.indexOf("locate"));
Output:7
String Concatenation
The + operator can be used between strings to combine them. This is called
concatenation:
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:
System.out.println(firstName.concat(lastName));
int x = 10;
int y = 20;
int z = x + y;
System.out.println(z);
Output:30
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:
String x = "10";
int y = 20;
String z = x + y;
System.out.println(z);
Output:1020
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:
String txt = "We are the so-called \"Vikings\" from the north.";
System.out.println(txt);
Output:
System.out.println(txt);
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?
The append() method concatenates the given argument with this String.
StringBufferExample.java
class StringBufferExample{
Output:
Hello Java
The insert() method inserts the given String with this string at the given
position.
StringBufferExample2.java
class StringBufferExample2{
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{
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
Output:
HJavalo
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[]){
sb.delete(1,3);
System.out.println(sb);//prints Hlo
Output:
Hlo
The reverse() method of the StringBuilder class reverses the current String.
StringBufferExample5.java
class StringBufferExample5{
sb.reverse();
System.out.println(sb);//prints olleH
}
}
Output:
olleH
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{
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
Output:
16
16
34
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{
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
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.
The StringBuilder append() method concatenates the given argument with this
String.
StringBuilderExample.java
1. class StringBuilderExample{
2. public static void main(String args[]){
7. }
Output:
Hello Java
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[]){
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[]){
5. System.out.println(sb);//prints Hlo
6. }
7. }
Output:
Hlo
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
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{
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("Java is my favourite language");
Output:
16
16
34
StringBuilderExample7.java
class StringBuilderExample7{
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
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
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;
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
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
3) Error
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.
try{
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
Output:
There are given some scenarios where unchecked exceptions may occur. They
are as follows:
1) A scenario where ArithmeticException occurs
1. int a=50/0;//ArithmeticException
1. String s=null;
2. System.out.println(s.length());//NullPointerException
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
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.
try{
}catch(Exception_class_Name ref){}
try{
}finally{}
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.
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:
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
Example 1
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.
Let's see the solution of the above problem by a java try-catch block.
TryCatchExample2.java
try
catch(ArithmeticException e)
System.out.println(e);
Output:
java.lang.ArithmeticException: / by zero
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
MultipleCatchBlock1.java
try{
a[5]=30/0;
catch(ArithmeticException e)
{
catch(ArrayIndexOutOfBoundsException e)
System.out.println("ArrayIndexOutOfBounds
Exception occurs");
catch(Exception e)
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.
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{
try{
try{
int b =39/0;
catch(ArithmeticException e)
System.out.println(e);
}
try{
a[5]=4;
catch(ArrayIndexOutOfBoundsException e)
System.out.println(e);
System.out.println("other statement");
catch(Exception e)
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 is a block used to execute important code such as closing the
connection, etc.
Let's see the different cases where Java finally block can be used.
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 {
try{
int data=25/5;
System.out.println(data);
catch(NullPointerException e){
System.out.println(e);
Output:
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
try {
int data=25/0;
System.out.println(data);
catch(NullPointerException e){
System.out.println(e);
finally {
Output:
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
try {
int data=25/0;
System.out.println(data);
catch(ArithmeticException e){
System.out.println("Exception handled");
System.out.println(e);
finally {
Output:
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.
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.
if(age<18) {
else {
System.out.println("Person is eligible to vote!!");
//main method
validate(13);
Output:
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.*;
//main method
public static void main(String args[]){
try
method();
catch (FileNotFoundException e)
e.printStackTrace();
Output:
Example 3: Throwing User-defined Exception
exception is everything else under the Throwable class.
TestThrow3.java
super(str);
{
try
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.
class TestExceptionPropagation1{
void m(){
int data=50/0;
void n(){
m();
void p(){
try{
n();
}catch(Exception e){System.out.println("exception
handled");}
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.
class TestExceptionPropagation2{
void m(){
void n(){
m();
void p(){
try{
n();
}catch(Exception e){System.out.println("exception
handeled");}
obj.p();
System.out.println("normal flow");
}
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{
m();
void p(){
try{
n();
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.
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.
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{
try{
M m=new M();
m.method();
Output:
exception handled
normal flow...
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.
Testthrows3.java
import java.io.*;
class M{
}
}
class Testthrows3{
M m=new M();
m.method();
System.out.println("normal flow...");
Output:
B) If exception occurs
Testthrows4.java
import java.io.*;
class M{
class Testthrows4{
M m=new M();
m.method();
System.out.println("normal flow...");
Output:
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
if (num < 1) {
else {
//main method
obj.checkNum(-3);
}
Difference between throw and throws in Java
TestThrows.java
//defining a method
int div = m / n;
return div;
//main method
try {
System.out.println(obj.divideNum(45, 0));
}
System.out.println("Rest of the code..");
Output:
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.
void display() {
age = 55;
}
obj.display();
Output:
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
try {
int data=25/0;
System.out.println(data); }
System.out.println("Exception handled");
System.out.println(e);
finally {
}
Output:
FinalizeExample.java
obj = null;
System.gc();
There are many rules if we talk about method overriding with exception
handling.
import java.io.*;
class Parent{
void msg() {
System.out.println("parent method");
System.out.println("TestExceptionChild");
p.msg();
}
Output:
TestExceptionChild1.java
import java.io.*;
class Parent{
void msg() {
System.out.println("parent method");
}
class TestExceptionChild1 extends Parent{
System.out.println("child method");
p.msg();
import java.io.*;
class Parent{
void msg()throws ArithmeticException {
System.out.println("parent method");
System.out.println("child method");
try {
p.msg();
}
}
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.
Java exceptions cover almost all the general type of exceptions that may occur
in the programming. However, we sometimes need to create custom exceptions.
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
super(str);
else {
System.out.println("welcome to vote");
// main method
try
validate(13);
Output:
Example 2:
TestCustomException2.java
// main method
try
System.out.println(ex.getMessage());
}
Output:
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.
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 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:
Then we can use the obj_test to perform reflection as this object will have all
the information about the class Test.
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:
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.
import java.lang.Class;
import java.lang.reflect.*;
interface Person {
System.out.println("I am a Student");
class Main {
try {
catch(Exception e) {
e.printStackTrace();
Output:
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.*;
interface PetAnimals {
public void makeSound();
}
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.
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
Given below are two reflection examples that demonstrate the reflection on the
public and private field.
import java.lang.Class;
import java.lang.reflect.*;
class Student {
class Main {
try{
student_field.set(student, "Lacey");
catch(Exception e) {
e.printStackTrace();
Output
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
modifier.
Reflection: Constructor
The constructor class provides the following methods for this purpose.
Method Description
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.
class c=obj.getclass();
Class c = Class.forName(“com.demo.Mydemoclass”);
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 {
this.age = age;
return name;
this.name = name;
return 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
Reflection: Constructor
The constructor class provides the following methods for this purpose.
Method Description
superclass.
import java.lang.Class
class Person {
}class Main {
try {
for(Constructor c : constructors) {
Class[] paramList=c.getParameterTypes();
System.out.print ("Constructor parameter types :");
System.out.println("\n");
catch(Exception e) {
e.printStackTrace();
Output
Drawbacks Of Reflection
Java files
Java has several methods for creating, reading, updating, and deleting files.
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):
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
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:
To get more information about a file, use any of the File methods:
Example
Delete a File
Example
import java.io.File; // Import the File class
Delete a Folder
You can also delete a folder. However, it must be empty:
Example:
import java.io.File;
if (myObj.delete()) {
} else {
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.
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;
/**
* @author w3spoint
*/
class IOTest{
try {
ByteArrayInputStream bais =
new ByteArrayInputStream(b);
int i;
//read file.
while((i=bais.read())!=-1){
System.out.print((char)i);
} catch (Exception e) {
e.printStackTrace();
//method call.
obj.readFile();
}
}
ByteArrayOutputStream:
ByteArrayOutputStream class uses byte array to write data. The buffer automatically grows
as data is written to it.
1. ByteArrayOutputStream ()
Creates a new byte array output stream, with a buffer capacity of the specified size, in bytes.
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;
/**
* @author w3spoint
*/
class IOTest{
try {
FileOutputStream fos =
baos.write(str.getBytes());
baos.writeTo(fos);
baos.flush();
baos.close();
} catch (Exception e) {
e.printStackTrace();
//method call
obj.writeFile();
}
Character stream
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
Applications
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.
Common Methods
Example Usage
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
* @author w3spoint
*/
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{
try
FileOutputStream fos =
oos.writeObject(stu);
//close streams.
oos.close();
fos.close();
"F:\\New folder\\student.ser");
}catch(IOException e)
System.out.println(e);
Student stu =
//Method call.
obj.objectSerialization(stu);
Output:
Deserialization:
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");
//write object.
stu = (Student) ois.readObject();
//close streams.
ois.close();
fis.close();
Output:
Name = Parmander
Class Name = MCA
RollNo = MCA/07/27
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.
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:
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:
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.
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.
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
Disadvantage:
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.
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.
In this example, sonoo is the database name, root is the username and password both.
import java.sql.*;
class MysqlCon{
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sonoo","root","root");
Statement stmt=con.createStatement();
while(rs.next())
con.close();
Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the jar
file here.
2) Set classpath:
o temporary
o permanent
C:>set classpath=c:\folder\mysql-connector-java-5.0.8-bin.jar;.;
PreparedStatement interface
As you can see, we are passing parameter (?) for the values. Its value will be set by calling
the setter methods of PreparedStatement.
Improves performance: The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once.
Syntax:
import java.sql.*;
class InsertPrepared{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","syst
em","oracle");
stmt.setString(2,"Ratan");
int i=stmt.executeUpdate();
con.close();
}
Example of PreparedStatement interface that updates the record
3. stmt.setInt(2,101);
4.
5. int i=stmt.executeUpdate();
6. System.out.println(i+" records updated");
Chapter 10: Multithreading in Java
1) It doesn't block the user because threads are independent and you can
perform multiple operations at the same time.
Multitasking
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 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).
The Collection framework represents a unified architecture for storing and manipulating a
group of objects. It has:
There are many methods declared in the Collection interface. They are as follows:
Iterator interface
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.
1. Iterator<T> iterator()
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.
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{
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
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.
import java.util.*;
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.
import java.util.*;
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.
import java.util.*;
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.
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.
import java.util.*;
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());
Iterator itr=queue.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
queue.remove();
queue.poll();
Iterator<String> itr2=queue.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
Output:
head:Amit Sharma
head:Amit Sharma
Amit Sharma
Raj
JaiShankar
Vijay Raj
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.
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.
import java.util.*;
deque.add("Gautam");
deque.add("Karan");
deque.add("Ajay");
//Traversing elements
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.
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.
import java.util.*;
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.
import java.util.*;
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.
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.
import java.util.*;
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
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.
import java.util.*;
map.put(1,"Amit");
map.put(5,"Rahul");
map.put(2,"Jai");
map.put(6,"Amit");
//Traversing Map
Iterator itr=set.iterator();
while(itr.hasNext()){
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{
map.put(100,"Amit");
map.put(101,"Vijay");
map.put(102,"Rahul");
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
Output:
102 Rahul
100 Amit
101 Vijay
import java.util.*;
class MapExample3{
map.put(100,"Amit");
map.put(101,"Vijay");
map.put(102,"Rahul");
map.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
//Performs an action for each element of this stream
.forEach(System.out::println);
Output:
100=Amit
101=Vijay
102=Rahul
import java.util.*;
class MapExample4{
map.put(100,"Amit");
map.put(101,"Vijay");
map.put(102,"Rahul");
.stream()
.sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
.forEach(System.out::println);
Output:
102=Rahul
101=Vijay
100=Amit
import java.util.*;
class MapExample5{
map.put(101,"Vijay");
map.put(102,"Rahul");
map.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue())
.forEach(System.out::println);
Output:
100=Amit
102=Rahul
101=Vijay
Java Map Example: comparingByValue() in Descending Order
import java.util.*;
class MapExample6{
map.put(100,"Amit");
map.put(101,"Vijay");
map.put(102,"Rahul");
map.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.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 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
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
We can format date and time in Java by using the following classes:
java.text.DateFormat class
java.text.SimpleDateFormat class
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.
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.TimeZone: It represents a time zone offset, and also figures out daylight savings.
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.
The new date API helps to overcome the drawbacks mentioned above with the legacy classes.
It includes the following classes:
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.ZoneId : It states a time zone identifier and provides rules for converting between
an Instant and a LocalDateTime.
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.
class EnumExample1{
//main method
System.out.println(s); }}
Output:
WINTER
SPRING
SUMMER
FALL
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.
Getting an Iterator
The iterator() method can be used to get an Iterator for any 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
Iterators are designed to easily change the collections that they loop through. The remove()
method can remove items from a collection while looping.
Example
import java.util.ArrayList;
import java.util.Iterator;