Java Programming Lecture Notes
Java Programming Lecture Notes
What is Java?
Java is a programming language and a platform. Java is a high level, robust, object-
oriented and secure programming language.
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.
Object means a real-world entity such as a pen, chair, table, computer, watch,
etc. Object-Oriented Programming is a methodology or paradigm to design a
program using classes and objects. It simplifies software development and maintenance
by providing some concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object
Any entity that has state and behavior is known as an object. For
example, a chair, pen, table, keyboard, bike, etc. It can be
physical or logical.
Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual
object. Class doesn't consume any space.
Inheritance
When one object acquires all the properties and behaviors of a parent object, it is known
as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
If one task is performed in different ways, it is known as polymorphism. For example: to
convince the customer differently, to draw something, for example, shape, triangle,
rectangle, etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example
phone call, we don't know the internal processing.
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as
encapsulation. For example, a capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.
The History and Evolution of JAVA:
Java was developed by James Gosling, who is known as the father of Java, in 1995. James Gosling and his
team members started the project in the early '90s.
Currently, Java is used in internet programming, mobile devices, games, e-business solutions, etc.
Following are given significant points that describe the history of Java.
James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991.
The small team of sun engineers called Green Team.
3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.
According to James Gosling, "Java was one of the top choices along with Silk". Since Java was so unique,
most of the team members preferred Java than other names.
8) Java is an island in Indonesia where the first coffee was produced (called Java coffee). It is a kind of
espresso bean. Java name was chosen by James Gosling while having a cup of coffee nearby his office.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
12) JDK 1.0 was released on January 23, 1996. After the first release of Java, there have been many
additional features added to the language. Now Java is being used in Windows applications, Web
applications, enterprise applications, mobile applications, cards, etc. Each new version adds new features
in Java.
Everything in Java is associated with classes and objects, along with its attributes and methods.
For example: in real life, a car is an object. The car has attributes, such as weight and color,
and methods, such as drive and brake.
Int x=5;
Create an Object:
an object is created from a class. We have already created the class named Main, so now we can
use this to create objects.
To create an object of Main, specify the class name, followed by the object name, and use the
keyword new
Int x=5;
System.out.println(myobj.x);
publicclassMain{
int x =5;
publicstaticvoidmain(String[]args){
MainmyObj1=newMain();// Object 1
MainmyObj2=newMain();// Object 2
System.out.println(myObj1.x);
System.out.println(myObj2.x);
}
Methods:
Methods are used to perform certain actions, and they are also known
as functions.To reuse code: define the code once, and use it many times.
publicclassMain{
staticvoidmyMethod(){
// code to be executed
publicclassMain{
staticvoidmyMethod(){
publicstaticvoidmain(String[]args){
myMethod();
Parameters are specified after the method name, inside the parentheses. You
can add as many parameters as you want, just separate them with a comma.
publicclassMain{
staticvoidmyMethod(Stringfname){
System.out.println(fname+" Refsnes");
publicstaticvoidmain(String[]args){
myMethod("Liam");
myMethod("Jenny");
myMethod("Anja");
// Liam Refsnes
// Jenny Refsnes
// AnjaRefsnes
Constructors:
A constructor in Java is a special method that is used to initialize objects. The
constructor is called when an object of a class is created. It can be used to set
initial values for object attributes.
Create a constructor:
publicclassMain{
publicMain(){
publicstaticvoidmain(String[]args){
// Outputs 5
Constructor Parameters
publicclassMain{
int x;
publicMain(int y){
x = y;
publicstaticvoidmain(String[]args){
MainmyObj=newMain(5);
System.out.println(myObj.x);
// Outputs 5
The most common use of the this keyword is to eliminate the confusion
between class attributes and parameters with the same name (because a class
attribute is shadowed by a method or constructor parameter). If you omit the
keyword in the example above, the output would be "0" instead of "5".
publicclassMain{
int x;
publicMain(int x){
this.x= x;
publicstaticvoidmain(String[]args){
MainmyObj=newMain(5);
System.out.println("Value of x = "+myObj.x);
1) By nulling a reference:
1. Employee e=new Employee();
2. e=null;
3) By anonymous object:
1. new Employee();
A primitive data type specifies the size and type of variable values, and it has
no additional methods.
Byte, Short, Int, Long, Float, Boolean, Char, Double these are the eight
primitive date types in java.
Numbers
Primitive number types are divided into two groups:
Integer types stores whole numbers, positive or negative (such as 123 or -456), without decimals.
Valid types are byte, short, int and long. Which type you should use, depends on the numeric
value.
Floating point types represents numbers with a fractional part, containing one or more decimals.
There are two types: float and double.
Even though there are many numeric types in Java, the most used for numbers are int (for whole
numbers) and double (for floating point numbers).
Integer Types
Byte
The byte data type can store whole numbers from -128 to 127. This can be used instead of int or
other integer types to save memory when you are certain that the value will be within -128 and 127:
Example
bytemyNum=100;
System.out.println(myNum);
Short
The short data type can store whole numbers from -32768 to 32767:
Example
shortmyNum=5000;
System.out.println(myNum);
Int
The int data type can store whole numbers from -2147483648 to 2147483647. In general, and in our
tutorial, the int data type is the preferred data type when we create variables with a numeric value.
Example
intmyNum=100000;
System.out.println(myNum);
Long
The long data type can store whole numbers from -9223372036854775808 to
9223372036854775807. This is used when int is not large enough to store the value. Note that you
should end the value with an "L":
Example
longmyNum=15000000000L;
System.out.println(myNum);
The float and double data types can store fractional numbers. Note that you should end the value
with an "f" for floats and "d" for doubles:
Float Example
floatmyNum=5.75f;
System.out.println(myNum);
Double Example
doublemyNum=19.99d;
System.out.println(myNum);
The precision of a floating point value indicates how many digits the value can have after the
decimal point. The precision of float is only six or seven decimal digits, while double variables
have a precision of about 15 digits. Therefore it is safer to use double for most calculations.
Scientific Numbers
A floating point number can also be a scientific number with an "e" to indicate the power of 10:
Example
float f1 =35e3f;
double d1 =12E4d;
System.out.println(f1);
System.out.println(d1);
Boolean Types
A boolean data type is declared with the boolean keyword and can only take the
values true or false:
Example
booleanisJavaFun=true;
booleanisFishTasty=false;
Boolean values are mostly used for conditional testing, which you will learn
more about in a later chapter.
Characters
The char data type is used to store a single character. The character must be
surrounded by single quotes, like 'A' or 'c':
Example
charmyGrade='B';
System.out.println(myGrade);
Example
char myVar1 =65, myVar2 =66, myVar3 =67;
System.out.println(myVar1);
System.out.println(myVar2);
System.out.println(myVar3);
Strings
The String data type is used to store a sequence of characters (text). String
values must be surrounded by double quotes:
Example
String greeting ="Hello World";
System.out.println(greeting);
Java Variables
Variables are containers for storing data values.
Syntax
typevariableName= value;
Where type is one of Java's types (such as int or String), and variableName is
the name of the variable (such as x or name). The equal sign is used to
assign values to the variable.
To create a variable that should store text, look at the following example:
Example
Create a variable called name of type String and assign it the value "John":
System.out.println(name);
To create a variable that should store a number, look at the following example:
Example
Create a variable called myNum of type int and assign it the value 15:
intmyNum=15;
System.out.println(myNum);
You can also declare a variable without assigning the value, and assign the
value later:
Example
intmyNum;
myNum=15;
System.out.println(myNum);
Example
Instead of writing:
int x =5;
int y =6;
int z =50;
System.out.println(x + y + z);
You can simply write:
System.out.println(x + y + z);
Example
int x, y, z;
x = y = z =50;
System.out.println(x + y + z);
Widening Casting
Widening casting is done automatically when passing a smaller size type
to a larger size type:
Example
publicclassMain{
publicstaticvoidmain(String[]args){
intmyInt=9;
doublemyDouble=myInt;// Automatic casting: int to double
System.out.println(myInt);// Outputs 9
System.out.println(myDouble);// Outputs 9.0
}
}
Narrowing Casting
Narrowing casting must be done manually by placing the type in
parentheses in front of the value:
Example
publicclassMain{
publicstaticvoidmain(String[]args){
doublemyDouble=9.78d;
intmyInt=(int)myDouble;// Manual casting: double to int
System.out.println(myDouble);// Outputs 9.78
System.out.println(myInt);// Outputs 9
}
}
Java Arrays
Normally, an array is a collection of similar type of elements which has contiguous
memory location.
Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure
where we store similar elements. We can store only a fixed set of elements in a Java
array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.
Unlike C/C++, we can get the length of the array using the length member. In C/C++,
we need to use the sizeof operator.
In Java, array is an object of a dynamically generated class. Java array inherits the Object
class, and implements the Serializable as well as Cloneable interfaces. We can store
primitive values or objects in an array in Java. Like C/C++, we can also create single
dimentional or multidimentional arrays in Java.
Moreover, Java provides the feature of anonymous arrays which is not available in
C/C++.
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its
size at runtime. To solve this problem, collection framework is used in Java which grows
automatically.
1. arrayRefVar=new datatype[size];
. The Java for-each loop prints the array elements one by one. It holds an array element in a variable,
then executes the body of the loop.
1. for(data_type variable:array){
2. //body of the loop
3. }
Let us see the example of print the elements of Java array using the for-each loop.
1. //Java Program to print the array elements using for-each loop
2. class Testarray1{
3. public static void main(String args[]){
4. int arr[]={33,3,4,5};
5. //printing array using for-each loop
6. for(int i:arr)
7. System.out.println(i);
8. }}
Output: 33 3 4 5
Let's see the simple example to get the minimum number of an array using a method.
Output: 3
Operators in Java
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, /
etc.
There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
Arithmetic multiplicative * / %
additive + -
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary ternary ? :
Output:
10
12
12
10
Output:
22
21
Output:
-11
9
false
true
Output:
15
5
50
2
0
Output:
21
Output:
40
80
80
240
1. public OperatorExample{
2. public static void main(String args[]){
3. System.out.println(10>>2);//10/2^2=10/4=2
4. System.out.println(20>>2);//20/2^2=20/4=5
5. System.out.println(20>>3);//20/2^3=20/8=2
6. }}
Output:
2
5
2
Output:
5
5
-5
1073741819
The bitwise & operator always checks both conditions whether first condition is true or
false.
Output:
false
false
Output:
false
10
false
11
The bitwise | operator always checks both conditions whether first condition is true or
false.
Output:
true
true
true
10
true
11
Output:
Another Example:
Output:
5
Java Assignment Operator
Java assignment operator is one of the most common operators. It is used to assign the
value on its right to the operand on its left.
Output:
14
16
Output:
13
9
18
9
Output:
Output:
20
Decision-Making statements:
As the name suggests, decision-making statements decide which statement to execute
and when. Decision-making statements evaluate the Boolean expression and control the
program flow depending upon the result of the condition provided. There are two types
of decision-making statements in Java, i.e., If statement and switch statement.
1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program is
diverted depending upon the specific condition. The condition of the If statement gives
a Boolean value, either true or false. In Java, there are four types of if-statements given
below.
1. if-else statement
2. if-else-if ladder
3. Nested if-statement
1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a
Boolean expression and enables the program to enter a block of code if the expression
evaluates to true.
1. if(condition) {
2. statement 1; //executes when condition is true
3. }
Consider the following example in which we have used the if statement in the java code.
Student.java
Student.java
Output:
x + y is greater than 20
2) if-else statement
is an extension to the if-statement, which uses another block of code, i.e., else block. The else
block is executed if the condition of the if-block is evaluated as false.
Syntax:
1. if(condition) {
2. statement 1; //executes when condition is true
3. }
4. else{
5. statement 2; //executes when condition is false
6. }
Student.java
1. public class Student {
2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y < 10) {
6. System.out.println("x + y is less than 10");
7. } else {
8. System.out.println("x + y is greater than 20");
9. }
10. }
11. }
Output:
x + y is greater than 20
3) if-else-if ladder:
1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. }
4. else if(condition 2) {
5. statement 2; //executes when condition 2 is true
6. }
7. else {
8. statement 2; //executes when all the conditions are false
9. }
Output:
Delhi
4. Nested if-statement
1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. if(condition 2) {
4. statement 2; //executes when condition 2 is true
5. }
6. else{
7. statement 2; //executes when condition 2 is false
8. }
9. }
Student.java
Output:
Delhi
Switch Statement:
In Java, Switch statements
are similar to if-else-if statements. The switch statement contains multiple blocks of code called
cases and a single case is executed based on the variable which is being switched. The switch
statement is easier to use instead of if-else-if statements. It also enhances the readability of the
program.
o The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of
expression. It is optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
o While using switch statements, we must notice that the case expression will be of
the same type as the variable. However, it will also be a constant value.
1. switch (expression){
2. case value1:
3. statement1;
4. break;
5. .
6. .
7. .
8. case valueN:
9. statementN;
10. break;
11. default:
12. default statement;
13. }
Consider the following example to understand the flow of the switch statement.
Student.java
Output:
While using switch statements, we must notice that the case expression will be of the
same type as the variable. However, it will also be a constant value. The switch permits
only int, string, and Enum type variables to be used.
Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while
some condition evaluates to true. However, loop statements are used to execute the set
of instructions in a repeated order. The execution of the set of instructions depends
upon a particular condition.
In Java, we have three types of loops that execute similarly. However, there are
differences in their syntax and condition checking time.
1. for loop
2. while loop
3. do-while loop
is similar to C
and C++
. It enables us to initialize the loop variable, check the condition, and increment/decrement in a
single line of code. We use the for loop only when we exactly know the number of times, we
want to execute the block of code.
1. for(initialization, condition, increment/decrement) {
2. //block of statements
3. }
Consider the following example to understand the proper functioning of the for loop in
java.
Calculation.java
Output:
Consider the following example to understand the functioning of the for-each loop in
Java.
Calculation.java
Output:
Java
C
C++
Python
JavaScript
It is also known as the entry-controlled loop since the condition is checked at the start
of the loop. If the condition is true, then the loop body will be executed; otherwise, the
statements after the loop will be executed.
1. while(condition){
2. //looping statements
3. }
The flow chart for the while loop is given in the following image.
Calculation .java
1. public class Calculation {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. System.out.println("Printing the list of first 10 even numbers \n");
6. while(i<=10) {
7. System.out.println(i);
8. i = i + 2;
9. }
10. }
11. }
Output:
0
2
4
6
8
10
checks the condition at the end of the loop after executing the loop statements. When the number
of iteration is not known and we have to execute the loop at least once, we can use do-while
loop.
It is also known as the exit-controlled loop since the condition is not checked in
advance. The syntax of the do-while loop is given below.
1. do
2. {
3. //statements
4. } while (condition);
The flow chart of the do-while loop is given in the following image.
Consider the following example to understand the functioning of the do-while loop in
Java.
Calculation.java
Output:
Jump Statements
Jump statements are used to transfer the control of the program to the specific
statements. In other words, jump statements transfer the execution control to the other
part of the program. There are two types of jump statements in Java, i.e., break and
continue.
is used to break the current flow of the program and transfer the control to the next statement
outside a loop or switch statement. However, it breaks only the inner loop in the case of the
nested loop.
The break statement cannot be used independently in the Java program, i.e., it can only
be written inside the loop or switch statement.
Consider the following example in which we have used the break statement with the for
loop.
BreakExample.java
Output:
0
1
2
3
4
5
6
Calculation.java
Output:
0
1
2
3
4
5
Java continue statement
Unlike break statement, the continue statement
doesn't break the loop, whereas, it skips the specific part of the loop and jumps to the next
iteration of the loop immediately.
Output:
0
1
2
3
5
1
2
3
5
2
3
5
Method Overloading
With method overloading, multiple methods can have the same name with
different parameters:
Example
intmyMethod(int x)
floatmyMethod(float x)
doublemyMethod(double x,double y)
Consider the following example, which has two methods that add numbers of
different type:
Example
staticintplusMethodInt(int x,int y){
return x + y;
return x + y;
publicstaticvoidmain(String[]args){
Instead of defining two methods that should do the same thing, it is better to
overload one.
In the example below, we overload the plusMethod method to work for
both int and double:
Example
staticintplusMethod(int x,int y){
return x + y;
return x + y;
publicstaticvoidmain(String[]args){
Example
1. public class Student {
2. //instance variables of the class
3. int id;
4. String name;
5.
6. Student(){
7. System.out.println("this a default constructor");
8. }
9.
10. Student(int i, String n){
11. id = i;
12. name = n;
13. }
14.
15. public static void main(String[] args) {
16. //object creation
17. Student s = new Student();
18. System.out.println("\nDefault Constructor values: \n");
19. System.out.println("Student Id : "+s.id + "\nStudent Name : "+s.name);
20.
21. System.out.println("\nParameterized Constructor values: \n");
22. Student student = new Student(10, "David");
23. System.out.println("Student Id : "+student.id + "\nStudent Name : "+student.name);
24. }
25. }
Let's understand what some of the different mechanisms for passing parameters to
functions are:
o value
o reference
o result
o value-result
o name
Nowadays, the two most used and common mechanisms are pass by value and pass by
reference. Let's discuss them:
Pass by Value: In the pass by value concept, the method is called by passing a value.
So, it is called pass by value. It does not affect the original parameter.
Pass by Reference: In the pass by reference concept, the method is called using an alias
or reference of the actual parameter. So, it is called pass by reference. It forwards the
unique identifier of the object to the method. If we made changes to the parameter's
instance member, it would affect the original value.
The primitive variables hold the actual values, whereas the non-primitive variables hold
the reference variable. However, both variables use stack memory to store the values.
See more about data types in Java
In Java, during the method invokation, a copy of each argument is created then passed
to the method.
In the case of primitive data types, it copies the value inside stack memory then pass it
to the method. In the case of non-primitive data types, it points a reference in stack
memory to actual data, which occurs in a heap. When we pass an object, it will copy a
reference from the stack memory and pass it to the callee method.
Bike.java
TestSpeed.java
Output:
Explanation: In the above program, when we create an instance of the class Bike using
the new operator, the instance of the class is created, and the variable holds the
reference of the memory where the object is saved.
While calling the swap() method, we have created two new variables o1 and o2, which
are pointing to the memory location of the apache and pulsar variable. Below is the
swap method implementation in the above program:
As we can see from the above code snippet, the values of o1 and o2 are changed. They
are copies of the apache and pulsar reference locations. So, it did not change the values
of apache and pulsar in the output.
PBVDemo.java
Output:
As we can see from the above output, the original values is not affected by the pass by
value mechanism.
1. class Operation2{
2. int data=50;
3.
4. void change(Operation2 op){
5. op.data=op.data+100;//changes will be in the instance variable
6. }
7.
8.
9. public static void main(String args[]){
10. Operation2 op=new Operation2();
11.
12. System.out.println("before change "+op.data);
13. op.change(op);//passing object
14. System.out.println("after change "+op.data);
15.
16. }
17. }
Output:before change 50
after change 150
Java Recursion
Recursion is the technique of making a function call itself. This technique
provides a way to break complicated problems down into simple problems which
are easier to solve.
Recursion may be a bit difficult to understand. The best way to figure out how it
works is to experiment with it.
Recursion Example
Adding two numbers together is easy to do, but adding a range of numbers is
more complicated. In the following example, recursion is used to add a range of
numbers together by breaking it down into the simple task of adding two
numbers:
Example
Use recursion to add all of the numbers up to 10.
publicclassMain{
publicstaticvoidmain(String[]args){
System.out.println(result);
publicstaticintsum(int k){
if(k >0){
}else{
return0;
Example Explained
When the sum() function is called, it adds parameter k to the sum of all
numbers smaller than k and returns the result. When k becomes 0, the function
just returns 0. When running, the program follows these steps
Since the function does not call itself when k is 0, the program stops there and
returns the result.
Java Strings
Strings are used for storing text.
Example
Create a variable of type String and assign it a value:
Example
String txt ="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Example
String txt ="Hello World";
Example
String txt ="Please locate where 'locate' occurs!";
System.out.println(txt.indexOf("locate"));// Outputs 7
String Concatenation
The + operator can be used between strings to combine them. This is
called concatenation:
Example
StringfirstName="John";
StringlastName="Doe";
System.out.println(firstName+" "+lastName);
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:
Example
StringfirstName="John ";
StringlastName="Doe";
System.out.println(firstName.concat(lastName));
Example
int x =10;
int y =20;
Example
String x ="10";
String y ="20";
String z = x + y;// z will be 1020 (a String)
If you add a number and a string, the result will be a string concatenation:
Example
String x ="10";
int y =20;
Special Characters
Because 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:
\\ \ Backslash
Example
String txt ="We are the so-called \"Vikings\" from the north.";
The sequence \' inserts a single quote in a string:
Example
String txt ="It\'s alright.";
Example
String txt ="The character \\ is called backslash.";
Code Result
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
Inheritance
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a
parent object. It is an important part of OOPs (Object Oriented programming system).
The idea behind inheritance in Java is that you can create new classes that are built upon existing classes.
When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover,
you can add new methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
The extends keyword indicates that you are making a new class that derives from an existing class. The
meaning of "extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is
called child or subclass.
Java Inheritance Example
As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The
relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a type of
Employee.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of Employee class i.e.
code reusability.
When one class inherits multiple classes, it is known as multiple inheritance. For Example:
Single Inheritance Example
When a class inherits another class, it is known as a single inheritance. In the example given below, Dog
class inherits the Animal class, so there is the single inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
barking...
eating...
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...
Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B
classes have the same method and you call it from child class object, there will be ambiguity to call the
method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2
classes. So whether you have same method or different, there will be compile time error.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were
Whenever you create the instance of subclass, an instance of parent class is created implicitly which is
referred by super reference variable.
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
Output:
black
white
In the above example, Animal and Dog both classes have a common property color. If we print color
property, it will print the color of current class by default. To access the parent property, we need to use
super keyword.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}
Output:
eating...
barking...
In the above example Animal and Dog both classes have eat() method if we call eat() method from Dog
class, it will call the eat() method of Dog class by default because priority is given to local.
To call the parent class method, we need to use super keyword.
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
Output:
animal is created
dog is created
Note: super() is added in each class constructor automatically by compiler if there is no super() or this().
As we know well that default constructor is provided by compiler automatically if there is no constructor.
But, it also adds super() as the first statement.
Another example of super keyword where super() is provided by the compiler implicitly.
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
System.out.println("dog is created");
}
}
class TestSuper4{
public static void main(String args[]){
Dog d=new Dog();
}}
Output:
animal is created
dog is created
class Person{
int id;
String name;
Person(int id,String name){
this.id=id;
this.name=name;
}
}
class Emp extends Person{
float salary;
Emp(int id,String name,float salary){
super(id,name);//reusing parent constructor
this.salary=salary;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
class TestSuper5{
public static void main(String[] args){
Emp e1=new Emp(1,"ankit",45000f);
e1.display();
}}
Output:
1 ankit 45000
In simple inheritance a subclass or derived class derives the properties from its parent class, but in multilevel inheritance a
subclass is derived from a derived class. One class inherits only single class. Therefore, in multilevel inheritance, every time
ladder increases by one. The lower most class will have the properties of all the super classes’.
It is common that a class is derived from another derived class.The class student serves as a base class for the derived class
marks, which in turn serves as a base class for the derived class percentage.The class marks is known as intermediates base
class since it provides a link for the inheritance between student and percentage.The chain is known as inheritance path. When
this type of situation occurs, each subclass inherits all of the features found in all of its super classes. In this case, percentage
inherits all aspects of marks and student.
class student
{
int rollno;
String name;
student(int r, String n)
{
rollno = r;
name = n;
}
void dispdatas()
{
System.out.println("Rollno = " + rollno);
System.out.println("Name = " + name);
}
}
Output:
Rollno = 102689
Name = RATHEESH
Total = 350
Percentage = 70
class A {
void funcA() {
System.out.println("This is class A");
}
}
class B extends A {
void funcB() {
System.out.println("This is class B");
}
}
class C extends B {
void funcC() {
System.out.println("This is class C");
}
}
public class Demo {
public static void main(String args[]) {
C obj = new C();
obj.funcA();
obj.funcB();
obj.funcC();
}
}
Output
This is class A
This is class B
This is class C
Method Overriding in Java
1. Understanding the problem without method overriding
If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in Java.
In other words, If a subclass provides the specific implementation of the method that has been declared by
one of its parent class, it is known as method overriding.
Let's understand the problem that we may face in the program if we don't use method overriding.
Output:
xVehicle is runningroblem is that I have to provide a specific implementation of run() method in subclass that is why
we use method overriding.
In this example, we have defined the run method in the subclass as defined in the parent class but it has
some specific implementation. The name and parameter of the method are the same, and there is IS-A
relationship between the classes, so there is method overriding.
Java uses the principle of ‘a superclass reference variable can refer to a subclass object’ to
resolve calls to overridden methods at run time. When a superclass reference is used to call an
overridden method, Java determines which version of the method to execute based on the type
of the object being referred to at the time call.
In other words, it is the type of object being referred to that determines which version of an
overridden method will be executed.
1. It allows Java to support overriding of methods, which are important for run-time
polymorphism.
2. It allows a class to define methods that will be shared by all its derived classes, while also
allowing these sub-classes to define their specific implementation of a few or all of those
methods.
3. It allows subclasses to incorporate their own methods and define their implementation.
class Fruits_Dispatch
{
public static void main(String args[])
{
Apple a = new Apple(); // object of Apple
Banana b = new Banana(); // object of Banana
Cherry c = new Cherry(); // object of Cherry
This program creates one superclass (i.e., class Apple) and two subclasses of it (i.e., Banana
class and Cherry class). Subclasses Banana and Cherry override the display() method declared in
Apple. Inside the main() method in class Fruits_Dispatch, objects of type Apple, Banana, and
Cherry are declared. A reference of type Apple, called ref, is declared.
The program then assigns a reference to each type of object to ref and uses the reference to
invoke display().
The version of display() executed is determined by the type of the object being referred to at the
time of the call.
. It can have abstract and non-abstract methods (method with the body).
Before learning the Java abstract class, let's understand the abstraction in Java first.
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only essential things to the user and hides the internal details, for example, sending
SMS where you type the text and send the message. You don't know the internal processing about the
message delivery
Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors
o It can have final methods which will force the subclass not to change the body of the method.
In this example, Bike is an abstract class that contains only one abstract method run. Its implementation is
provided by the Honda class.
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is called blank final
variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can
be static also which will be initialized in the static block only. We will have detailed learning of these. Let's
first learn the basics of final keyword.
There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed
because final variable once assigned a value can never be changed.
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
Output:Compile Time Error
Let's take an example, there is getObject() method that returns an object but it can be of any type like
Employee,Student etc, we can use Object class reference to refer that object. For example:
1. Object obj=getObject();//we don't know what object will be returned from this method
The Object class provides some common behaviors to all the objects such as object can be compared,
object can be cloned, object can be notified etc.
Packages:
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
If you are not using any IDE, you need to follow the syntax given below:
For example
1. javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any directory
name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep the package within
the same directory, you can use . (dot).
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The . represents the
folder.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
The import keyword is used to make the classes and interface of another package accessible to the current
package.
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
It is generally used when two packages have same class name e.g. java.util and java.sql packages contain
Date class.
If you import a package, all the classes and interface of that package will be imported excluding the classes
and interfaces of the subpackages. Hence, you need to import the subpackage as well.
Note: Sequence of the program must be package then import then class.
Package
A package is a collection of related Java entities (such as classes, interfaces, exceptions, errors and enums). Packages are
used for:
1. Resolving naming conflict of classes by prefixing the class name with a package name. For
example, com.zzz.Circle and com.yyy.Circle are two distinct classes. Although they share the same class
name Circle, but they belong to two different packages: com.zzz and com.yyy. These two classes can be used in
the same program and distinguished using the fully-qualified class name - package name plus class name. This
mechanism is called Namespace Management.
2. Access Control: Besides public and private, Java has two access control modifiers – protected and default – that
are related to package. A protected entity is accessible by classes in the same package and its subclasses. An entity
without access control modifier (i.e., default) is accessible by classes in the same package only.
3. For distributing a collection of reusable classes, usually in a format known as Java Archive (JAR) file.
Package Naming Convention
A package name is made up of the reverse of the Internet Domain Name (to ensure uniqueness) plus your own
organization's internal project name, separated by dots '.'. Package names are in lowercase. For example, suppose that
your Internet Domain Name is "zzz.com", you can name your package as "com.zzz.project1.subproject2".
The prefix "java" and "javax" are reserved for core Java packages and Java extensions, respectively.
Package Name & the Directory Structure
The package name is closely associated with the directory structure used to store the classes. For example, the
class Circle of package com.zzz.project1.subproject2 is stored as
"$BASE_DIR\com\zzz\project1\subproject2\Circle.class", where $BASE_DIR denotes the base directory of the
package. Clearly, the "dot" in the package name corresponds to a sub-directory of the file system.
The base directory ($BASE_DIR) could be located anywhere in the file system. Hence, the Java compiler and runtime must
be informed about the location of the $BASE_DIR so as to locate the classes. This is accomplished by an environment
variable called CLASSPATH. (CLASSPATH is similar to another environment variable PATH, which is used by the command shell
to search for the executable programs.)
In writing GUI programs, we are often confused by two packages: java.awt and java.awt.event. They are two distinct
packages sharing some common directory structures. The classes belonging to the package java.awt are stored in
directory "$BASE_DIR\java\awt\" while the classes of package java.awt.event are stored in directory
"$BASE_DIR\java\awt\event\". java.awt and java.awt.event are two distinct packages with common prefix and
directory structure. There is no such concept of sub-package in Java (i.e., java.awt.event is not a sub-package
of java.awt).
Creating Packages
To make a class as part of a package, you have to include the package statement as the first statement in the source file.
Example 1
We shall write a class called Circle in package com.yyy. It is a good practice to store the source files and the classes in
separate directories, typically called "src" and "classes". This is to facilitate the distribution of classes without the source
files.
Suppose that our base directory ($BASE_DIR) is d:\myProject. Create two sub-directories "src" and "classes".
Write the Circle.java and save under "src\com\yyy", as follows:
// src\com\yyy\Circle.java
package com.yyy;
// Compile
> javac -d classes src/com/yyy/Circle.java
// NOTE: you can use either forward slash or backward slash as directory separator in javac
o You need to load a class that is not present in the current directory or any sub-directories.
o You need to load a class that is not in a location specified by the extensions mechanism.
The CLASSPATH depends on what you are setting the CLASSPATH. The CLASSPATH has a directory name or
file name at the end. The following points describe what should be the end of the CLASSPATH.
o If a JAR or zip, the file contains class files, the CLASSPATH end with the name of the zip or JAR file.
o If class files placed in an unnamed package, the CLASSPATH ends with the directory that contains the class
files.
o If class files placed in a named package, the CLASSPATH ends with the directory that contains the root
package in the full package name, that is the first package in the full package name.
The default value of CLASSPATH is a dot (.). It means the only current directory searched. The default value
of CLASSPATH overrides when you set the CLASSPATH variable or using the -classpath command (for short
-cp). Put a dot (.) in the new setting if you want to include the current directory in the search path.
If CLASSPATH finds a class file which is present in the current directory, then it will load the class and use it,
irrespective of the same name class presents in another directory which is also included in the CLASSPATH.
If you want to set multiple classpaths, then you need to separate each CLASSPATH by a semicolon (;).
The third-party applications (MySQL and Oracle) that use the JVM can modify the CLASSPATH environment
variable to include the libraries they use. The classes can be stored in directories or archives files. The classes
of the Java platform are stored in rt.jar.
There are two ways to ways to set CLASSPATH: through Command Prompt or by setting Environment
Variable.
Step 4: If the CLASSPATH already exists in System Variables, click on the Edit button then put a semicolon
(;) at the end. Paste the Path of MySQL-Connector Java.jar file.
If the CLASSPATH doesn't exist in System Variables, then click on the New button and type Variable name
as CLASSPATH and Variable value as C:\Program Files\Java\jre1.8\MySQL-Connector Java.jar;.;
It is used by the operating system to find the It is used by Application ClassLoader to locate the .class file.
executable files (.exe).
You are required to include the directory You are required to include all the directories which contain .class and JAR
which contains .exe files.
PATH environment variable once set, cannot The CLASSPATH environment variable can be overridden by using the co
be overridden. cp or -CLASSPATH to both javac and java command.
In the above command, The set is an internal DOS command that allows the user to change the variable
value. CLASSPATH is a variable name. The variable enclosed in percentage sign (%) is an existing
environment variable. The semicolon is a separator, and after the (;) there is the PATH of rt.jar file.
members are accessible within the same class members only. Java has four access modifiers, and they are
as a container of data and methods. So, the access modifier decides the accessibility of class members
across the different packages.
In java, the accessibility of the members of a class or interface depends on its access specifiers. The
following table provides information about the visibility of both data members and methods.
□ The private members can be accessed only inside the same class.
□ The protected members are accessible to every child class (same package or other packages).
□ The default members are accessible within the same package but not outside the package.
Example
class ParentClass{
int a = 10;
public int b = 20;
protected int c = 30;
private int d = 40;
void showData() {
System.out.println("Inside ParentClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
void accessData() {
System.out.println("Inside ChildClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
//System.out.println("d = " + d); // private member can't be accessed
}
}
public class AccessModifiersExample {
imported, we can refer to all the classes of that package using their name directly.
The import statement must be after the package statement, and before any other statement.
Using an import statement, we may import a specific class or all the classes from a package.
□ Using one import statement, we may import only one package or a class.
□ Using an import statement, we can not import a class directly, but it must be a part of a package.
Using an importing statement, we can import a specific class. The following syntax is employed to import a
specific class.
Syntax
import packageName.ClassName;
Let's look at an import statement to import a built-in package and Scanner class.
Example
package myPackage;
import java.util.Scanner;
int i = read.nextInt();
In the above code, the class ImportingExample belongs to myPackage package, and it also importing a
class called Scanner from java.util package.
Using an importing statement, we can import all the classes of a package. To import all the classes of the
package, we use * symbol. The following syntax is employed to import all the classes of a package.
Syntax
import packageName.*;
Example
package myPackage;
import java.util.*;
int i = read.nextInt();
In the above code, the class ImportingExample belongs to myPackage package, and it also importing all
the classes like Scanner, Random, Stack, Vector, ArrayList, HashSet, etc. from the java.util package.
□ The import statement imports only classes of the package, but not sub-packages and its classes.
□ We may also import sub-packages by using a symbol '.' (dot) to separate parent package and sub-
package.
import java.util.*;
The above import statement util is a sub-package of java package. It imports all the classes
of util package only, but not classes of java package.
Interfaces:
In java, an interface is similar to a class, but it contains abstract methods and static final variables only.
The interface in Java is another mechanism to achieve abstraction.
We may think of an interface as a completely abstract class. None of the methods in the interface has an
implementation, and all the variables in the interface are constants.
All the methods of an interface, implemented by the class that implements it.
The interface in java enables java to support multiple-inheritance. An interface may extend only one
interface, but a class may implement any number of interfaces.
□ An interface is a container of abstract methods and static final variables.
□ An interface, implemented by a class. (class implements interface).
□ An interface may extend another interface. (Interface extends Interface).
□ An interface never implements another interface, or class.
□ A class may implement any number of interfaces.
□ We can not instantiate an interface.
□ Specifying the keyword abstract for interface methods is optional, it automatically added.
□ All the members of an interface are public by default.
Syntax
interface InterfaceName{
...
members declaration;
...
}
Example
interface HumanInterfaceExample {
In the above code defines an interface HumanInterfaceExample that contains two abstract methods
learn(), work() and one constant duration.
Every interface in Java is auto-completed by the compiler. For example, in the above example code, no
member is defined as public, but all are public automatically.
The above code automatically converted as follows.
Converted code
interface HumanInterfaceExample {
In the next tutorial, we will learn how a class implements an interface to make use of the interface concept.
The class uses a keyword implements to implement an interface. A class can implement any number of
interfaces. When a class wants to implement more than one interface, we use the implements keyword is
followed by a comma-separated list of the interfaces implemented by the class.
The following is the syntax for defineing a class that implements an interface.
Syntax
Example
interface Human {
In the above code defines an interface Human that contains two abstract methods learn(), work() and one constant
duration. The class Programmer implements the interface. As it implementing the Human interface it must provide the
When a class wants to implement more than one interface, we use the implements keyword is followed by
a comma-separated list of the interfaces implemented by the class.
The following is the syntax for defineing a class that implements multiple interfaces.
Syntax
Let's look at an example code to define a class that implements multiple interfaces.
Example
interface Human {
void learn(String str);
void work();
}
interface Recruitment {
boolean screening(int score);
boolean interview(boolean selected);
}
class Programmer implements Human, Recruitment {
public void learn(String str) {
System.out.println("Learn using " + str);
}
public boolean screening(int score) {
System.out.println("Attend screening test");
int thresold = 20;
if(score > thresold)
return true;
return false;
}
public boolean interview(boolean selected) {
System.out.println("Attend interview");
if(selected)
return true;
return false;
}
public void work() {
System.out.println("Develop applications");
}
}
public class HumanTest {
public static void main(String[] args) {
Programmer trainee = new Programmer();
trainee.learn("Coding");
trainee.screening(30);
trainee.interview(true);
trainee.work();
}
}
In the above code defines two interfaces Human and Recruitment, and a class Programmer implements both the
interfaces.
When we run the above program, it produce the following output.
Learn using coding
Attend Screening test
Attend Interview
Develop Applications
members defined in its parent interface too. The class which implements a child interface needs to provide
code for the methods defined in both child and parent interfaces, otherwise, it needs to be defined as
abstract class.
□ The class that implements child interface needs to provide code for all the methods defined in both child
Example
interface ParentInterface{
void parentMethod();
}
obj.childMethod();
obj.parentMethod();
defined inside another interface or a class is konwn as nested interface. The nested interface is also
refered as inner interface.
□ The nested interface declared within a class can be with any access modifier.
The nested interface cannot be accessed directly. We can only access the nested interface by using outer
interface or outer class name followed by dot( . ), followed by the nested interface name.
The nested interface that defined inside another interface must be accessed
as OuterInterface.InnerInterface.
Let's look at an example code to illustrate nested interfaces inside another interface.
Example
interface OuterInterface{
void outerMethod();
interface InnerInterface{
void innerMethod();
}
}
obj_1.outerMethod();
obj_2.innerMethod();
}
static final variables. The interface contains the static final variables. The variables defined in an interface
can not be modified by the class that implements the interface, but it may use as it defined in the interface.
□ If any variable in an interface is defined without public, static, and final keywords then, the compiler
automatically adds the same.
□ The class that implements an interface can not modify the interface variable, but it may use as it defined
in the interface.
Example
interface SampleInterface{
Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
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.
In this tutorial, we will learn about Java exceptions, it's types, and the difference between checked and
unchecked exceptions.
In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.
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:
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
Keyword Description
try The "try" keyword is used to specify a block where we should place an exception code. It means
we can't use try block alone. The try block must be followed by either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try block which
means we can't use catch block alone. It can be followed by finally block later.
finally The "finally" block is used to execute the necessary code of the program. It is executed whether
an exception is handled or not.
throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an
exception in the method. It doesn't throw an exception. It is always used with method signature.
JavaExceptionExample.java
Output:
In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch block.
1. String s=null;
2. System.out.println(s.length());//NullPointerException
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.
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be other
reasons to occur ArrayIndexOutOfBoundsException. Consider the following statements.
Exception Types:
exception is an event that occurs during the execution of a program and disrupts
the normal flow of the program's instructions. Bugs or errors that we don't want
and restrict our program's normal execution of code are referred to
as exceptions. In this section, we will focus on the types of exceptions in
Java and the differences between the two.
1. Built-in Exceptions
o Checked Exception
o Unchecked Exception
2. User-Defined Exceptions
Built-in Exception
Exceptions that are already available in Java libraries are referred to as built-in
exception. These exceptions are able to define the error situation so that we can
understand the reason of getting this error. It can be categorized into two broad
categories, i.e., checked exceptions and unchecked exception.
Checked Exception
Checked exceptions are called compile-time exceptions because these
exceptions are checked at compile-time by the compiler. The compiler ensures
whether the programmer handles the exception or not. The programmer should
have to handle the exception; otherwise, the system has shown a compilation
error.
CheckedExceptionExample.java
1. import java.io.*;
2. class CheckedExceptionExample {
3. public static void main(String args[]) {
4. FileInputStream file_data = null;
5. file_data = new FileInputStream("C:/Users/ajeet/OneDrive/Desktop/Hello.txt
");
6. int m;
7. while(( m = file_data.read() ) != -1) {
8. System.out.print((char)m);9.
}
10. file_data.close();
11. }
12. }
In the above code, we are trying to read the Hello.txt file and display its data or
content on the screen. The program throws the following exceptions:
Output:
How to resolve the error?
There are basically two ways through which we can solve these errors.
1) The exceptions occur in the main method. We can get rid from these
compilation errors by declaring the exception in the main method using the
throws We only declare the IOException, not FileNotFoundException, because of
the child-parent relationship. The IOException class is the parent class of
FileNotFoundException, so this exception will automatically cover by IOException.
We will declare the exception in the following way:
1. class Exception{
2. public static void main(String args[]) throws IOException {
3. ...
4. ...
5. }
If we compile and run the code, the errors will disappear, and we will see the data
of the file.
2) We can also handle these exception using try-catch However, the way which
we have used above is not correct. We have to a give meaningful message for
each exception type. By doing that it would be easy to understand the error. We
will use the try-catch block in the following way:
Exception.java
1. import java.io.*;
2. class Exception{
3. public static void main(String args[]) {
4. FileInputStream file_data = null;
5. try{
6. file_data = new FileInputStream("C:/Users/ajeet/OneDrive/Desktop/progr
ams/Hell.txt");
7. }catch(FileNotFoundException fnfe){
8. System.out.println("File Not Found!");9.
}
10. int m;
11. try{
12. while(( m = file_data.read() ) != -1) {
13. System.out.print((char)m);
14. }
15. file_data.close();
16. }catch(IOException ioe){
17. System.out.println("I/O error occurred: "+ioe);
18. }
19. }
20. }
We will see a proper error message "File Not Found!" on the console because
there is no such file in that location.
Unchecked Exceptions
The unchecked exceptions are just opposite to the checked exceptions. The
compiler will not check these exceptions at compile time. In simple words, if a
program throws an unchecked exception, and even if we didn't handle or declare
it, the program would not give a compilation error. Usually, it occurs when the
user provides bad data during the interaction with the program.
Note: The RuntimeException class is able to resolve all the unchecked exceptions
because of the child-parent relationship.
UncheckedExceptionExample1.java
1. class UncheckedExceptionExample1 {
2. public static void main(String args[])
3. {
4. int postive = 35;
5. int zero = 0;
6. int result = positive/zero;
7. //Give Unchecked Exception here.
8. System.out.println(result);
9. }
10. }
Output:
UncheckedException1.java
1. class UncheckedException1 {
2. public static void main(String args[])
3. {
4. int num[] ={10,20,30,40,50,60};
5. System.out.println(num[7]);
6. }
7. }
Output:
In the above code, we are trying to get the element located at position 7, but the
length of the array is 6. The code compiles successfully, but throws the
ArrayIndexOutOfBoundsException at runtime.
User-defined Exception
In Java, we already have some built-in exception classes like ArrayIndex
OutOfBounds Exception, NullPointer Exception, and Arithmetic Exception.
These exceptions are restricted to trigger on some predefined conditions. In Java,
we can write our own exception class by extends the Exception class. We can
throw our own exception on a particular condition using the throw keyword. For
creating a user-defined exception, we should have basic knowledge of the try-
catch block and throw keyword.
Let's write a Java program and create user-defined exception.
UserDefinedException.java
1. import java.util.*;
2. class UserDefinedException{
3. public static void main(String args[]){
4. try{
5. throw new NewException(5);6.
}
7. catch(NewException ex){
8. System.out.println(ex) ;9.
}
10. }
11. }
12. class NewException extends Exception{
13. int x;
14. NewException(int y) {
15. x=y;
16. }
17. public String toString(){
18. return ("Exception value = "+x) ;
19. }
20. }
Output:
Description:
In the UserDefined Exception class, we have added a try-catch block. In the try
section, we throw the exception, i.e., New Exception and pass an integer to it.
The value will be passed to the NewException class and return a message. We
catch that message in the catch block and show it on the screen.
Bugs or errors that we don't want and restrict the normal execution of the
programs are referred to as exceptions.
ArithmeticException,ArrayIndexOutOfBoundExceptions,ClassNotFoundExce
ptions etc. are come in the category of Built-in Exception. Sometimes, the built-
in exceptions are not sufficient to explain or describe certain situations. For
describing these situations, we have to create our own exceptions by creating an
exception class as a subclass of the Exception class. These types of exceptions
come in the category of User-Defined Exception.
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.
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:
But if the application programmer handles the exception, the normal flow of the
application is maintained, i.e., rest of the code is executed.
Example 1
TryCatchExample1.java
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.
Example 2
TryCatchExample2.java
As displayed in the above example, the rest of the code is executed, i.e., the rest
of the code statement is printed.
Example 3
In this example, we also kept the code in a try block that will not throw an
exception.
TryCatchExample3.java
Here, we can see that if an exception occurs in the try block, the rest of the block
code will not execute.
Example 4
Here, we handle the exception using the parent class exception.
TryCatchExample4.java
Points to remember
o At a time only one exception occurs and at a time only one catch block is
executed.
o All catch blocks must be ordered from most specific to most general, i.e.
catch for ArithmeticException must come before catch for Exception.
Example 1
Let's see a simple example of java multi-catch block.
MultipleCatchBlock1.java
16. }
17. catch(Exception e)
18. {
19. System.out.println("Parent Exception occurs");
20. }
21. System.out.println("rest of the code");
22. }
23. }
Output:
Arithmetic Exception occurs
rest of the code
Syntax:
1. ....
2. //main try block
3. try
4. {
5. statement 1;
6. statement 2;
7. //try catch block within another try block
8. try
9. {
10. statement 3;
11. statement 4;
12. //try catch block within nested try block
13. try
14. {
15. statement 5;
16. statement 6;
17. }
18. catch(Exception e2)
19. {
20. //exception message
21. }
22.
23. }
24. catch(Exception e1)
25. {
26. //exception message
27. }
28. }
29. //catch block of parent (outer) try block
30. catch(Exception e3)
31. {
32. //exception message
33. }
34. ....
NestedTryBlock.java
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.
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 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.
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.
Output:
The above code throw an unchecked exception. Similarly, we can also throw
unchecked and user defined exceptions.
throws Keyword
Any method capable of causing exceptions must list all the exceptions possible during its
execution, so that anyone calling that method gets a prior knowledge about which exceptions
to handle. A method can do so by using the throws keyword.
Syntax :
class Test
{
static void check() throws ArithmeticException
{
System.out.println("Inside check function");
throw new ArithmeticException("demo");
}
Class ExceptionTest
{
public static void main(String[] args)
{
int a[]= new int[2];
System.out.println("out of try");
try
{
System.out.println("Access invalid element"+ a[3]);
/* the above statement will throw ArrayIndexOutOfBoundException */
}
finally
{
System.out.println("finally is always executed.");
}
}
}
Output :
Out of try
finally is always executed.
Exception in thread main java. Lang. exception array Index out of bound
exception.
You can see in above example even if exception is thrown by the program, which is not
handled by catch block, still finally block will get executed.
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.
In this section, we will learn how custom exceptions are implemented and used in
Java programs.
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.
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
1. // class representing custom exception
2. class InvalidAgeException extends Exception
3. {
4. public InvalidAgeException (String str)
5. {
6. // calling the constructor of parent Exception
7. super(str);
8. }
9. }
10.
11. // class that uses custom exception InvalidAgeException
12. public class TestCustomException1
13. {
14.
15. // method to check the age
16. static void validate (int age) throws InvalidAgeException{
17. if(age < 18){
18.
19. // throw an object of user defined exception
20. throw new InvalidAgeException("age is not valid to vote");
21. }
22. else {
23. System.out.println("welcome to vote");
24. }
25. }
26.
27. // main method
28. public static void main(String args[])
29. {
30. try
31. {
32. // calling the method
33. validate(13);
34. }
35. catch (InvalidAgeException ex)
36. {
37. System.out.println("Caught the exception");
38.
39. // printing the message from InvalidAgeException object
40. System.out.println("Exception occured: " + ex);
41. }
42.
43. System.out.println("rest of the code...");
44. }
45. }
Output:
Stream based I/O:
The ByteStream classes are divided into two types of classes, i.e., InputStream and
OutputStream. These classes are abstract and the super classes of all the
Input/Output stream classes.
InputStream Class
The InputStream class provides methods to read bytes from a file, console or
memory. It is an abstract class and can't be instantiated; however, various classes
inherit the InputStream class and override its methods. The subclasses of
InputStream class are given in the following table.
SN Class Description
The InputStream class contains various methods to read the data from an input
stream. These methods are overridden by the classes that inherit the InputStream
class. However, the methods are given in the following table.
Play Videox
SN Method Description
2 int read (byte This method is used to read the specified buffer length
buffer []) bytes from the input and returns the total number of
bytes successfully read. It returns -1 once the end of the
input is encountered.
3 int read (byte This method is used to read the 'nBytes' bytes from the
buffer [], int buffer starting at a specified location, 'loc'. It returns the
loc, int nBytes) total number of bytes successfully read from the input.
It returns -1 once the end of the input is encountered.
4 int available () This method returns the number of bytes that are
available to read.
5 Void mark(int This method is used to mark the current position in the
nBytes) input stream until the specified nBytes are read.
6 void reset () This method is used to reset the input pointer to the
previously set mark.
7 long skip (long This method is used to skip the nBytes of the input
nBytes) stream and returns the total number of bytes that are
skipped.
SN Class Description
SN Method Description
1 void write (int i) This method is used to write the specified single
byte to the output stream.
4 void flush () It is used to flush the output stream and writes the
pending buffered bytes.
Example:
The following example uses the ByteArrayInputStream
to create an input stream from a byte array "content". We use the read() method to read the content from an input
stream. We have also used the write() method on a FileOutputStream object to write the byte array content in the file.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class InputOutputStreamExample {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
byte content[] = "Jtp is the best website to learn new technologies".getBytes();
ByteArrayInputStream inputStream = new ByteArrayInputStream(content);
inputStream.read(content);
File newFile = new File("/Users/MyUser/Desktop/MyNewFile.doc");
FileOutputStream outputStream = new FileOutputStream(newFile);
outputStream.write(content);
}
}
Output:
A new file MyNewFile.doc will be created on desktop with the content "Jtp is the best
website to learn new technologies".
However, the CharacterStream classes are mainly used to read characters from
the source and write them to the destination. For this purpose, the
CharacterStream classes are divided into two types of classes, I.e., Reader class
and Writer class.
Reader Class
Reader class
is used to read the 16-bit characters from the input stream. However, it is an abstract class and can't be instantiated, but
there are various subclasses that inherit the Reader class and override the methods of the Reader class. All methods of
the Reader class throw an IOException. The subclasses of the Reader class are given in the following table.
SN Class Description
2 int read(char This method is used to read from the specified buffer.
buffer[]) It returns the total number of characters successfully
read. It returns -1 if the end of the input is
encountered.
3 int read(char This method is used to read the specified nChars from
buffer[], int loc, the buffer at the specified location. It returns the total
int nChars) number of characters successfully read.
5 void reset() This method is used to reset the input pointer to the
previous set mark.
7 boolean ready() This method returns a boolean value true if the next
request of input is ready. Otherwise, it returns false.
Writer Class
Writer class is used to write 16-bit Unicode characters to the output stream. The
methods of the Writer class generate IOException. Like Reader class, Writer class
is also an abstract class that cannot be instantiated; therefore, the subclasses of
the Writer class are used to write the characters onto the output stream. The
subclasses of the Writer class are given in the below table.
SN Class Description
SN Method Description
1 void write() This method is used to write the data to the output
stream.
6 void flush () This method is used to flush the output stream and
writes the waiting buffered characters.
Java Console Class
The Java Console class is be used to get input from console. It provides methods
to read texts and passwords.
If you read password using Console class, it will not be displayed to the user.
The java.io.Console class is attached with system console internally. The Console
class is introduced since 1.5.
1. String text=System.console().readLine();
2. System.out.println("Text is: "+text);
1. Console c=System.console();
Java Console Example
1. import java.io.Console;
2. class ReadStringTest{
3. public static void main(String args[]){
4. Console c=System.console();
5. System.out.println("Enter your name: ");
6. String n=c.readLine();
7. System.out.println("Welcome "+n);
8. }
9. }
Output
Enter your name: Nakul Jain
Welcome Nakul Jain
Output
Enter password:
Password is: 123
Java File Class
The File class is an abstract representation of file and directory pathname. A
pathname can be either absolute or relative.
The File class have several methods for working with directories and files such as
creating new directories or files, deleting and renaming directories or files, listing
the contents of a directory etc.
Fields
Modifier Type Field Description
Constructors
Constructor Description
File(File parent, String It creates a new File instance from a parent abstract
child) pathname and a child pathname string.
File(String pathname) It creates a new File instance by converting the given
pathname string into an abstract pathname.
Useful Methods
Modifier Method Description
and Type
Output:
New File is created!
FileWriter(File file) Creates a new file. It gets file name in File object.
Methods of File Writer class
Method Description
1. package com.javatpoint;
2. import java.io.FileWriter;
3. public class FileWriterExample {
4. public static void main(String args[]){
5. try{
6. FileWriter fw=new FileWriter("D:\\testout.txt");
7. fw.write("Welcome to javapoint.");
8. fw.close();
9. }catch(Exception e){System.out.println(e);}
10. System.out.println("Success...");
11. }
12. }
Output:
Success...
testout.txt:
Welcome to javapoint.
1. package com.javatpoint;
2. import java.io.FileReader;
3. public class FileReaderExample {
4. public static void main(String args[])throws Exception{
5. FileReader fr=new FileReader("D:\\testout.txt");
6. int i;
7. while((i=fr.read())!=-1)
8. System.out.print((char)i);
9. fr.close();
10. }
11. }
Here, we are assuming that you have following data in "testout.txt" file:
Welcome to javaTpoint.
Output:
Welcome to javaTpoint.
Java - RandomAccessFile
This class
is used for reading and writing to random access file. A random access file behaves like a large array
, by moving the cursor we do the read write operations. If end-of-file is reached before the desired number of byte has
been read than EOFException is thrown
. It is a type of IOException.
Constructor
Constructor Description
Method
Modifier Method Method
and Type
Example
1. import java.io.IOException;
2. import java.io.RandomAccessFile;
3.
7. try {
11. e.printStackTrace();
12. }
13. }
14. private static byte[] readFromFile(String filePath, int position, int size)
17. file.seek(position);
19. file.read(bytes);
20. file.close();
22. }
23. private static void writeToFile(String filePath, String data, int position)
26. file.seek(position);
27. file.write(data.getBytes());
28. file.close();
29. }
30. }
The myFile.TXT contains text "This class is used for reading and writing to random access file."
If you read password using Console class, it will not be displayed to the user.
The java.io.Console class is attached with system console internally. The Console
class is introduced since 1.5.
1. String text=System.console().readLine();
2. System.out.println("Text is: "+text);
1. Console c=System.console();
Output
Enter your name: Nakul Jain
Welcome Nakul Jain
Java Console Example to read password
1. import java.io.Console;
2. class ReadPasswordTest{
3. public static void main(String args[]){
4. Console c=System.console();
5. System.out.println("Enter password: ");
6. char[] ch=c.readPassword();
7. String pass=String.valueOf(ch);//converting char array into string
8. System.out.println("Password is: "+pass);
9. }
10. }
Output
Enter password:
Password is: 123
We must have to implement the Serializable interface for serializing the object.
Advantages of Java Serialization
It is mainly used to travel object's state on the network (that is known as
marshalling).
java.io.Serializable interface
Serializable is a marker interface (has no data member and method). It is used to
"mark" Java classes so that the objects of these classes may get a certain
capability. The Cloneable and Remote are also marker interfaces.
The Serializable interface must be implemented by the class whose object needs
to be persisted.
Student.java
1. import java.io.Serializable;
2. public class Student implements Serializable{
3. int id;
4. String name;
5. public Student(int id, String name) {
6. this.id = id;
7. this.name = name;
8. }
9. }
In the above example, Student class implements Serializable interface. Now its
objects can be converted into stream. The main class implementation of is
showed in the next code.
ObjectOutputStream class
The ObjectOutputStream class is used to write primitive data types, and Java
objects to an OutputStream. Only objects that support the java.io.Serializable
interface can be written to streams.
Constructor
Important Methods
Method Description
Constructor
Important Methods
Method Description
Persist.java
1. import java.io.*;
2. class Persist{
3. public static void main(String args[]){
4. try{
5. //Creating the object
6. Student s1 =new Student(211,"ravi");
7. //Creating stream and writing the object
8. FileOutputStream fout=new FileOutputStream("f.txt");
9. ObjectOutputStream out=new ObjectOutputStream(fout);
10. out.writeObject(s1);
11. out.flush();
12. //closing the stream
13. out.close();
14. System.out.println("success");
15. }catch(Exception e){System.out.println(e);}
16. }
17. }
Output:
success
Depersist.java
1. import java.io.*;
2. class Depersist{
3. public static void main(String args[]){
4. try{
5. //Creating stream to read the object
6. ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
7. Student s=(Student)in.readObject();
8. //printing the data of the serialized object
9. System.out.println(s.id+" "+s.name);
10. //closing the stream
11. in.close();
12. }catch(Exception e){System.out.println(e);}
13. }
14. }
Output:
211 ravi
Java Enums
The Enum in Java is a data type which contains a fixed set of constants.
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.
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.
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.
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
o Enum improves type safety
o Enum can be easily used in switch
o Enum can be traversed
o Enum can have fields, constructors and methods
o Enum may implement many interfaces but cannot extend any class because
it internally extends Enum class
Let us see another example of Java enum where we are using value(), valueOf(),
and ordinal() methods of Java enum.
1. class EnumExample1{
2. //defining enum within class
3. public enum Season { WINTER, SPRING, SUMMER, FALL }
4. //creating the main method
5. public static void main(String[] args) {
6. //printing all enum
7. for (Season s : Season.values()){
8. System.out.println(s);
9. }
10. System.out.println("Value of WINTER is: "+Season.valueOf("WINTER"));
11. System.out.println("Index of WINTER is: "+Season.valueOf("WINTER").ordina
l());
12. System.out.println("Index of SUMMER is: "+Season.valueOf("SUMMER").ordi
nal());
13.13.
14. }}
Output:
WINTER
SPRING
SUMMER
FALL
Value of WINTER is: WINTER
Index of WINTER is: 0
Index of SUMMER is: 2
Note: Java compiler internally adds values(), valueOf() and ordinal() methods within
the enum at compile time. It internally creates a static and final class for the enum.
What is the purpose of the values() method in the enum?
The Java compiler internally adds the values() method when it creates an enum.
The values() method returns an array containing all the values of the enum.
Or,
Output:
WINTER
1. enum Season {
2. WINTER, SPRING, SUMMER, FALL;
3. public static void main(String[] args) {
4. Season s=Season.WINTER;
5. System.out.println(s);
6. }
7. }
Output:
WINTER
Output:
WINTER 5
SPRING 10
SUMMER 15
FALL 20
Constructor of enum type is private. If you don't declare private compiler internally
creates private constructor.
1. enum Season{
2. WINTER(10),SUMMER(20);
3. private int value;
4. Season(int value){
5. this.value=value;
6. }
7. }
Internal code generated by the compiler for the above
example of enum type
1. final class Season extends Enum
2. {
3. public static Season[] values()
4. {
5. return (Season[])$VALUES.clone();
6. }
7. public static Season valueOf(String s)
8. {
9. return (Season)Enum.valueOf(Season, s);
10. }
11. private Season(String s, int i, int j)
12. {
13. super(s, i);
14. value = j;
15. }
16. public static final Season WINTER;
17. public static final Season SUMMER;
18. private int value;
19. private static final Season $VALUES[];
20. static
21. {
22. WINTER = new Season("WINTER", 0, 10);
23. SUMMER = new Season("SUMMER", 1, 20);
24. $VALUES = (new Season[] {
25. WINTER, SUMMER
26. });
27. }
28. }
Can we create the instance of Enum by new keyword?
No, because it contains private constructors only.
1. class EnumExample5{
2. enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SA
TURDAY}
3. public static void main(String args[]){
4. Day day=Day.MONDAY;
5.
6. switch(day){
7. case SUNDAY:
8. System.out.println("sunday");
9. break;
10. case MONDAY:
11. System.out.println("monday");
12. break;
13. default:
14. System.out.println("other day");
15. }
16. }}
Output:
monday
Autoboxing and Unboxing:
The automatic conversion of primitive data types into its equivalent Wrapper type
is known as boxing and opposite operation is known as unboxing. This is the new
feature of Java5. So java programmer doesn't need to write the conversion code.
1. class UnboxingExample1{
2. public static void main(String args[]){
3. Integer i=new Integer(50);
4. int a=i;
5.
6. System.out.println(a);
7. }
8. }
9.
Output:
50
1.
2. class UnboxingExample2{
3. public static void main(String args[]){
4. Integer i=new Integer(50);
5.
6. if(i<100){ //unboxing internally
7. System.out.println(i);
8. }
9. }
10. }
11.
Output:50
Generics in Java
The Java Generics programming is introduced in J2SE 5 to deal with type-safe
objects. It makes the code stable by detecting the bugs at compile time.
Before generics, we can store any type of objects in the collection, i.e., non-
generic. Now generics force the java programmer to store a specific type of
objects.
Advantage of Java Generics
There are mainly 3 advantages of generics. They are as follows:
1. ClassOrInterface<Type>
1. ArrayList<String>
1. import java.util.*;
2. class TestGenerics1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();
5. list.add("rahul");
6. list.add("jai");
7. //list.add(32);//compile time error
8.
9. String s=list.get(1);//type casting is not required
10. System.out.println("element is: "+s);
11.
12. Iterator<String> itr=list.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. }
17. }
1. import java.util.*;
2. class TestGenerics1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();
5. list.add("rahul");
6. list.add("jai");
7. //list.add(32);//compile time error
8.
9. String s=list.get(1);//type casting is not required
10. System.out.println("element is: "+s);
11.
12. Iterator<String> itr=list.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. }
17. }
Output:
element is: jai
rahul
jai
Generic class
A class that can refer to any type is known as a generic class. Here, we are using
the T type parameter to create the generic class of specific type.
Let's see a simple example to create and use the generic class.
1. class TestGenerics3{
2. public static void main(String args[]){
3. MyGen<Integer> m=new MyGen<Integer>();
4. m.add(2);
5. //m.add("vivek");//Compile time error
6. System.out.println(m.get());
7. }}
Output
2
UNIT-IV Multi Threading
Multithreading in Java is a process of executing multiple threads simultaneously.
A Thread is a very light-weighted process, or we can say the smallest part of the
process that allows a program to operate more efficiently by running multiple tasks
simultaneously.
Thread Model
Just like a process, a thread exists in several states. These states are as follows:
Thread Class
A Thread class has several methods and constructors which allow us to perform
various operations on a thread. The Thread class extends the Object class.
The Object class implements the Runnable interface. The thread class has the
following constructors that are used to perform various operations.
o Thread()
o Thread(Runnable, String name)
o Thread(Runnable target)
o Thread(ThreadGroup group, Runnable target, String name)
o Thread(ThreadGroup group, Runnable target)
o Thread(ThreadGroup group, String name)
o Thread(ThreadGroup group, Runnable target, String name, long
stackSize)
start() method
The method is used for starting a thread that we have newly created. It starts a new
thread with a new callstack. After executing the start() method, the thread changes
the state from New to Runnable. It executes the run() method when the thread gets
the correct time to execute it.
ThreadExample1.java
Output:
In Java, we can also create a thread by implementing the runnable interface. The
runnable interface provides us both the run() method and the start() method.
Let's takes an example to understand how we can create, start and run the thread
using the runnable interface.
ThreadExample2.java
Output:
Thread class:
Thread class provide constructors and methods to create and perform operations on
a thread.Thread class extends Object class and implements Runnable interface.
o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)
Runnable interface:
B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 7
The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread. Runnable interface have only one method
named run().
Starting a thread:
The start() method of Thread class is used to start a newly created thread. It
performs the following tasks:
FileName: Multi.java
Output:
thread is running...
FileName: Multi3.java
Output:
thread is running...
If you are not extending the Thread class, your class object would not be treated as
a thread object. So you need to explicitly create the Thread class object. We are
passing the object of your class that implements Runnable so that your class run()
method may execute.
Using the Thread Class: Thread(String Name)
We can directly use the Thread class to spawn new threads using the constructors
defined above.
FileName: MyThread1.java
Output:
My first thread
FileName: MyThread2.java
Output:
My new thread
Now the thread is running ...
Each thread has a priority. Priorities are represented by a number between 1 and 10.
In most cases, the thread scheduler schedules the threads according to their priority
(known as preemptive scheduling). But it is not guaranteed because it depends on
JVM specification that which scheduling it chooses. Note that not only JVM a Java
programmer can also assign the priorities of a thread explicitly in a Java program.
Let's discuss the setter and getter method of the thread priority.
FileName: ThreadPriority.java
Output:
Priority of the thread th1 is : 5
Priority of the thread th2 is : 5
Priority of the thread th2 is : 5
Priority of the thread th1 is : 6
Priority of the thread th2 is : 3
Priority of the thread th3 is : 9
Currently Executing The Thread : main
Priority of the main thread is : 5
Priority of the main thread is : 10
We know that a thread with high priority will get preference over lower priority
threads when it comes to the execution of threads. However, there can be other
FileName: ThreadPriorityExample1.java
Output:
Priority of the main thread is : 7
Priority of the thread th1 is : 7
Explanation: If there are two threads that have the same priority, then one can not
predict which thread will get the chance to execute first. The execution then is
dependent on the thread scheduler's algorithm (First Come First Serve, Round-
Robin, etc.)
Example of IllegalArgumentException
We know that if the value of the parameter newPriority of the method getPriority()
goes out of the range (1 to 10), then we get the IllegalArgumentException. Let's
observe the same with the help of an example.
FileName: IllegalArgumentException.java
Synchronization in Java
Java Synchronization is better option where we want to allow only one thread to
access the shared resource.
Types of Synchronization
1. Process Synchronization
2. Thread Synchronization
Thread Synchronization
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. Static synchronization.
2. Cooperation (Inter-thread communication in java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing
data. It can be achieved by using the following three ways:
TestSynchronization1.java
class Table{
void printTable(int n){//method not synchronized
B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 17
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
class TestSynchronization1{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 18
t1.start();
t2.start();
}
}
Output:
5
100
10
200
15
300
20
400
25
500
When a thread invokes a synchronized method, it automatically acquires the lock for
that object and releases it when the thread completes its task.
TestSynchronization2.java
5
10
15
20
25
100
200
In this program, we have created the two threads by using the anonymous class, so
less coding is required.
TestSynchronization3.java
Output:
5
10
15
20
25
100
200
300
400
500
o wait()
o notify()
o notifyAll()
1) wait() method
The wait() method causes current thread to release the lock and wait until either
another thread invokes the notify() method or the notifyAll() method for this object,
or a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from the
synchronized method only otherwise it will throw exception.
2) notify() method
The notify() method wakes up a single thread that is waiting on this object's
monitor. If any threads are waiting on this object, one of them is chosen to be
awakened. The choice is arbitrary and occurs at the discretion of the
implementation.
Syntax:
3) notifyAll() method
Syntax:
1. public final void notifyAll()
Understanding the process of inter-thread communication
Why wait(), notify() and notifyAll() methods are defined in Object class not
Thread class?
Let's see the important differences between wait and sleep methods.
wait() sleep()
The wait() method releases the lock. The sleep() method doesn't release the
lock.
Test.java
class Customer{
int amount=10000;
synchronized void withdraw(int amount){
System.out.println("going to withdraw...");
if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount){
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}.start();
new Thread(){
public void run(){c.deposit(10000);}
}.start();
}}
B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 25
Output:
going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
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).
Collection Interface
The Collection interface is the root interface of the Java collections framework.
There is no direct implementation of this interface. However, it is implemented
through its subinterfaces like List, Set, and Queue.
For example, the ArrayList class implements the List interface which is a
subinterface of the Collection Interface.
1. List Interface
The List interface is an ordered collection that allows us to add and remove elements like an
array.
2. Set Interface
The Set interface allows us to store elements in different sets similar to the set in mathematics. It
3. Queue Interface
The Queue interface is used when we want to store and access elements in First In, First Out
(FIFO) manner.
Collection Classes:
Array List:
Java ArrayList class uses a dynamic array for storing the elements. It is like an array,
but there is no size limit. We can add or remove elements anytime. So, it is much
more flexible than the traditional array. It is found in the java.util package. It is like
the Vector in C++.
As shown in the above diagram, the Java ArrayList class extends AbstractList class
which implements the List interface. The List interface extends the Collection and
Iterable interfaces in hierarchical order.
Constructors of ArrayList
Constructor Description
Methods of ArrayList
Method Description
In a generic collection, we specify the type in angular braces. Now ArrayList is forced
to have the only specified type of object in it. If you try to add another type of
object, it gives a compile-time error.
For more information on Java generics, click here Java Generics Tutorial.
import java.util.*;
public class ArrayListExample1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Mango");//Adding object in arraylist
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Printing the arraylist object
System.out.println(list);
}
}
Output:
[Mango, Apple, Banana, Grapes]
FileName: ArrayListExample2.java
import java.util.*;
public class ArrayListExample2{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Mango");//Adding object in arraylist
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Traversing list through Iterator
Iterator itr=list.iterator();//getting the Iterator
while(itr.hasNext()){//check if iterator has the elements
System.out.println(itr.next());//printing the element and move to next
}
}
}
Output:
Mango
Apple
Banana
Grapes
FileName: ArrayListExample3.java
import java.util.*;
public class ArrayListExample3{
Output:
Mango
Apple
Banana
Grapes
FileName: ArrayListExample4.java
import java.util.*;
public class ArrayListExample4{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Mango");
al.add("Apple");
al.add("Banana");
al.add("Grapes");
//accessing the element
Output:
Returning element: Apple
Mango
Dates
Banana
Grapes
Java LinkedList class uses a doubly linked list to store the elements. It provides a
linked-list data structure. It inherits the AbstractList class and implements List and
Deque interfaces.
Constructor Description
Method Description
import java.util.*;
public class LinkedList2{
public static void main(String args[]){
LinkedList<String> ll=new LinkedList<String>();
System.out.println("Initial list of elements: "+ll);
ll.add("Ravi");
ll.add("Vijay");
ll.add("Ajay");
System.out.println("After invoking add(E e) method: "+ll);
//Adding an element at the specific position
ll.add(1, "Gaurav");
System.out.println("After invoking add(int index, E element) method: "+ll);
B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 37
LinkedList<String> ll2=new LinkedList<String>();
ll2.add("Sonoo");
ll2.add("Hanumat");
//Adding second list elements to the first list
ll.addAll(ll2);
System.out.println("After invoking addAll(Collection<? extends E> c) method:
"+ll);
LinkedList<String> ll3=new LinkedList<String>();
ll3.add("John");
ll3.add("Rahul");
//Adding second list elements to the first list at specific position
ll.addAll(1, ll3);
System.out.println("After invoking addAll(int index, Collection<? extends E> c)
method: "+ll);
//Adding an element at the first position
ll.addFirst("Lokesh");
System.out.println("After invoking addFirst(E e) method: "+ll);
//Adding an element at the last position
ll.addLast("Harsh");
System.out.println("After invoking addLast(E e) method: "+ll);
}
}
Initial list of elements: []
After invoking add(E e) method: [Ravi, Vijay, Ajay]
After invoking add(int index, E element) method: [Ravi, Gaurav, Vijay, Ajay]
After invoking addAll(Collection<? extends E> c) method:
[Ravi, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addAll(int index, Collection<? extends E> c) method:
[Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addFirst(E e) method:
[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addLast(E e) method:
[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat, Harsh]
Java HashSet
Java HashSet class is used to create a collection that uses a hash table for storage. It
inherits the AbstractSet class and implements Set interface.
import java.util.*;
class HashSet1{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet();
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");
set.add("Five");
Iterator<String> i=set.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}
Five
One
Four
Two
Three
import java.util.*;
B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 44
class HashSet2{
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());
}
}
}
Ajay
Vijay
Ravi
import java.util.*;
class HashSet3{
public static void main(String args[]){
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Arun");
set.add("Sumit");
System.out.println("An initial list of elements: "+set);
//Removing specific element from HashSet
Constructor Description
Method Description
import java.util.*;
class TreeSet1{
public static void main(String args[]){
//Creating and adding elements
TreeSet<String> al=new TreeSet<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
//Traversing elements
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ajay
Ravi
Vijay
FileName: TreeSet2.java
import java.util.*;
Output:
Traversing element through Iterator in descending order
Vijay
Ravi
Ajay
Traversing element through NavigableSet in descending order
Vijay
Ravi
Ajay
PriorityQueue Class
PriorityQueue is also class that is defined in the collection framework that gives us a
way for processing the objects on the basis of priority. It is already described that
the insertion and deletion of objects follows FIFO pattern in the Java queue.
However, sometimes the elements of the queue are needed to be processed
according to the priority, that's where a PriorityQueue comes into action.
import java.util.*;
class TestCollection12{
public static void main(String args[]){
PriorityQueue<String> queue=new PriorityQueue<String>();
queue.add("Amit");
queue.add("Vijay");
queue.add("Karan");
queue.add("Jai");
queue.add("Rahul");
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:
ArrayDeque Hierarchy
The hierarchy of ArrayDeque class is given in the figure displayed at the right side of
the page.
import java.util.*;
public class ArrayDequeExample {
public static void main(String[] args) {
//Creating Deque and adding elements
Deque<String> deque = new ArrayDeque<String>();
deque.add("Ravi");
B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 55
deque.add("Vijay");
deque.add("Ajay");
//Traversing elements
for (String str : deque) {
System.out.println(str);
}
}
}
Output:
Ravi
Vijay
Ajay
FileName: DequeExample.java
import java.util.*;
public class DequeExample {
public static void main(String[] args) {
Deque<String> deque=new ArrayDeque<String>();
deque.offer("arvind");
deque.offer("vimal");
deque.add("mukul");
deque.offerFirst("jai");
System.out.println("After offerFirst Traversal...");
for(String s:deque){
System.out.println(s);
}
//deque.poll();
//deque.pollFirst();//it is same as poll()
deque.pollLast();
System.out.println("After pollLast() Traversal...");
Output:
After offerFirst Traversal...
jai
arvind
vimal
mukul
After pollLast() Traversal...
jai
arvind
vimal
Points to remember
o A Hashtable is an array of a list. Each list is known as a bucket. The position of
the bucket is identified by calling the hashcode() method. A Hashtable contains
values based on the key.
o Java Hashtable class contains unique elements.
o Java Hashtable class doesn't allow null key or value.
o Java Hashtable class is synchronized.
o The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75.
Constructor Description
Method Description
V get(Object key) This method returns the object that contains the value
associated with the key.
V remove(Object It is used to remove the key and its value. This method
key) returns the value associated with the key.
int size() This method returns the number of entries in the hash
table.
Output:
103 Rahul
102 Ravi
101 Vijay
100 Amit
import java.util.*;
public class Hashtable2 {
public static void main(String args[]) {
Hashtable<Integer,String> map=new Hashtable<Integer,String>();
map.put(100,"Amit");
map.put(102,"Ravi");
map.put(101,"Vijay");
map.put(103,"Rahul");
System.out.println("Before remove: "+ map);
// Remove value for key 102
map.remove(102);
System.out.println("After remove: "+ map);
}
}
Output:
Before remove: {103=Rahul, 102=Ravi, 101=Vijay, 100=Amit}
After remove: {103=Rahul, 101=Vijay, 100=Amit}
import java.util.*;
class Hashtable3{
public static void main(String args[]){
Hashtable<Integer,String> map=new Hashtable<Integer,String>();
map.put(100,"Amit");
map.put(102,"Ravi");
map.put(101,"Vijay");
map.put(103,"Rahul");
//Here, we specify the if and else statement as arguments of the method
System.out.println(map.getOrDefault(101, "Not Found"));
Output:
Vijay
Not Found
import java.util.*;
class Hashtable4{
public static void main(String args[]){
Hashtable<Integer,String> map=new Hashtable<Integer,String>();
map.put(100,"Amit");
map.put(102,"Ravi");
map.put(101,"Vijay");
map.put(103,"Rahul");
System.out.println("Initial Map: "+map);
//Inserts, as the specified pair is unique
map.putIfAbsent(104,"Gaurav");
System.out.println("Updated Map: "+map);
//Returns the current value, as the specified pair already exist
map.putIfAbsent(101,"Vijay");
System.out.println("Updated Map: "+map);
}
}
Output:
Initial Map: {103=Rahul, 102=Ravi, 101=Vijay, 100=Amit}
Updated Map: {104=Gaurav, 103=Rahul, 102=Ravi, 101=Vijay, 100=Amit}
Updated Map: {104=Gaurav, 103=Rahul, 102=Ravi, 101=Vijay, 100=Amit}
The properties object contains key and value pair both as a string. The
java.util.Properties class is the subclass of Hashtable.
It can be used to get property value based on the property key. The Properties class
provides methods to get data from the properties file and store data into the
properties file. Moreover, it can be used to get the properties of a system.
Method Description
Method Description
public void load(InputStream is) It loads data from the InputStream object
To get information from the properties file, create the properties file first.
db.properties
1. user=system
2. password=oracle
Now, let's create the java class to read the data from the properties file.
Test.java
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args)throws Exception{
FileReader reader=new FileReader("db.properties");
Properties p=new Properties();
p.load(reader);
System.out.println(p.getProperty("user"));
System.out.println(p.getProperty("password"));
}
}
Output:system
oracle
Now if you change the value of the properties file, you don't need to recompile the
java class. That means no maintenance problem.
By System.getProperties() method we can get all the properties of the system. Let's
create the class that gets information from the system properties.
Test.java
import java.util.*;
import java.io.*;
In Java, Stack is a class that falls under the Collection framework that extends
the Vector class. It also implements interfaces List, Collection, Iterable, Cloneable,
Serializable. It represents the LIFO stack of objects. Before using the Stack class, we
must import the java.util package. The stack class arranged in the Collections
framework hierarchy, as shown below.
The Stack class contains only the default constructor that creates an empty stack.
1. public Stack()
Creating a Stack
If we want to create a stack, first, import the java.util package and create an object of
the Stack class.
Or
Where type denotes the type of stack like Integer, String, etc.
We can perform push, pop, peek and search operation on the stack. The Java Stack
class provides mainly five methods to perform these operations. Along with this, it
also provides all the methods of the Java Vector class.
The empty() method of the Stack class check the stack is empty or not. If the stack
is empty, it returns true, else returns false. We can also use the isEmpty() method of
the Vector class.
Syntax
Returns: The method returns true if the stack is empty, else returns false.
In the following example, we have created an instance of the Stack class. After that,
we have invoked the empty() method two times. The first time it
returns true because we have not pushed any element into the stack. After that, we
have pushed elements into the stack. Again we have invoked the empty() method
that returns false because the stack is not empty.
StackEmptyMethodExample.java
import java.util.Stack;
public class StackEmptyMethodExample
{
public static void main(String[] args)
{
//creating an instance of Stack class
Stack<Integer> stk= new Stack<>();
// checking stack is empty or not
boolean result = stk.empty();
B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 66
System.out.println("Is the stack empty? " + result);
// pushing elements into stack
stk.push(78);
stk.push(113);
stk.push(90);
stk.push(120);
//prints elements of the stack
System.out.println("Elements in Stack: " + stk);
result = stk.empty();
System.out.println("Is the stack empty? " + result);
}
}
Output:
Is the stack empty? true
Elements in Stack: [78, 113, 90, 120]
Is the stack empty? false
The method inserts an item onto the top of the stack. It works the same as the
method addElement(item) method of the Vector class. It passes a parameter item to
be pushed into the stack.
Syntax
Returns: The method returns the argument that we have passed as a parameter.
The method removes an object at the top of the stack and returns the same object.
It throws EmptyStackException if the stack is empty.
Syntax
B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 67
1. public E pop()
Let's implement the stack in a Java program and perform push and pop operations.
StackPushPopExample.java
import java.util.*;
public class StackPushPopExample
{
public static void main(String args[])
{
//creating an object of Stack class
Stack <Integer> stk = new Stack<>();
System.out.println("stack: " + stk);
//pushing elements into the stack
pushelmnt(stk, 20);
pushelmnt(stk, 13);
pushelmnt(stk, 89);
pushelmnt(stk, 90);
pushelmnt(stk, 11);
pushelmnt(stk, 45);
pushelmnt(stk, 18);
//popping elements from the stack
popelmnt(stk);
popelmnt(stk);
//throws exception if the stack is empty
try
{
popelmnt(stk);
}
catch (EmptyStackException e)
B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 68
{
System.out.println("empty stack");
}
}
//performing push operation
static void pushelmnt(Stack stk, int x)
{
//invoking push() method
stk.push(new Integer(x));
System.out.println("push -> " + x);
//prints modified stack
System.out.println("stack: " + stk);
}
//performing pop operation
static void popelmnt(Stack stk)
{
System.out.print("pop -> ");
//invoking pop() method
Integer x = (Integer) stk.pop();
System.out.println(x);
//prints modified stack
System.out.println("stack: " + stk);
}
}
Output:
stack: []
push -> 20
stack: [20]
push -> 13
stack: [20, 13]
push -> 89
stack: [20, 13, 89]
push -> 90
stack: [20, 13, 89, 90]
push -> 11
Java Vector
Vector is like the dynamic array which can grow or shrink its size. Unlike array, we
can store n-number of elements in it as there is no size limit. It is a part of Java
Collection framework since Java 1.2. It is found in the java.util package and
implements the List interface, so we can use all the methods of List interface here.
The Iterators returned by the Vector class are fail-fast. In case of concurrent
modification, it fails and throws the ConcurrentModificationException.
o Vector is synchronized.
o Java Vector contains many legacy methods that are not the part of a
collections framework.
Vector class supports four types of constructors. These are given below:
SN Constructor Description
SN Method Description
Output:
Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]
Output:
StringTokenizer in Java
It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc.
like StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O
chapter.
In the StringTokenizer class, the delimiters can be provided at the time of creation or
one by one to the tokens.
Constructor Description
Methods Description
Let's see an example of the StringTokenizer class that tokenizes a string "my name is
khan" on the basis of whitespace.
Simple.java
import java.util.StringTokenizer;
public class Simple{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name is khan"," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
Output:
my
name
is
khan
Test.java
import java.util.*;
public class Test {
public static void main(String[] args) {
StringTokenizer st = new StringTokenizer("my,name,is,khan");
// printing next token
System.out.println("Next token is : " + st.nextToken(","));
}
}
Output:
Next token is : my
The Java BitSet class implements a vector of bits. The BitSet grows automatically as
more bits are needed. The BitSet class comes under java.util package. The BitSet
class extends the Object class and provides the implementation of Serializable and
Cloneable interfaces.
Each component of bit set contains at least one Boolean value. The contents of one
BitSet may be changed by other BitSet using logical AND, logical OR and logical
exclusive OR operations. The index of bits of BitSet class is represented by positive
integers.
Each element of bits contains either true or false value. Initially, all bits of a set have
the false value. A BitSet is not safe for multithreaded use without using external
synchronization.
Note: Passing a null parameter to any of the methods of BitSet class will throw a
NullPointerException.
Java Calendar class is an abstract class that provides methods for converting date
between a specific instant in time and a set of calendar fields such as MONTH, YEAR,
HOUR, etc. It inherits Object class and implements the Comparable interface.
Output:
The current date is : Thu Jan 19 18:47:02 IST 2017
15 days ago: Wed Jan 04 18:47:02 IST 2017
4 months later: Thu May 04 18:47:02 IST 2017
2 years later: Sat May 04 18:47:02 IST 2019
Output:
At present Calendar's Year: 2017
At present Calendar's Day: 20
Example 1
import java.util.Random;
public class JavaRandomExample1 {
public static void main(String[] args) {
//create random object
Random random= new Random();
//returns unlimited stream of pseudorandom long values
System.out.println("Longs value : "+random.longs());
// Returns the next pseudorandom boolean value
boolean val = random.nextBoolean();
System.out.println("Random boolean value : "+val);
byte[] bytes = new byte[10];
//generates random bytes and put them in an array
random.nextBytes(bytes);
System.out.print("Random bytes = ( ");
for(int i = 0; i< bytes.length; i++)
{
Output:
Longs value : java.util.stream.LongPipeline$Head@14ae5a5
Random boolean value : true
Random bytes = ( 57 77 8 67 -122 -71 -79 -62 53 19 )
Example 2
import java.util.Random;
public class JavaRandomExample2 {
public static void main(String[] args) {
Random random = new Random();
//return the next pseudorandom integer value
System.out.println("Random Integer value : "+random.nextInt());
// setting seed
long seed =20;
random.setSeed(seed);
//value after setting seed
System.out.println("Seed value : "+random.nextInt());
//return the next pseudorandom long value
Long val = random.nextLong();
System.out.println("Random Long value : "+val);
}
}
Output:
Random Integer value : 1294094433
Seed value : -1150867590
Random Long value : -7322354119883315205
The Java Scanner class breaks the input into tokens using a delimiter which is
whitespace by default. It provides many methods to read and parse various primitive
values.
The Java Scanner class is widely used to parse text for strings and primitive types
using a regular expression. It is the simplest way to get input in Java. By the help of
Scanner in Java, we can get input from the user in primitive types such as int, long,
double, byte, float, short, etc.
The Java Scanner class extends Object class and implements Iterator and Closeable
interfaces.
The Java Scanner class provides nextXXX() methods to return the type of value such
as nextInt(), nextByte(), nextShort(), next(), nextLine(), nextDouble(), nextFloat(),
nextBoolean(), etc. To get a single character from the scanner, you can call
next().charAt(0) method which returns a single character.
To get the instance of Java Scanner which parses the strings, we need to pass the
strings in the constructor of Scanner class. For Example:
Example 1
Let's see a simple example of Java Scanner where we are getting a single input from
the user. Here, we are asking for a string through in.nextLine() method.
import java.util.*;
public class ScannerExample {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine();
System.out.println("Name is: " + name);
in.close();
}
}
Output:
Enter your name: sonoo jaiswal
Example 2
import java.util.*;
public class ScannerClassExample1 {
public static void main(String args[]){
String s = "Hello, This is JavaTpoint.";
//Create scanner Object and pass string in it
Scanner scan = new Scanner(s);
//Check if the scanner has a token
System.out.println("Boolean Result: " + scan.hasNext());
//Print the string
System.out.println("String: " +scan.nextLine());
scan.close();
System.out.println("--------Enter Your Details -------- ");
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.next();
System.out.println("Name: " + name);
System.out.print("Enter your age: ");
int i = in.nextInt();
System.out.println("Age: " + i);
System.out.print("Enter your salary: ");
double d = in.nextDouble();
System.out.println("Salary: " + d);
in.close();
}
}
Output:
Boolean Result: true
String: Hello, This is JavaTpoint.
-------Enter Your Details---------
Enter your name: Abhishek
Example 3
import java.util.*;
public class ScannerClassExample2 {
public static void main(String args[]){
String str = "Hello/This is JavaTpoint/My name is Abhishek.";
//Create scanner with the specified String Object
Scanner scanner = new Scanner(str);
System.out.println("Boolean Result: "+scanner.hasNextBoolean());
//Change the delimiter of this scanner
scanner.useDelimiter("/");
//Printing the tokenized Strings
System.out.println("---Tokenizes String---");
while(scanner.hasNext()){
System.out.println(scanner.next());
}
//Display the new delimiter
System.out.println("Delimiter used: " +scanner.delimiter());
scanner.close();
}
}
Output:
Boolean Result: false
---Tokenizes String---
Hello
This is JavaTpoint
My name is Abhishek.
Delimiter used: /
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.
B.Praveen Kumar Asst.Prof Dept.of CSE, MTIET Page 86
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.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
java.time.ZoneId : It states a time zone identifier and provides rules for converting
between an Instant and a LocalDateTime.
Advantage of Applet
Drawback of Applet
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class
extends Container which is the subclass of Component.
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
For creating any applet java.applet.Applet class must be inherited. It provides 4 life
cycle methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is
maximized. It is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is
stop or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
1. By html file.
2. By appletViewer tool (for testing purpose).
To execute the applet by html file, create an applet and compile it. After that create
an html file and place the applet code in html file. Now click the html file.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}
}
Note: class must be public because its object is created by Java Plugin software that
resides on the browser.
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
Simple example of Applet by appletviewer tool:
To execute the applet by appletviewer tool, create an applet that contains applet
tag in comment and compile it. After that run it by: appletviewer First.java. Now
Html file is not required but it is for testing purpose only.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome to applet",150,150);
}
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
The Java application makes calls to the JDBC driver, which sends queries and other SQL statements to
the database. The database sends query results to the JDBC driver, which sends them on to the Java
application.
You can also use the time series Java classes in Java applets and servlets, as shown in the following
figures.
The database server is connected to the JDBC driver, which is connected to the applet. The applet is
also connected to a browser, which is connected to a web server that communicates with the database.
An Applet Skeleton
Most applets override these four methods. These four methods forms Applet lifecycle.
init() : init() is the first method to be called. This is where variable are initialized. This
start() : start() method is called after init(). This method is called to restart an applet after
stop() : stop() method is called to suspend thread that does not need to run when applet
is not visible.
destroy() : destroy() method is called when your applet needs to be removed completely
from memory.
import java.awt.*;
import java.applet.*;
//initialization
}
public void start ()
//suspend execution
Example of an Applet
import java.applet.*;
import java.awt.*;
height = getSize().height;
width = getSize().width;
setName("MyApplet");
To execute an Applet with an applet viewer, write short HTML file as discussed above. If name it
as run.htm, then the following command will run your applet program.
f:/>appletviewer run.htm
Requesting Repainting
As a general rule, an applet writes to its window only when its paint( ) method is called by the
AWT. This raises an interesting question: How can the applet itself cause its window to be
updated when its information changes? For example, if an applet is displaying a moving banner,
what mechanism does the applet use to update the window each time this banner scrolls?
Remember, one of the fundamental architectural constraints imposed on an applet is that it must
quickly return control to the run-time system. It cannot create a loop inside paint( ) that
repeatedly scrolls the banner, for example. This would prevent control from passing back to the
AWT. Given this constraint, it may seem that output to your applet’s window will be difficult at
best. Fortunately, this is not the case. Whenever your applet needs to update the information
displayed in its window, it simply calls repaint( ).
The repaint( ) method is defined by the AWT. It causes the AWT run-time system to execute a
call to your applet’s update( ) method, which, in its default implementation, calls paint( ). Thus,
for another part of your applet to output to its window, simply store the output and then
call repaint( ). The AWT will then execute a call to paint( ), which can display the stored
information. For example, if part of your applet needs to output a string, it can store this string in
a String variable and then call repaint( ). Inside paint( ), you will output the string
using drawString( ).
The repaint( ) method has four forms. Let’s look at each one, in turn. The simplest version
of repaint( ) is shown here:
void repaint( )
This version causes the entire window to be repainted. The following version specifies a region
that will be repainted:
Here, the coordinates of the upper-left corner of the region are specified by left and top, and the
width and height of the region are passed in width and height. These dimensions are specified in
pixels. You save time by specifying a region to repaint. Window updates are costly in terms of
time. If you need to update only a small portion of the window, it is more efficient to repaint only
that region.
Calling repaint( ) is essentially a request that your applet be repainted sometime soon. However,
if your system is slow or busy, update( ) might not be called immediately. Multiple requests for
repainting that occur within a short time can be collapsed by the AWT in a manner such
that update( ) is only called sporadically. This can be a problem in many situations, including
animation, in which a consistent update time is necessary. One solution to this problem is to use
the following forms of repaint( ):
Here, maxDelay specifies the maximum number of milliseconds that can elapse before update(
) is called. Beware, though. If the time elapses before update( ) can be called, it isn’t called.
There’s no return value or exception thrown, so you must be careful.
How can output a message on status window.
An applet can output a message to the status window of the browser or applet viewer on which it is running. For
this, it makes a call to showStatus( ) with the string that we want to be displayed. The status window is a place
where the user can give feedback about what is occurring in the applet, suggest options, or report some types of
errors. The status window also makes an excellent debugging aid, because it gives an easy way to
output information about the applet. The applet below shows the use of showStatus( ):
import java.awt.*;
import java.applet.*;
/*
<applet code="StatusWindow" width=300 height=50> </applet>
*/
public class StatusWindow extends Applet
{
public void init()
{
setBackground(Color.pink);
}
public void paint (Graphics g)
{
g.drawString("You are in main applet window.", 10, 20);
showStatus("This is the status window.");
}
}
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:
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:
Disadvantage:
Disadvantages:
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.
Advantage:
3. Driver Manager: The Driver Manager plays an important role in the JDBC architecture.
The Driver manager uses some database-specific drivers that effectively connect
enterprise applications to databases.
4. JDBC drivers: JDBC drivers help us to communicate with a data source through JDBC.
We need a JDBC driver that can intelligently interact with the respective data source.
Types of JDBC Architecture
There are two types of processing models in JDBC architecture: two-tier and three-tier.
These models help us to access a database. They are:
1. Two-tier model
In this model, a Java application directly communicates with the data source. JDBC
driver provides communication between the application and the data source. When a
user sends a query to the data source, the answers to those queries are given to the user
in the form of results.
We can locate the data source on a different machine on a network to which a user is
connected. This is called a client/server configuration, in which the user machine acts as
a client, and the machine with the data source acts as a server.
2. Three-tier model
In the three-tier model, the query of the user queries goes to the middle-tier services.
From the middle-tier service, the commands again reach the data source. The results of
the query go back to the middle tier.
From there, it finally goes to the user. This type of model is beneficial for management
information system directors.
It is a predefined class present/declared in java.sql package. It is a non-abstract class in the JDBC API. It has no
constructor which implies that this class cannot be inherited or initialized directly.
All the methods or properties of this class are declared as static, so it is not necessary to construct an object of
DriverManager Class. We can call these static methods using class name.
The main responsibility of the DriverManager class is preparing a connection by using Driver implementation
that accepts the given JDBC URL.
Methods in DriverManager
(a) public static Connection getConnection (String url, String user name, String pswd);
Establishes connection between driver and database. This class selects a driver from the list of drivers and creates
a connection by checking user parameter for which the connection is being made. Password parameter represents
the password of the user.
(b) public static Driver getDriver (String url) throws SQLException
Locates the requested driver in the DriverManager class. The URL parameter specifies the URL of requested
driver.
(c) public static void register (Driver drvr) throws SQLException:
Registers a requested driver with DriverManager Class.
(d) public static void deregister (Driver drvr) throws SQLException
Drops a driver from the list of the driver maintained by DriverManager.
Driver Interface
It is a predefined interface present in java.sql. package. It is a basic interface that every JDBC driver provider has
to implement. The java.sql.Driver is an Interface defined under JDBCAPI to describe an object that is responsible
to establish connection to database. All the driver classes implement this interface to connect to a database.
Methods in Driver Interface
(a) public Connection connect (String url, Properties info)
This method establishes connectivity with database. The URL parameter specifies a URL that describes the
database details to which the driver is to be connected. The info parameter specifies the information of the
tag/value pair used in driver.
Connection Interface
It is an interface present in java.sql package. This interface defines an abstraction to access the session,
established with the database server. The JDBC connection helps to perform the following operation:
• Create JDBC Statement
• Control local transaction
Methods in Connection Interface
(a) public void close () throws SQLException
Closes the connection and releases the connection object associated with the connected database.
(b) public Statement createStatement () throws SQLException
Create a Statement object to send sql statements to the specified database.
(c) public PreparedStatement prepareStatement (String sql) throws SQLException
Create a PreparedStatement object to send sql statements over a connection.
(d) public CallableStatement prepareCall (String sql) throws SQLException
Create a CallableStatement object for calling database stored procedures.
(e) public void commit () throws SQLException
Commits the changes made in the previous commit and releases any database locks held by the current
Connection object.
(f) public void rollback () throws SQLException
Rolls back all the transactions and releases any locks that are currently held by the Connection object.
Statement Interface
It is a predefined interface present in java.sql package. It is a part of JDBC API that abstracts an object. It is
responsible to execute sql statement and return the result. A
Statement object can open a single ResultSet object at a time.
The PreparedStatement interface is dealing with IN parameter whereas the CallableStatement interface deals with
both IN and OUT.
Methods of Statement Interface
(a) public int executeUpdate (String sql) throws SQLException
Execute the Insert, Update and Delete Statement or the SQL DDL statements.
(b) public ResultSet executeQuery (String sql) throws SQLException
Execute a sql command and return a single ResultSet.
(c) public void close () throws SQLException
Closes the Statement object, therefore, it releases its control from the database and also from the connection.
(d) public ResultSet getResultSet () throws SQLException
Retrieves the current Resultset object generated by Statement object.
(e) public Connection getConnection () throws SQLException
Accepts the Connection object made to the database.
ResultSet Interface
This interface provides methods for the retrieval of data returned by an SQL statement execution. A ResultSet
maintains a cursor pointing to its current row of data. The most often used methods, namely, getXXX and
updateXXX methods are present in this interface.
Methods in ResultSet
(a) public booleannext () throws SQLException
Moves the cursor down one row from its current position.
(b) public void close () throws SQLException
Releases this ResultSet object’s database and JDBC resources immediately instead of waiting for this to happen
when it is automatically closed.
(c) public booleanwasNull () throws SQLException
Reports whether the last column read had a value of SQL NULL.
(d) public StringgetXXX (int columnIndex) throws SQLException
Retrieves the value of the designated column in the current row of this ResultSet object as per the type of data.
(e) public void beforeFirst () throws SQLException
Moves the cursor to the front of this ResultSet object, just before the first row.
(f) public void afterLast () throws SQLException
Moves the cursor to the end of this ResultSet object, just after the last row.
(g) public booleanabsolute (int row) throws SQLException
Moves the cursor to the given row number in this ResultSet object.
(h) public booleanprevious () throws SQLException
Moves the cursor to the previous row in this ResultSet object.
(i) public void deleteRow () throws SQLException
Deletes the current row from this ResultSet object and from the underlying database.
(j) public void insertRow () throws SQLException
Inserts the contents of the insert row into this ResultSet object and into the database.
Code Explanation:
Line1: By importing the java.sql package, JDBC API is made available to the JDBC application.
Line2: A user-defined class “AccountStoringApplication” is defined here.
1. This JDBC application is a standalone application.
2. Every standalone application should have a main method in java.
3. To encapsulate the main method, the class “AccountStoringApplication ” is defined here.
Line 4 & 5: the main method is defined as is standalone JDBC application.
Within the main method body during the forName() method call there is a chance
of java.lang.ClassNotFoundException raising. During other JDBC API calls, there is a chance
of java.sql.SQLException getting raised. These are checked exceptions. These checked
exceptions must be handled. Non-handling of checked exceptions in a java application is a
syntactical error.
To pass (temporarily handled) on the exception handling duty to the higher level and at the same
to overcome the compilation error, a throws clause is written for the main method.
Line6:
The main method is calling forName() method on the Class(name of the class) class by specifying
oracle corporation developed TYPE- 4 driver class as an argument. The forName() method loads
the oracle driver class from secondary memory into primary memory.
In OracleDriver class (in fact in every driver class) there is a static block. In that block, two things
are performed
1. Driver class object creation.
2. Registering it with DriverManager
Static
{
OracleDriver d = new OracleDriver();
DriverManager.registerDriver(d);
}
If the specified driver class is not found at the specified location, the forName() method causes
ClassNotFoundException. In the case of OracleDriver, we need to place any one of the following
jar files into the classpath.
1. classes12.jar
2. ojdbc14.jar
3. jdbc5.jar
4. ojdbc.jar
For example: set CLASSPATH = .;\ojdbc14.jar
Here dot (.) represent the current directory.
Line7:
The main method is calling the getConnection() method on DriverManager class by supplying the
connection string as the first argument, username as the second, and password as the third
argument. (Username and password are the database user name and password).
The connection string is “jdbc:oracle:thin:@localhost:1521:xe”
Here,
1. jdbc = main protocol
2. oracle = sub protocol
3. thin = type of driver (here type 4)
4. localhost = IP address of the current machine
5. 1521 = port number
6. xe = database service name.
Note: port number and database service name we have to check in the “tnsnames.ora” file
Line 8 & 9:
Creating a Statement object and executing the SQL statement against the Oracle database.
Line 13 & 14:
Closing the statement and connection object.
Note: For the insert, update, and delete operations, the DBMS returns an integer number. In the
case of INSERT if the record is successfully inserted into the database then DBMS returns 1. In
the case of UPDATE if the record is successfully updated then it returns the no i.e. updated
number of records. And in the case of DELETE, it returns 1 if the successful record is deleted else
it returns 0.
Connection Interface in JDBC
The java.sql.Connection interface represents a session between a java application and a database.
All SQL statements are executed and results are returned within the context of a Connection
Object. The connection interface is mainly used to create java.sql.statement,
java.sql.PreparedStatement and java.sql.CallableStatement objects.
For example :
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con = DriverManager.getConnection(“dbc:odbc:DSN”);
Methods of Connection Interface
1. public Statement CreateStatement(): creates a statement object that can be used to
execute SQL queries.
2. public Statement createStatement(int resultSetType, int
resultSetConcurrency): creates a statement object that will generate ResultSet objects
with the given type and concurrency.
3. public void setAutoCommit(boolean status): is used to set the commit status. By default
it is true.
4. public void comit(): saves the changes made since the previous commit/rollback
permanent.
5. public void rollback(): Drops all changes made since the previous commit/rollback.
6. public void close(): closes the connection and releases JDBC resources immediately.
Statement Interface in JDBC
Once a connection is obtained we can interact with the database. The JDBC Statement,
CallableStatement, and PreperedStatement interface define the methods and properties that enable
you to send SQL or PL/SQL commands and receive data from your database. They also define
methods that help bridge data type differences between Java and SQL data types used in a
database.
Methods of Statement Interface
1. public ResultSet executeQuery(String sql): is used to execute the SELECT query. It
returns the object of ResultSet.
2. public int executeUpdate(String sql): is used to execute the specified query, it may be
created, drop, insert, update, delete, etc.
3. public Boolean execute(String sql): is used to execute queries that may return multiple
results.
4. public int[] executeBatch() : is used to execute batch of commands.
JDBC - Create Database Example
Before executing the following example, make sure you have the following in place
You should have admin privilege to create a database in the given schema. To execute the
following example, you need to replace the username and password with your actual user name
and password.
Your MySQL or whatever database is up and running.
Required Steps
The following steps are required to create a new Database using JDBC application
Import the packages − Requires that you include the packages containing the JDBC
classes needed for database programming. Most often, using import java.sql.* will suffice.
Open a connection − Requires using the DriverManager.getConnection() method to create
a Connection object, which represents a physical connection with the database server.
To create a new database, you need not give any database name while preparing database
URL as mentioned in the below example.
Execute a query − Requires using an object of type Statement for building and submitting
an SQL statement to the database.
Clean up the environment . try with resources automatically closes the resources.
Sample Code
Copy and paste the following example in JDBCExample.java, compile and run as
follows −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
Register the driver: Register the driver class using the registerDriver() method of
the DriverManager class. Pass the driver class name to it, as parameter.
Establish a connection: Connect ot the database using the getConnection() method of
the DriverManager class. Passing URL (String), username (String), password (String) as
parameters to it.
Create Statement: Create a Statement object using the createStatement() method of
the Connection interface.
Execute the Query: Execute the query using the execute() method of the Statement interface.
Example
Following JDBC program establishes connection with MySQL and creates a table named customers in
the database named SampleDB:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class CreateTableExample {
public static void main(String args[]) throws SQLException {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String mysqlUrl = "jdbc:mysql://localhost/SampleDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established. .... ");
//Creating the Statement
Statement stmt = con.createStatement();
//Query to create a table
String query = "CREATE TABLE CUSTOMERS("
+ "ID INT NOT NULL, "
+ "NAME VARCHAR (20) NOT NULL, "
+ "AGE INT NOT NULL, "
+ "SALARY DECIMAL (18, 2), "
+ "ADDRESS CHAR (25) , "
+ "PRIMARY KEY (ID))";
stmt.execute(query);
System.out.println("Table Created ..... ");
}
}
Output
Connection established......
Table Created......
The show tables command gives you the list of tables in the current database in
MySQL.
If you verify the list of tables in the database named sampledb, you can observe
the newly created table in it as:
mysql> show tables;
+ +
| Tables_in_sampledb |
+ +
| articles |
| customers |
| dispatches |
| technologies |
| tutorial |
+ +
5 rows in set (0.00 sec)