Professional Documents
Culture Documents
Oops Using Java
Oops Using Java
What is Java?
1) Standalone Application
2) Web Application
3) Enterprise Application
4) Mobile Application
Desktop GUI Applications
❖ Java support for web development through Servlet, JSP, and Struts.
❖ Popular android app development IDE Android Studio also uses Java for
developing android applications.
❖ The most popular android applications Spotify and Twitter are developed
using Java
Gaming Applications
4) JavaFX
Java Platform, Standard Edition (Java SE):
▪ Java SE’s API offers the Java programming language’s core functionality.
• By using standard Java naming conventions, we make our code easier to read
• It indicates that less time is spent to figure out what the code does.
Classes and interfaces
• If the name is created from several words, the first letter of the inner words
should be capitalized (a "camelCase" format).
• First letter must be lowercase, and then normal camelCase rules are used.
• First letter must be lowercase, and then normal camelCase rules are used.
buttonHeight.
Constants
System.out.println("Hello Java");
} javac
To compile:
Simple.java
To execute: java Simple
Compilation Flow
Valid java main method signature
1. local variable
2. instance variable
3. static variable
1. Local Variable:
• Variable declared inside the body of the method.
• We can use this variable only within that method
• Cannot be defined with "static" keyword
2. Instance Variable
• Variable declared inside the class but outside the body of the method.
• It is not declared as static.
3. Static variable
• Variable which is declared as static is called static variable.
• It cannot be local
• Memory allocation for static variable happens only once when the class is
loaded in the memory
Example to understand the types of variables in java
class A
{
int data=50;
//instance variable
static int m=100; //static variable
void method()
{
int n=90; //local variable
}
Java Variable Example: Widening
class Simple{
int a=10;
float f=a;
System.out.println(a); OUTPUT:
System.out.println(f); 10
10.0
}}
Java Variable Example: Narrowing
class Simple {
float f=10.5f;
int a=f;
int a=(int)f;
OUTPUT:
System.out.println(f);
System.out.println(a); 10.5
10
}}
Data Types in Java
Integer
This group includes byte, short, int, long
byte :
short :
long :
• It is 8 bytes(64-bits) integer data type.
• Value range from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
• Default value zero. example:
• long l=100012;
// byte type
byte b = 20;
System.out.println("b= "+b);
// short type
short s = 20;
System.out.println("s= "+s);
// int type
int i = 20;
System.out.println("i= "+i);
// long type
long l = 20;
System.out.println("l= "+l);
Floating-Point Number
This group includes float, double
float :
• It is 4 bytes(32-bits) float data type.
• Default value 0.0f.
• example: float ff=10.3f;
double :
• It is 8 bytes(64-bits) float data type.
• Default value 0.0d.
• example: double db=11.123;
Characters
• Data types used to store characters are char.
• Unicode defines a fully international character set that can represent all of the
characters found in all human languages like, latin, greek, arabic, and many
more.
• This data type is a single 16-bit(2bytes) unicode character and its value-ranges
between ‘\u0000’ (or 0) to ‘\uffff’ (or 65,535 inclusive).
• The \u in your example is for Unicode, we can store unicode characters that take
up to 16 bits, from \u0000 to \uFFFF.
public class Demo {
public static void main(String[] args)
{
char ch = 'S';
System.out.println(ch);
boolean t = true;
System.out.println(t);
boolean f = false;
System.out.println(f);
} }
Type casting in java
Type Casting in Java
• Process of converting the value of one data type (int, float, double, etc.)
Into another data type is known as type casting.
There are two types of casting:
byte -> short -> char -> int -> long -> float -> double
double -> float -> long -> int -> char -> short -> byte
Widening Casting
public class Test
{
public static void main(String[] args)
{
int i = 100;
long l = i;
float f = l;
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
} Output:
Int value 100
Long value 100
} Float value 100.0
Narrowing Casting
public class Test
{
public static void main(String[] args)
{
double d = 100.04;
long l = (long)d; //explicit type casting required
int i = (int)l; //explicit type casting required
// i % 256
b = (byte)i;
// d % 256
b = (byte)d;
i = 257 b = 1
d = 323.142 b= 67
Java int to char
int a=65;
char c=(char)a;
System.out.println(a);
}}
Output:
A
Convert char to int
char a = '5';
char b = 'c';
int num1 = a;
int num2 = b;
System.out.println(num1); // 53
System.out.println(num2); // 99
char to int using getNumericValue() method
char a = '5';
char b = '9';
System.out.println(num1); // 5
System.out.println(num2); // 9
char to int using parseInt() method
char a = '5';
char b = '9';
// Use parseInt()
System.out.println(num1); // 5
System.out.println(num2); // 9
Tokens
Tokens
• Tokens is the building block or the basic component for creating a program.
Keywords in Java
keywords
• keyword is a reserved word.
• Names should start with a lowercase letter and it cannot contain whitespace
• Names can also begin with $ and _ (but we will not use it)
• Names are case sensitive ("myVar" and "myvar" are different variables)
• Reserved words (like Java keywords, such as int or boolean) cannot be used
as names
valid identifiers in Java:
• TestVariable
• testvariable
• a
• i
• Test_Variable
• _testvariable
• $testvariable
• sum_of_array
• TESTVARIABLE
• jtp123
Invalid identifiers
• Have a constant value and a fixed data type and are often known as
constants in Java.
1. binary (base 2)
3. octal (base 8)
• int octal_int=077;
Hexadecimal Integer:
• Integers having a base value of 16.
• int hexadec_int=0x1ff2;
Binary Integer
• int binary_int=0b1010101;
Example
int decimal_int=1234;
int octal_int=077;
int hexadec_int=0x1ff2;
int binary_int=0b1010101;
• We can assign them to float data types by adding an f at the end of the
value.
• 123.45 //Legal
• 122.32E5 //Legal
• 231.12F //Legal
• 1/4 // Illegal Symbol Used “/”
• 1.7.5 //Illegal, as two decimal points used.
• 1,234.56 // Illegal, as commas are not allowed
• 123.E4 //Illegal, as E cannot precede the point.
• 321E //Illegal, as the exponent part is incomplete.
Example
float val_float=1.7732f;
double val_double=1.7732d;
float val_exponent=123E4f;
boolean flag1=true;
boolean flag2=false;
• Example
String null_Literal=null;
Output:
• we can specify char literal as integral literal, which represents the Unicode
value of the character, and that integral literal can be specified either in
• char ch = 062;
Unicode Representation:
char ch = 'a';
// It is an Integer literal with octal form
char b = 0789;
// Unicode representation
char c = '\u0061';
System.out.println(ch);
System.out.println(b);
System.out.println(c);
Output
• a
• a
OPERATORS IN JAVA
Operators in java
Assignment assignment = += -= *= /= %=
Java Unary Operator
class OperatorExample{
int x=10;
System.out.println(x++);
10
System.out.println(++x); 12
12
System.out.println(x--);
10
System.out.println(--x);
}}
SHIFT OPERATOR
Shift Operator
• Left shift operator shifts all bits towards the left by a certain number of
specified bits.
• It is denoted by <<.
Java Left Shift Operator Example
class OperatorExample{
System.out.println(10<<2); //10*2^2=10*4=40
System.out.println(10<<3); //10*2^3=10*8=80
System.out.println(20<<2); //20*2^2=20*4=80
System.out.println(15<<4); //15*2^4=15*16=240
}}
Right Shift Operator
• Right shift operator shifts all bits towards the right by a certain number of
specified bits.
• It is denoted by >>.
• When we shift any number to the right, the least significant bits (rightmost) are
discarded and the most significant position (leftmost) is filled with the sign bit.
Java Right Shift Operator Example
class OperatorExample{
System.out.println(10>>2); //10/2^2=10/4=2
System.out.println(20>>2); //20/2^2=20/4=5
System.out.println(20>>3); //20/2^3=20/8=2
}}
Relation operators
Relation operators
• Can be use to test whether two values are equal or not equal or less than or
greater than etc.
• Returns the Boolean results, i.e. true or false after the comparison
Operator Description
> Check if operand on the left is greater than operand on the right
int a, b;
a=40;
b=30;
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
• Java defines several bitwise operators that can be applied to the integer types
long, int, short, char and byte.
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< left shift
>> right shift
truth table for bitwise &, | and ^
00001100
| 00011001
____________
class Main {
public static void main(String[] args) {
00001100
& 00011001
____________
class Main {
public static void main(String[] args) {
00001100
^ 00011001
____________
class Main {
public static void main(String[] args) {
• It is denoted by ~.
For example,
class Main {
public static void main(String[] args) {
// bitwise complement of 35
result = ~number;
System.out.println(result); // prints -36
}
}
Logical Operators
Logical operators
// && operator
System.out.println((5 > 3) && (8 > 5)); // true
System.out.println((5 > 3) && (8 < 5)); // false
// || operator
System.out.println((5 < 3) || (8 > 5)); // true
System.out.println((5 > 3) || (8 < 5)); // true
System.out.println((5 < 3) || (8 < 5)); // false
// ! operator
System.out.println(!(5 == 3)); // true
System.out.println(!(5 > 3)); // false
}
}
Java Ternary Operator
System.out.println(result);
JAVA WRAPPER CLASSES
Description
Each of Java's eight primitive data types has a class dedicated to it. These are
known as wrapper classes, because they "wrap" the primitive data type into an
object of that class. The wrapper classes are part of the java.lang package, which is
can do activities reserved for the objects like being added to ArrayList, Hashset,
primitive types to and from string objects, converting to various bases like
The following two statements illustrate the difference between a primitive data
int x = 25;
25. The second statement instantiates an Integer object. The object is initialized
with the value 33 and a reference to the object is assigned to the object variable y.
Below table lists wrapper classes in Java API with constructor details.
As explain in above table all wrapper classes (except Character) take String as
Here in we can provide any number as string argument but not the words etc.
table. Similar methods for the other wrapper classes are found in the Java API
documentation.
Method Purpose
int compareTo(int i) Compares the numerical value of the invoking object with that of i.
num2) equal. Returns a negative value if num1 is less than num2. Returns a
boolean equals(Object intObj) Returns true if the invoking Integer object is equivalent to intObj.
Let’s see java program which explain few wrapper classes methods.
1. package WrapperIntro;
2.
3.
4.
6.
7.
8.
10.
12.
14.
16.
17. //compareTo demo
18.
tObj2));
20.
tObj3));
22.
23.
24.
26.
28.
30.
31.
32.
34.
36.
38.
40.
41. System.out.println("Comparing using compare f1 and f3: " +Float.compare(f1,f3));
42.
43.
44.
46.
48.
50.
51. }
52.
53.
54.
55. }
Output
valueOf (), toHexString(), toOctalString() and
toBinaryString() Methods:
This is another approach to create wrapper objects. We can convert from binary or
octal or hexadecimal before assigning value to wrapper object using two argument
1. package WrapperIntro;
2.
3.
4.
6.
7.
8.
10.
12.
14.
16.
18.
21.
22.
24.
26.
28.
30.
32.
33. }
34.
35. }
Output
Summary
Each of primitive data types has dedicated class in java library.
Wrapper class provides many methods while using collections like sorting,
searching etc.
control statements
a) if statement
b) nested if statement
c) if-else statement
d) if-else-if statement
If statement
If statement consists a condition, followed by statement or a set of statements as shown below:
if(condition){
Statement(s);
}
The statements gets executed only when the given condition is true. If the condition is false then the
statements inside if statement body are completely ignored.
Example of if statement
public class IfStatementExample {
if(condition_2) {
Statement2(s);
}
}
Statement1 would execute if the condition_1 is true. Statement2 would only execute if both the conditions(
condition_1 and condition_2) are true.
Example of Nested if statement
public class NestedIfExample {
if-else-if Statement
if-else-if statement is used when we need to check multiple conditions. In this statement we have only one
“if” and one “else”, however we can have multiple “else if”. It is also known as if else if ladder. This is how
it looks:
if(condition_1) {
/*if condition_1 is true execute this*/
statement(s);
}
else if(condition_2) {
/* execute this if condition_1 is not met and
* condition_2 is met
*/
statement(s);
}
else if(condition_3) {
/* execute this if condition_1 & condition_2 are
* not met and condition_3 is met
*/
statement(s);
}
.
.
.
else {
/* if none of the condition is true
* then these statements gets executed
*/
statement(s);
}
Note: The most important point to note here is that in if-else-if statement, as soon as the condition is met, the
corresponding set of statements get executed, rest gets ignored. If none of the condition is met then the
statements inside “else” gets executed.
Example of if-else-if
public class IfElseIfExample {
Explanation: In switch I gave an expression, you can give variable also. I gave num+2, where num value is
2 and after addition the expression resulted 4. Since there is no case defined with value 4 the default case got
executed. This is why we should use default in switch case, so that if there is no catch that matches the
condition, the default block gets executed.
Switch Case Flow Diagram
First the variable, value or expression which is provided in the switch parenthesis is evaluated and then
based on the result, the corresponding case block is executed that matches the result.
First step: In for loop, initialization happens first and only one time, which means that the initialization part
of for loop only executes once.
Second step: Condition in for loop is evaluated on each iteration, if the condition is true then the statements
inside for loop body gets executed. Once the condition returns false, the statements in for loop does not
execute and the control gets transferred to the next statement in the program after for loop.
Third step: After every execution of for loop’s body, the increment/decrement part of for loop executes that
updates the loop counter.
Fourth step: After third step, the control jumps to second step and condition is re-evaluated.
System.out.print(j+" ");
}
}
}
Output:
012356
As you may have noticed, the value 4 is missing in the output, why? because when the value of variable j is
4, the program encountered a continue statement, which makes it to jump at the beginning of for loop for
next iteration, skipping the statements for current iteration (that’s the reason println didn’t execute when the
value of j was 4).
Flow Diagram of Continue Statement
}
}
Output:
012345689
switch (num)
{
case 1:
System.out.println("Case 1 ");
break;
case 2:
System.out.println("Case 2 ");
break;
case 3:
System.out.println("Case 3 ");
break;
default:
System.out.println("Default ");
}
}
}
Output:
Case 2
In this example, we have break statement after each Case block, this is because if we don’t have it then the
subsequent case block would also execute. The output of the same program without break would be Case 2
Case 3 Default.
Arrays and String
An array is a collection of similar type of elements which is stored in a 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.
A list of items can be given one variable name using only one subscript such a variable is called
a single-scripted or one –dimensional array.
Example
int a[]=new int[5];
for this array computer reserve five memory locations as
Creating Array:
Array must be declared and created in computer memory before they are used. Creation of array
involves three steps:
1. Declare the array
2. Create memory locations
3. Put values into the locations
Declaration of Arrays
Array in java may be declared in two forms.
Form1
Datatype Arrayname[ ];
Form2
Datatype[ ] Arrayname;
Example:
int number[ ];
floar percentage []
int[ ] count;
float[ ] average;
Creation of Arrays
Two dimensional array requires two subscript one for Row and another for Column .Data in two
dimensional arrays are stored in tabular form (in row major order).
Declaration of 2D array:
int a[ ][ ];
a = new int [3][4];
or
int[][] a = new int[3][4];
Here, a is a two-dimensional (2d) array. The array can hold maximum of 12 elements of
type int.
Initialization of 2D array :
Ex.
int a[ ][ ] = {1,2,3,4,5,6,7,8,9,10,11,12};
Or
int a[ ][ ] = { {1,2,3,4}, {5,6,7,8}, {9,10,11,12} };
or
int a[ ][ ] = {
{1,2,3,4},
{5,6,7,8},
{9,10,11,12}
};
Below code shows different ways for string array declaration in java.
String[ ] strArray; //declare without size
String Methods:
The String class has a set of built-in methods that you can use on strings.
Method Description Return Type
Output
true
compareTo( )
• For sorting, we need to know which string is less than, equal to, or greater than the
next.
• A String is less than another if it comes before the other in dictionary order.
• A String is greater than another if it comes after the other in dictionary order.
• General form
int compareTo(String str)
str -> string being compared
Value Meaning
<0 Invoking string less than str
>0 Invoking string greater than str
= 0 Two strings are equal
• Example
• Now comes first because of the uppercase(uppercase has low value in ascii
set)
• If you want ignore the case while comparing, then call the method,
compareToIgnoreCase( )
GF
int compareToIgnoreCase(String str)
Searching Strings
• indexOf( ) -> searches for the first occurrence of a character or
substring.
• lastIndexOf( ) -> searches for the last occurrence of a character or
substring
• General forms
int indexOf(char ch)
int lastIndexOf(char ch)
int indexOf(String str)
int lastIndexOf(String str)
ch -> character being sought
str -> substring
• Specifying starting points for the search
int indexOf(char ch, int startIndex)
int latIndexOf(char ch, int startIndex)
startIndex -> index at which point the search begins
-> for index( ) search runs from startIndex to the end of
the string.
-> for lastIndexOf( ), search runs from startIndex to zero.
• Example
String s = “This is a test.This is too”;
System.out.println(s.indexOf(‘t’));
System.out.println(s.lastIndexOf(‘t’));
System.out.println(s.indexOf(“is”);
System.out.println(s.indexOf(‘s’,10));
System.out.println(s.lastIndexOf(“is”, 15));
Modifying a String
• String objects are immutable. To modify a string,
-> use one of the String methods given below
subString( )
• To extract a sub string
• 2 forms
String subString(int startIndex)
-> from startIndex to end of the invoking string
String subString(int startIndex, int endIndex)
-> from startIndex to endIndex – 1
• Example
concat( )
• To concatenate two strings
• General form
String concat(String str)
• Example
String s1 = “One”;
String s2 = s1.concat(“Two”);
System.out.println(s2);
Output
One Two
replace( )
• Replaces all occurrences of one character in the invoking string with
another character.
• General form
String replace(char original, char replacement)
• Example
String s = “Hello”;
String s1 = s.replace(‘l’, ‘w’);
System.out.println(s1);
Output
Hewwo
trim( )
• Returns a copy of the invoking string from which any leading and trailing
whitespace has been removed.
• General form
String trim( )
• Example
String s = “ Hello World “.trim( );
System.out.println(s);
Output
Hello World
Changing the case of characters
• toLowerCase( ) -> converts all the characters in a String from uppercase
to lowercase
• toUpperCase( ) -> converts all the characters in a String from lowercase to
uppercase
• General forms
String toLowerCase( )
String toUpperCase( )
• Example
String s = “This is a test”;
String upper = s.toUpperCase( );
String lower = s.toLowerCase( );
System.out.println(upper);
System.out.println(lower);
Output
THIS IS A TEST
this is a test
Data Conversion using valueOf( )
• The valueOf( ) method converts data from its internal format into a
human readable form.
• static method
• General forms
static String valueOf(double num)
static String valueOf(long num)
static String valueOf(Object ob)
static String valueOf(char chars[ ])
• valueOf( ) is called when String representation of some other data
type is needed.
• Example
String s = “hello”;
int a = 10;
String abc = s.valueOf(a);
System.out.println(abc);
Output
10
Java classes/objects
Java objects
• Java is an object-oriented programming language.
• The car has attributes, such as weight and color, and methods, such as drive and
brake.
Java Class
• A class is a blueprint for the object.
• It contains all the details about the floors, doors, windows, etc.
// fields
// methods
• Fields
• Methods
• Constructors
• Blocks
class Bicycle {
// state or field
int gear = 5;
// behavior or method
public void braking() {
System.out.println("Working of Braking");
}
}
Java Objects
• An object is called an instance of a class.
• The new is a keyword which is used to allocate memory for the object.
Example: Creating a Class and its object
public class Student{
String name;
int rollno;
int age;
void info(){
System.out.println("Name: "+name);
System.out.println("Roll Number: "+rollno);
System.out.println("Age: "+age);
}
public static void main(String[] args) {
Student student = new Student();
// Calling method
student.info();
} }
Output:
Name: Ramesh
Age: 25
3 ways to initialize object
There are 3 ways to initialize object in Java.
• By reference variable
• By method
• By constructor
1) Object and Class Example: Initialization through reference
• In this example, we are creating the two objects of Student class and initializing
the value to these objects by invoking the insertRecord method.
• Here, we are displaying the state (data) of the objects by invoking the
displayInformation() method.
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
• Object gets the memory in heap memory area.
• The reference variable refers to the object allocated in the heap memory area.
• Here, s1 and s2 both are reference variables that refer to the objects allocated in memory.
Constructor
Constructors in Java
1. Default constructor
2. User-Defined constructor
Java Default Constructor
• Default constructor is used to provide the default values to the object like 0,
null, etc., depending on the type.
Example of default constructor that displays the
default values
class Student3{
int id;
String name;
void display()
{ System.out.println(id+“ "+name); }
A constructor is used to initialize the state of an A method is used to expose the behavior of an
object. object.
A constructor must not have a return type. A method must have a return type.
The constructor name must be same as the class The method name may or may not be same as
name. class name.
static keyword
static keyword
➢ A static method can be accessed without creating an object of the class first:
The static can be used with :
• Block
• Nested class
static variable
• Used to refer to the common property of all objects (which is not unique for
each object), for example, the company name of employees, college name of
students, etc.
• Gets memory only once in the class area at the time of class loading.
Advantages of static variable
• A static method belongs to the class rather than the object of a class.
• A static method can be invoked without the need for creating an instance of a
class.
• A static method can access static data member and can change the value of it.
class StaticTest {
// non-static method
int multiply(int a, int b){
return a * b;
}
// static method
static int add(int a, int b){
return a + b;
}
}
class A2{
static{
System.out.println("Hello main");
}
Static class
• A class can be made static only if it is a nested class.
}
public static void main(String args[])
{ JavaExample.MyNestedClass obj = new JavaExample.MyNestedClass();
obj.disp();
}
}
this keyword in java
this keyword
int age;
Main(int age){
age = age;
int age;
Main(int age){
this.age = age;
}
Output:
} Age = 8
this: to invoke current class method
• We may invoke the method of the current class by using the this keyword.
• If we don't use the this keyword, compiler automatically adds this keyword
while invoking the method.
class A{
void m() {System.out.println("hello m");}
void n(){
System.out.println("hello n");
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
Output:
a.n();
hello n
}} hello m
this() : to invoke current class constructor
• this() constructor call can be used to invoke the current class constructor.
class A{
A(){System.out.println("hello a");}
A(int x){
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){
Output:
A a=new A(10);
hello a
}} 10
Calling parameterized constructor from default constructor:
class A{
A(){
this(5);
System.out.println("hello a");
}
A(int x){
System.out.println(x);
}
}
class TestThis6{
public static void main(String args[]){
A a=new A(); Output:
5
} hello a
Encapsulation in Java with example
Encapsulation simply means binding object state(fields) and
behaviour(methods) together. If you are creating class, you are doing
encapsulation. In this guide we will see how to do encapsulation in java
program, if you are looking for a real-life example of encapsulation then refer
this guide: OOPs features explained using real-life examples.
For other OOPs topics such as inheritance and polymorphism, refer OOPs
concepts
What is encapsulation?
The whole idea behind encapsulation is to hide the implementation details
from users. If a data member is private it means it can only be accessed
within the same class. No outside class can access private data member
(variable) of other class.
This way data can only be accessed by public methods thus making the
private fields and their implementation hidden for outside classes. That’s why
encapsulation is known as data hiding. Lets see an example to understand
this concept better.
class EncapsulationDemo{
private int ssn;
private String empName;
private int empAge;
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 felds of the parent class. Moreover, you can add
new methods and felds in your current class also.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It
is also called a derived class, extended class, or child class.
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.
class Employee{
float salary=40000;
int bonus=10000;
public static void main(String args[]){
}
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the feld of own class
as well as of Employee class i.e. code reusability.
File: TestInheritance.java
class Animal{
void eat(){System.out.println("eating...");}
void bark(){System.out.println("barking...");}
class TestInheritance{
d.bark();
d.eat();
}}
Output:
barking...
eating...
File: TestInheritance2.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
void weep(){System.out.println("weeping...");}
class TestInheritance2{
d.weep();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...
File: TestInheritance3.java
class Animal{
void eat(){System.out.println("eating...");}
void bark(){System.out.println("barking...");}
class TestInheritance3{
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 diferent, 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
C obj=new C();
}
Compile Time Error
class Animal{
String color="white";
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
class TestSuper1{
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...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
}
}
class TestSuper2{
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.
class Animal{
Animal(){System.out.println("animal is created");}
Dog(){
super();
System.out.println("dog is created");
class TestSuper3{
Output:
animal is created
dog is created
1. variable
2. method
3. class
The fnal keyword can be applied with the variables, a fnal variable that
have no value it is called blank fnal variable or uninitialized fnal variable. It
can be initialized in the constructor only. The blank fnal variable can be
static also which will be initialized in the static block only. We will have
detailed learning of these. Let's frst learn the basics of fnal keyword.
class Bike9{
void run(){
speedlimit=400;
obj.run();
}//end of class
Output:Compile Time Error
honda.run();
}
}
Output:Compile Time Error
honda.run();
}
Output:Compile Time Erro
class Bike{
new Honda2().run();
}
Output:running...
Q) What is blank or uninitialized final variable?
A fnal variable that is not initialized at the time of declaration is known as
blank fnal variable.
int id;
String name;
...
}
Que) Can we initialize blank final variable?
class Bike10{
Bike10(){
speedlimit=70;
System.out.println(speedlimit);
new Bike10();
}
Output: 70
static blank final variable
A static fnal variable that is not initialized at the time of declaration is known
as static blank fnal variable. It can be initialized only in static block.
static{ data=50;}
System.out.println(A.data);
If you declare any parameter as fnal, you cannot change the value of it.
class Bike11{
n*n*n;
b.cube(5);
}
Output: Compile Time Error
Declaring an interface
An interface is declared by using the interface keyword. It provides total abstraction;
means all the methods in an interface are declared with the empty body, and all the
fields are public, static and final by default. A class that implements an interface must
implement all the methods declared in the interface.
Syntax:
interface interface_name
{
// declare constant fields
// declare methods that abstract
// by default.
}
Example
interface A
{
void display();
}
class B implements A
{
public void display()
{
System.out.println("Hello");
}
}
class MB
{
public static void main(String args[])
{
B obj = new B();
obj.display();
}
}
Output:
Hello
Interface Example:
In this example, the interface A has only one method. Its implementation is provided by
B and C classes. In a real scenario, an interface is defined by someone else, but its
implementation is provided by different implementation providers. Moreover, it is used
by someone else. The implementation part is hidden by the user who uses the
interface.
interface A
{
void display();
}
class B implements A
{
public void display()
{
System.out.println("Display method in B class");
}
}
class C implements B
{
public void display()
{
System.out.println("display method in C class");
}
}
class MainClass
{
public static void main(String args[])
{
D obj=new D();
obj.draw();
}
}
interface A
{
void display();
}
interface B
{
void show();
}
class C implements A,B
{
public void display()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
}
class MainClass
{
public static void main(String args[])
{
C obj = new C();
obj.display();
obj.show();
}
}
Output:
Hello
Welcome
Interface inheritance
A class implements an interface, but one interface extends another interface.
interface A
{
void display();
}
interface B extends A
{
void show();
}
class C implements B
{
public void display()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
}
Class MainClass
{
public static void main(String args[])
{
C obj = new C();
obj.display();
obj.show();
}
}
Output:
Hello
Welcome
Abstract Method
A method which is declared as abstract and does not have implementation is known as
an abstract method.
Example
abstract void display(); //no method body and abstract
1) Abstract class can have abstract and non- Interface can have only abstract methods. Since Java
abstract methods. 8, it can have default and statc methods also.
3) Abstract class can have fnal, non-fnal, statc Interface has only statc and fnal variables.
and non-statc variables.
4) Abstract class can provide the Interface can't provide the implementaton of
implementaton of interface. abstract class.
5) The abstract keyword is used to declare The interface keyword is used to declare interface.
abstract class.
6) An abstract class can extend another Java An interface can extend another Java interface only.
class and implement multple Java interfaces.
7) An abstract class can be extended using An interface can be implemented using keyword
keyword "extends". "implements".
8) A Java abstract class can have class members Members of a Java interface are public by default.
like private, protected, etc.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Polymorphism in Java
Polymorphism in Java is a concept by which we can perform a single
action in difeeent ways. Polymorphism is derived from 2 Greek words: poly
and morphs. The word "poly" means many and "morphs" means forms. So
polymorphism means many forms.
Upcasting
If the reference variable of Parent class refers to the object of Child class, it
is known as upcasting. For example:
class A{}
class B extends A{}
A a=new B();//upcasting
For upcasting, we can use the reference variable of class type or an interface
type. For Example:
interface I{}
class A{}
B IS-A A
B IS-A I
B IS-A Object
Since Object is the root class of all classes in Java, so we can write B IS-A
Object
class Bike{
void run(){System.out.println("running");}
Output:
Note: This example is also given in method overriding but there was no upcasting.
class Bank{
}
class ICICI extends Bank{
class TestPolymorphism{
Bank b;
b=new SBI();
b=new ICICI();
b=new AXIS();
Output:
void draw(){System.out.println("drawing...");}
class TestPolymorphism2{
Shape s;
s=new Rectangle();
s.draw();
s=new Circle();
s.draw();
s=new Triangle();
s.draw();
Output:
drawing rectangle...
drawing circle...
drawing triangle...
void eat(){System.out.println("eating...");}
class TestPolymorphism3{
Animal a;
a=new Dog();
a.eat();
a=new Cat();
a.eat();
a=new Lion();
a.eat();
}}
Output:
eating bread...
eating rat...
eating meat...
In the example given below, both the classes have a data member
speedlimit. We are accessing the data member by the reference variable of
Parent class which refers to the subclass object. Since we are accessing the
data member which is not overridden, hence it will access the data member
of the Parent class always.
class Bike{
int speedlimit=90;
System.out.println(obj.speedlimit);//90
Output:
90
class Animal{
void eat(){System.out.println("eating");}
Animal a1,a2,a3;
a1=new Animal();
a2=new Dog();
a3=new BabyDog();
a1.eat();
a2.eat();
a3.eat();
}
Output:
eating
eating fruits
drinking Milk
a.eat();
}}
Output:
Dog is eating
Since, BabyDog is not overriding the eat() method, so eat() method of Dog
class is invoked.
Understanding Type
Let's understand the type of instance.
int data=30;
}
3) Objects have a type
An object is an instance of particular java
class,but it is also an instance of its superclass.
class Animal{}
static binding
When type of the object is determined at compiled time(by the compiler), it
is known as static binding.
If there is any private, fnal or static method in a class, there is static binding.
d1.eat();
}
Dynamic binding
When type of the object is determined at run-time, it is known as dynamic
binding.
a.eat();
}
Output:dog is eating...
2
The Java Collection Framework
3
The Main Types of Collections
• Lists
• Sets
• Maps
4
Lists
5
Sets
6
Maps
7
Part of the JCF Hierarchy
8
9
The Collection Interface
10
Some Methods in the Collection Interface
Method Description
add(o : E) : boolean Adds an object o to the Collection. The method returns
true if o is successfully added to the collection, false
otherwise.
clear() : void Removes all elements from the collection.
11
AbstractCollection
12
Iterators
13
The Iterator Interface
14
Methods of the Iterator Interface
Method Description
15
The List Interface
16
List Interface Methods
17
The List Interface Methods
add(index:int, el:E) : Adds the element el to the collection at the given index.
void Throws IndexOutOfBoundsException if index is negative,
or greater than the size of the list.
get(index:int):E Returns the element at the given index, or throws
IndexOutBoundsException if index is negative or greater
than or equal to the size of the list.
indexOf(o:Object):int Returns the least (first) index at which the object o is
found; returns -1 if o is not in the list.
lastIndexOf(o:Object):int Returns the greatest (last) index at which the object o is
found; returns -1 if o is not in the list.
listIterator():ListIterator< Returns an iterator specialized to work with List
E> collections.
remove(index:int):E Removes and returns the element at the given index;
throws IndexOutOfBoundsException if index is negative,
or greater than or equal to the size of the list.
set(index:int, el:E):E Replaces the element at index with the new element el.
18
AbstractList
19
ArrayList and Vector
20
AbstractSequentialList and LinkedList
21
Using the Concrete List Classes
22
Example: ArrayList
import java.util.*;
public class Test
{
public static void main(String [ ] args)
{
List<String> nameList = new ArrayList<String> ();
String [ ] names = {"Ann", "Bob", "Carol"};
// Add to arrayList
for (int k = 0; k < names.length; k++)
nameList.add(names[k]);
24
Example: LinkedList
import java.util.*;
public class Test
{
public static void main(String [ ] args)
{
List<String> nameList = new LinkedList<String> ();
String [ ] names = {"Ann", "Bob", "Carol"};
// Add to arrayList
for (int k = 0; k < names.length; k++)
nameList.add(names[k]);
26
The Iterator remove() method
27
Using an Iterator
28
ListIterator
29
Some ListIterator Methods
Method Description
add(el:E):void Adds el to the list at the position just before the
element that will be returned by the next call to the
next() method.
hasPrevious():boolean Returns true if a call to the previous() method will
return an element, false if a call to previous() will throw
an exception because there is no previous element.
nextIndex():int Returns the index of the element that would be
returned by a call to next(), or the size of the list if
there is no such element.
previous():E Returns the previous element in the list. If the iterator
is at the beginning of the list, it throws
NoSuchElementException.
previousIndex():int Returns the index of the element that would be
returned by a call to previous(), or -1.
A call to next() puts the cursor just after the element returned,
and just before the element that will be returned by the next
call to next().
31
Iterator and ListIterator Exceptions
32
Example Use of a ListIterator
public static void main(String [ ] args)
{
List<String> nameList = new ArrayList<String>();
String [ ] names = {"Ann", "Bob", "Carol"};
33
Enhanced For Loop
34
Sets
35
The Set Part of the JCF Hierarchy
AbstractCollection
AbstractSet
HashSet TreeSet
LinkedHashSet
36
The Set Part of the JCF
37
HashSet
38
Examples of Hashing Functions
39
A Simplistic Hashing Function
40
Implementation of a HashSet
41
Implementation of a HashSet
42
How a HashSet Works
• To add an element X, the hash code for X is used (as
an index) to locate the appropriate bucket. X is then
added to the list for that bucket. If X is already in the
bucket (The test is done using the equals method),
then it is not added.
43
Efficiency of HashSet Operations
45
HashSet Capacity and Load Factor
46
Some HashSet Constructors
47
The hashCode() method
48
Overriding the hashCode() Method
49
HashSet Example 1
import java.util.*;
/**
This program demonstrates how to add elements
to a HashSet. It also shows that duplicate
elements are not allowed.
*/
public class HashSetDemo1
{
public static void main(String[] args)
{
// Create a HashSet to hold String objects.
Set<String> fruitSet = new HashSet<String>();
// Add some strings to the set.
fruitSet.add("Apple");
fruitSet.add("Banana");
fruitSet.add("Pear");
fruitSet.add("Strawberry");
// Display the elements in the set.
System.out.println("Here are the elements.");
for (String element : fruitSet)
System.out.println(element);
// Try to add a duplicate element.
System.out.println("\nTrying to add Banana to " +
"the set again...");
if (!fruitSet.add("Banana"))
System.out.println("Banana was not added again.");
// Display the elements in the set.
System.out.println("\nHere are the elements once more.");
for (String element : fruitSet)
System.out.println(element);
}
}
50
A Car Class for Use With a HashSet
class Car
{
String vin, description;
public boolean equals(Object other) // Depends on vin only
{
if (!(other instanceof Car))
return false;
else
return vin.equalsIgnoreCase(((Car)other).vin);
}
52
Use of the Car Class with a HashSet
public static void main(String [ ] args)
{
Set<Car> carSet = new HashSet<Car>();
Car [ ] myRides = {
new Car("TJ1", "Toyota"),
new Car("GM1", "Corvette"),
new Car("TJ1", "Toyota Corolla")
};
// Add the cars to the HashSet
for (Car c : myRides)
carSet.add(c);
GM1 Corvette
TJ1 Toyota
Note:
• The iterator does not return items in the order added to the
HashSet.
• The entry of the Toyota Corolla is rejected because it is equal
to an entry already stored (same vin).
54
HashSet Example 2
import java.util.*;
/**
This program creates a HashSet, adds some
names to it, gets an iterator for the set,
and searches the set for names.
*/
public class HashSetDemo2
{
public static void main(String[] args)
{
// Create a HashSet to hold names.
Set<String> nameSet = new HashSet<String>();
// Add some names to the set.
nameSet.add("Chris");
nameSet.add("David");
nameSet.add("Katherine");
nameSet.add("Kenny");
// Get an iterator for the set.
Iterator it = nameSet.iterator();
55
HashSet Example 2
// Display the elements in the set.
System.out.println("Here are the names in the set.");
while (it.hasNext())
System.out.println(it.next());
System.out.println();
// Search for "Katherine". We should find this
// name in the set.
if (nameSet.contains("Katherine"))
System.out.println("Katherine is in the set.");
else
System.out.println("Katherine is NOT in the set.");
// Search for "Bethany". We should not find
// this name in the set.
if (nameSet.contains("Bethany"))
System.out.println("Bethany is in the set.");
else
System.out.println("Bethany is NOT in the set.");
}
}
56
HashSet Example 3
/**
The Car class stores a VIN (Vehicle Identification
Number) and a description for a car.
*/
public class Car
{
private String vin; // Vehicle Identification Number
private String description; // Car description
/**
Constructor
@param v The VIN for the car.
@param desc The description of the car.
*/
public Car(String v, String desc)
{
vin = v;
description = desc;
}
/**
getVin method
@return The car's VIN.
*/
public String getVin()
{
return vin;
}
57
HashSet Example 3
/**
getDescription method
@return The car's description.
*/
public String getDescription()
{
return description;
}
/**
toString method
@return A string containing the VIN and description.
*/
public String toString()
{
return "VIN: " + vin +
"\tDescription: " +
description;
}
/**
hashCode method
@return A hash code for this car.
*/
public int hashCode()
{
return vin.hashCode();
}
58
HashSet Example 3
/**
equals method
@param obj Another object to compare this object to.
@return true if the two objects are equal, false otherwise.
*/
public boolean equals(Object obj)
{
// Make sure the other object is a Car.
if (obj instanceof Car)
{
// Get a Car reference to obj.
Car tempCar = (Car) obj;
// Compare the two VINs. If the VINs are
// the same, then they are the same car.
if (vin.equalsIgnoreCase(tempCar.vin))
return true;
else
return false;
}
else
return false;
}
}
59
HashSet Example 3
import java.util.*;
/**
This program stores Car objects in a HashSet and then
searches for various objects.
*/
public class CarHashSet
{
public static void main(String[] args)
{
// Create a HashSet to store Car objects.
Set<Car> carSet = new HashSet<Car>();
// Add some Car objects to the HashSet.
carSet.add(new Car("227H54", "1997 Volkswagen"));
carSet.add(new Car("448A69", "1965 Mustang"));
carSet.add(new Car("453B55", "2007 Porsche"));
carSet.add(new Car("177R60", "1980 BMW"));
// Display the elements in the HashSet.
System.out.println("Here are the cars in the set:");
for (Car c : carSet)
System.out.println(c);
System.out.println();
60
HashSet Example 3
// Search for a specific car. This one is in the set.
Car mustang = new Car("448A69", "1965 Mustang");
System.out.println("Searching for " + mustang);
if (carSet.contains(mustang))
System.out.println("The Mustang is in the set.");
else
System.out.println("The Mustang is NOT in the set.");
// Search for another car. This one is not in the set.
Car plymouth = new Car("911C87", "2000 Plymouth");
System.out.println("Searching for " + plymouth);
if (carSet.contains(plymouth))
System.out.println("The Plymouth is in the set.");
else
System.out.println("The Plymouth is NOT in the set.");
}
}
61
LinkedHashSet
62
TreeSet
63
Order
64
Examples of Natural Orders
65
The Comparable Interface
66
Using a TreeSet with Comparable Elements
67
Sorting Strings Using a TreeSet
import java.util.*;
public class Test
{
public static void main(String [ ] args)
{
// Create TreeSet
Set<String> mySet = new TreeSet<String>();
// Add Strings
mySet.add("Alan");
mySet.add("Carol");
mySet.add("Bob");
// Get Iterator
Iterator it = mySet.iterator();
while (it.hasNext())
{
System.out.println(it.next());
}
}
}
68
The SortedSet Interface
69
Comparators
70
The Comparator Interface
72
A Comparator for Ordering Strings in Reverse
Alphabetic Order
import java.util.*;
class RevStrComparator implements Comparator<String>
{
public int compare(String s1, String s2)
{
return - s1.compareTo(s2); // Note the negation operator
}
}
73
Using a TreeSet to Sort Strings in Reverse
Alphabetic Order
public class Test
{
public static void main(String [ ] args)
{ // Create Comparator
RevStrComparator comp = new RevStrComparator();
Set<String> mySet = new TreeSet<String>(comp);
// Add strings
mySet.add("Alan");
mySet.add("Carol");
mySet.add("Bob");
// Get Iterator
Iterator it = mySet.iterator();
while (it.hasNext())
{
System.out.println(it.next());
}
}
}
74
TreeSet Example 1
import java.util.*;
/**
This program demonstrates how a TreeSet
sorts its elements in ascending order.
*/
public class TreeSetDemo1
{
public static void main(String[] args)
{
// Create a TreeSet and store some values in it.
SortedSet<String> mySet = new TreeSet<String>();
mySet.add("Pear");
mySet.add("Apple");
mySet.add("Strawberry");
mySet.add("Banana");
// Display the elements in the TreeSet.
System.out.println("Here are the TreeSet elements " +
"in ascending order:");
for (String str : mySet)
System.out.println(str);
// Add a new element to the TreeSet.
System.out.println("\nAdding Blueberry to the set.");
mySet.add("Blueberry");
// Display the elements again.
System.out.println("\nHere are the TreeSet elements " +
"again:");
for (String str : mySet)
System.out.println(str);
}
}
75
TreeSet Example 2
import java.util.Comparator;
public class CarComparator<T extends Car>
implements Comparator<T>
{
public int compare(T car1, T car2)
{
// Get the two cars' VINs.
String vin1 = car1.getVin();
String vin2 = car2.getVin();
// Compare the VINs and return the
// result of the comparison.
return vin1.compareToIgnoreCase(vin2);
}
}
76
TreeSet Example 2
import java.util.*;
/**
This program demonstrates how a TreeSet
can use a Comparator to sort its elements.
*/
public class TreeSetDemo2
{
public static void main(String[] args)
{
// Create a TreeSet and pass an instance of
// CarComparator to it.
SortedSet<Car> carSet =
new TreeSet<Car>( new CarComparator<Car>() );
// Add some Car objects to the TreeSet.
carSet.add(new Car("227H54", "1997 Volkswagen"));
carSet.add(new Car("453B55", "2007 Porsche"));
carSet.add(new Car("177R60", "1980 BMW"));
carSet.add(new Car("448A69", "1965 Mustang"));
// Display the elements in the TreeSet.
System.out.println("Here are the cars sorted in " +
"order of their VINs:");
for (Car car : carSet)
System.out.println(car);
}
}
77
Maps
The map stores the mappings based on the key part of the
mapping, in a way similar to how a Set collection stores its
elements.
78
The Map Part of the JCF Hierarchy
Map
AbstractMap
HashMap TreeMap
LinkedHashMap
79
The Map Interface
80
Some Methods of the Map Interface
keySet() : Set<K> Returns the set of all keys stored in the map.
81
Some Methods of the Map Interface
82
Concrete Map Classes
83
HashMap Example 1
import java.util.*;
/**
This program stores mappings in a HashMap and then
searches for various objects.
*/
public class CarHashMap1
{
public static void main(String[] args)
{
// Create a HashMap to store Car objects.
Map<String, Car> carMap =
new HashMap<String, Car>();
// Create some Car objects.
Car vw = new Car("227H54", "1997 Volkswagen");
Car mustang = new Car("448A69", "1965 Mustang");
Car porsche = new Car("453B55", "2007 Porsche");
Car bmw = new Car("177R60", "1980 BMW");
// Put some mappings into the HashMap. In each
// mapping, the car's VIN is the key and the
// Car object containing that VIN is the value.
carMap.put(vw.getVin(), vw);
carMap.put(mustang.getVin(), mustang);
carMap.put(porsche.getVin(), porsche);
carMap.put(bmw.getVin(), bmw);
84
HashMap Example 1
// Search for the Mustang by its VIN.
System.out.println("\nSearching for the car with " +
"VIN " + mustang.getVin());
Car foundCar = carMap.get(mustang.getVin());
// If the car was found, display it.
if (foundCar != null)
System.out.println(foundCar);
else
System.out.println("The Mustang is NOT in the set.");
// Search for another VIN. This one is not in the set.
System.out.println("\nSearching for the car with " +
"VIN 911C87");
foundCar = carMap.get("911C87");
// If the car was found display it.
if (foundCar != null)
System.out.println(foundCar);
else
System.out.println("That car is NOT in the set.");
}
}
85
HashMap Example 2
import java.util.*;
/**
This program retrieves a set of keys and a
collection of values from a HashMap.
*/
public class CarHashMap2
{
public static void main(String[] args)
{
// Create a HashMap to store Car objects.
Map<String, Car> carMap =
new HashMap<String, Car>();
// Create some Car objects.
Car vw = new Car("227H54", "1997 Volkswagen");
Car mustang = new Car("448A69", "1965 Mustang");
Car porsche = new Car("453B55", "2007 Porsche");
Car bmw = new Car("177R60", "1980 BMW");
// Put some mappings into the HashMap. In each
// mapping, the car's VIN is the key and the
// Car object containing that VIN is the value.
carMap.put(vw.getVin(), vw);
carMap.put(mustang.getVin(), mustang);
carMap.put(porsche.getVin(), porsche);
carMap.put(bmw.getVin(), bmw);
86
HashMap Example 2
// Get a set containing the keys in this map.
Set<String> keys = carMap.keySet();
// Iterate through the keys, printing each one.
System.out.println("Here are the keys:");
for (String k : keys)
System.out.println(k);
// Get a collection containing the values.
Collection<Car> values = carMap.values();
// Iterate through the values, printing each one.
System.out.println("\nHere are the values:");
for (Car c : values)
System.out.println(c);
}
}
87
HashMap Example 3
import java.util.*;
/**
This program retrieves the mappings from a HashMap
as a Set of Map.Entry objects.
*/
public class CarHashMap3
{
public static void main(String[] args)
{
// Create a HashMap to store Car objects.
Map<String, Car> carMap =
new HashMap<String, Car>();
// Create some Car objects.
Car vw = new Car("227H54", "1997 Volkswagen");
Car mustang = new Car("448A69", "1965 Mustang");
Car porsche = new Car("453B55", "2007 Porsche");
Car bmw = new Car("177R60", "1980 BMW");
// Put some mappings into the HashMap. In each
// mapping, the car's VIN is the key and the
// Car object containing that VIN is the value.
carMap.put(vw.getVin(), vw);
carMap.put(mustang.getVin(), mustang);
carMap.put(porsche.getVin(), porsche);
carMap.put(bmw.getVin(), bmw);
88
HashMap Example 3
// Get a set containing the mappings in this map.
Set<Map.Entry<String, Car>> cars = carMap.entrySet();
// Iterate through the mappings, printing each one.
System.out.println("Here are the mappings:");
for (Map.Entry<String, Car> entry : cars)
{
System.out.println("Key = " + entry.getKey());
System.out.println("Value = " + entry.getValue());
System.out.println();
}
}
}
89
HashMap Example 4
import java.util.*;
/**
This program retrieves the mappings from a
LinkedHashMap as a Set of Map.Entry objects.
*/
public class CarHashMap4
{
public static void main(String[] args)
{
// Create a LinkedHashMap to store Car objects.
Map<String, Car> carMap =
new LinkedHashMap<String, Car>();
// Create some Car objects.
Car vw = new Car("227H54", "1997 Volkswagen");
Car mustang = new Car("448A69", "1965 Mustang");
Car porsche = new Car("453B55", "2007 Porsche");
Car bmw = new Car("177R60", "1980 BMW");
90
HashMap Example 4
// Put some mappings into the LinkedHashMap. In
// each mapping, the car's VIN is the key and the
// Car object containing that VIN is the value.
carMap.put(vw.getVin(), vw);
carMap.put(mustang.getVin(), mustang);
carMap.put(porsche.getVin(), porsche);
carMap.put(bmw.getVin(), bmw);
// Get a set containing the mappings in this map.
Set<Map.Entry<String, Car>> cars = carMap.entrySet();
// Iterate through the mappings, printing each one.
System.out.println("Here are the mappings:");
for (Map.Entry<String, Car> entry : cars)
{
System.out.println("Key = " + entry.getKey());
System.out.println("Value = " + entry.getValue());
System.out.println();
}
}
}
91
HashMap Example 5
import java.util.*;
/**
This program displays the mappings stored in a
TreeMap. The mappings are displayed in ascending
key order.
*/
public class CarHashMap5
{
public static void main(String[] args)
{
// Create a TreeMap to store Car objects.
SortedMap<String, Car> carMap =
new TreeMap<String, Car>();
// Create some Car objects.
Car vw = new Car("227H54", "1997 Volkswagen");
Car mustang = new Car("448A69", "1965 Mustang");
Car porsche = new Car("453B55", "2007 Porsche");
Car bmw = new Car("177R60", "1980 BMW");
// Put some mappings into the TreeMap. In each
// mapping, the car's VIN is the key and the
// Car object containing that VIN is the value.
carMap.put(vw.getVin(), vw);
carMap.put(mustang.getVin(), mustang);
carMap.put(porsche.getVin(), porsche);
carMap.put(bmw.getVin(), bmw);
92
HashMap Example 5
// Get a set containing the mappings in this map.
Set<Map.Entry<String, Car>> cars = carMap.entrySet();
// Iterate through the mappings, printing each one.
System.out.println("Here are the mappings:");
for (Map.Entry<String, Car> entry : cars)
{
System.out.println("Key = " + entry.getKey());
System.out.println("Value = " + entry.getValue());
System.out.println();
}
}
}
93
Exception handling in java with examples
Exception handling is one of the most important feature of java programming that allows us to handle the
runtime errors caused by exceptions. In this guide, we will learn what is an exception, types of it, exception
classes and how to handle exceptions in java with examples.
What is an exception?
An Exception is an unwanted event that interrupts the normal flow of the program. When an exception
occurs program execution gets terminated. In such cases we get a system generated error message. The good
thing about exceptions is that they can be handled in Java. By handling the exceptions we can provide a
meaningful message to the user about the issue rather than a system generated message, which may not be
understandable to a user.
There can be several reasons that can cause a program to throw exception. For example: Opening a non-
existing file in your program, Network connection problem, bad input data provided by user etc.
Exception Handling
If an exception occurs, which has not been handled by programmer then program execution gets terminated
and a system generated error message is shown to the user. For example look at the system generated
exception below:
This message is not user friendly so a user will not be able to understand what went wrong. In order to let
them know the reason in simple language, we handle exceptions. We handle such conditions and then prints
a user friendly warning message to user, which lets them correct the error as most of the time exception
occurs due to bad data provided by user.
Exception handling ensures that the flow of the program doesn’t break when an exception occurs. For
example, if a program has bunch of statements and an exception occurs mid way after executing certain
statements then the statements after the exception will not execute and the program will terminate abruptly.
By handling we make sure that all the statements execute and the flow of program doesn’t break.
Difference between error and exception
Errors indicate that something severe enough has gone wrong, the application should crash rather than try to
handle the error.
Exceptions are events that occurs in the code. A programmer can handle such conditions and take necessary
corrective actions. Few examples:
NullPointerException – When you try to use a reference that points to null.
ArithmeticException – When bad data is provided by user, for example, when you try to divide a number by
zero this exception occurs because dividing a number by zero is undefined.
ArrayIndexOutOfBoundsException – When you try to access the elements of an array out of its bounds, for
example array size is 5 (which means it has five elements) and you are trying to access the 10th element.
Types of exceptions
Checked exceptions
All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler checks
them during compilation to see whether the programmer has handled them or not. If these exceptions are not
handled/declared in the program, you will get compilation error. For example, SQLException, IOException,
ClassNotFoundException etc.
Unchecked Exceptions
Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are not checked at compile-
time so compiler does not check whether the programmer has handled them or not but it’s the responsibility
of the programmer to handle these exceptions and provide a safe exit. For example, ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException etc.
Compiler will never force you to catch such exception or force you to declare it in the method using throws
keyword.
In the previous tutorial we discussed what is exception handling and why we do it. In this tutorial we will see
try-catch block which is used for exception handling.
Try block
The try block contains set of statements where an exception can occur. A try block is always followed by a
catch block, which handles the exception that occurs in associated try block. A try block must be followed
by catch blocks or finally block or both.
try{
//statements that may cause an exception
}
While writing a program, if you think that certain statements in a program can throw a exception, enclosed
them in try block and handle that exception
Catch block
A catch block is where you handle the exceptions, this block must follow the try block. A single try block
can have several catch blocks associated with it. You can catch different exceptions in different catch blocks.
When an exception occurs in try block, the corresponding catch block that handles that particular exception
executes. For example if an arithmetic exception occurs in try block then the statements enclosed in catch
block for arithmetic exception executes.
try
{
//statements that may cause an exception
}
catch (exception(type) e(object
{
//error handling code
}
If an exception occurs in try block then the control of execution is passed to the corresponding catch block.
A single try block can have multiple catch blocks associated with it, you should place the catch blocks in
such a way that the generic exception handler catch block is at the last(see in the example below).
The generic exception handler can handle all the exceptions but you should place is at the end, if you place it
at the before all the catch blocks then it will display the generic message. You always want to give the user a
meaningful message for each type of exception rather then a generic message.
class Example1 {
public static void main(String args[]) {
int num1, num2;
try {
/* We suspect that this block of statement can throw
* exception so we handled it by placing these statements
* inside try and handled the exception in catch block
*/
num1 = 0;
num2 = 62 / num1;
System.out.println(num2);
System.out.println("Hey I'm at the end of try block");
}
catch (ArithmeticException e) {
/* This block will only execute if any Arithmetic exception
* occurs in try block
*/
System.out.println("You should not divide a number by zero");
}
catch (Exception e) {
/* This is a generic Exception handler which means it can handle
* all the exceptions. This will execute if the exception is not
* handled by previous catch blocks.
*/
System.out.println("Exception occurred");
}
System.out.println("I'm out of try-catch block in Java.");
}
}
Output:
The example we seen above is having multiple catch blocks, lets see few rules about multiple catch blocks
with the help of examples. To read this in detail, see catching multiple exceptions in java.
1. As I mentioned above, a single try block can have any number of catch blocks.
2. A generic catch block can handle all the exceptions. Whether it is ArrayIndexOutOfBoundsException or
ArithmeticException or NullPointerException or any other type of exception, this handles all of them. To see
the examples of NullPointerException and ArrayIndexOutOfBoundsException,.
catch(Exception e){
//This catch block catches all the exceptions
}
If you are wondering why we need other catch handlers when we have a generic that can handle all. This is
because in generic exception handler you can display a message but you are not sure for which type of
exception it may trigger so it will display the same message for all the exceptions and user may not be able
to understand which exception occurred. Thats the reason you should place is at the end of all the specific
exception catch blocks
3. If no exception occurs in try block then the catch blocks are completely ignored.
4. Corresponding catch blocks execute for that specific type of exception:
catch(ArithmeticException e) is a catch block that can hanlde ArithmeticException
catch(NullPointerException e) is a catch block that can handle NullPointerException
5. You can also throw exception,
class Example2{
public static void main(String args[]){
try{
int a[]=new int[7];
a[4]=30/0;
System.out.println("First print statement in try block");
}
catch(ArithmeticException e){
System.out.println("Warning: ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Warning: ArrayIndexOutOfBoundsException");
}
catch(Exception e){
System.out.println("Warning: Some Other exception");
}
System.out.println("Out of try-catch block...");
}
}
Output:
Warning: ArithmeticException
Out of try-catch block...
In the above example there are multiple catch blocks and these catch blocks executes sequentially when an
exception occurs in try block. Which means if you put the last catch block ( catch(Exception e)) at the first
place, just after try block then in case of any exception this block will execute as it can handle all exceptions.
This catch block should be placed at the last to avoid such situations.
Finally block
I have covered this in a separate tutorial here: java finally block. For now you just need to know that this
block executes whether an exception occurs or not. You should place those statements in finally blocks, that
must execute whether exception occurs or not.
In the previous tutorial, I have covered how to handle exceptions using try-catch blocks. In this guide, we
will see how to handle multiple exceptions and how to write them in a correct order so that user gets a
meaningful message for each type of exception.
Catching multiple exceptions
class Example{
public static void main(String args[]){
try{
int arr[]=new int[7];
arr[4]=30/0;
System.out.println("Last Statement of try block");
}
catch(ArithmeticException e){
System.out.println("You should not divide a number by zero");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Accessing array elements outside of the limit");
}
catch(Exception e){
System.out.println("Some Other Exception");
}
System.out.println("Out of the try-catch block");
}
}
Output:
In the above example, the first catch block got executed because the code we have written in try block
throws ArithmeticException (because we divided the number by zero).
Now lets change the code a little bit and see the change in output:
class Example{
public static void main(String args[]){
try{
int arr[]=new int[7];
arr[10]=10/5;
System.out.println("Last Statement of try block");
}
catch(ArithmeticException e){
System.out.println("You should not divide a number by zero");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Accessing array elements outside of the limit");
}
catch(Exception e){
System.out.println("Some Other Exception");
}
System.out.println("Out of the try-catch block");
}
}
Output:
Accessing array elements outside of the limit
Out of the try-catch block
In this case, the second catch block got executed because the code throws
ArrayIndexOutOfBoundsException. We are trying to access the 11th element of array in above program but
the array size is only 7.
class Example{
public static void main(String args[]){
try{
int arr[]=new int[7];
arr[10]=10/5;
System.out.println("Last Statement of try block");
}
catch(Exception e){
System.out.println("Some Other Exception");
}
catch(ArithmeticException e){
System.out.println("You should not divide a number by zero");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Accessing array elements outside of the limit");
}
System.out.println("Out of the try-catch block");
}
}
Output:
When a try catch block is present in another try block then it is called the nested try catch block. Each time a
try block does not have a catch handler for a particular exception, then the catch blocks of parent try block
are inspected for that exception, if match is found that that catch block executes.
If neither catch block nor parent catch block handles exception then the system generated message would be
shown for the exception, similar to what we see when we don’t handle exception.
Lets see the syntax first then we will discuss this with an example.
....
//Main try block
try {
statement 1;
statement 2;
//try-catch block inside another try block
try {
statement 3;
statement 4;
//try-catch block inside nested try block
try {
statement 5;
statement 6;
}
catch(Exception e2) {
//Exception Message
}
}
catch(Exception e1) {
//Exception Message
}
}
//Catch of Main(parent) try block
catch(Exception e3) {
//Exception Message
}
....
Here we have deep (two level) nesting which means we have a try-catch block inside a nested try block. To
make you understand better I have given the names to each try block in comments like try-block2, try-
block3 etc.
This is how the structure is: try-block3 is inside try-block2 and try-block2 is inside main try-block, you can
say that the main try-block is a grand parent of the try-block3. Refer the explanation which is given at the
end of this code.
class NestingDemo{
public static void main(String args[]){
//main try-block
try{
//try-block2
try{
//try-block3
try{
int arr[]= {1,2,3,4};
/* I'm trying to display the value of
* an element which doesn't exist. The
* code should throw an exception
*/
System.out.println(arr[10]);
}catch(ArithmeticException e){
System.out.print("Arithmetic Exception");
System.out.println(" handled in try-block3");
}
}
catch(ArithmeticException e){
System.out.print("Arithmetic Exception");
System.out.println(" handled in try-block2");
}
}
catch(ArithmeticException e3){
System.out.print("Arithmetic Exception");
System.out.println(" handled in main try-block");
}
catch(ArrayIndexOutOfBoundsException e4){
System.out.print("ArrayIndexOutOfBoundsException");
System.out.println(" handled in main try-block");
}
catch(Exception e5){
System.out.print("Exception");
System.out.println(" handled in main try-block");
}
}
}
Output:
As you can see that the ArrayIndexOutOfBoundsException occurred in the grand child try-block3. Since try-
block3 is not handling this exception, the control then gets transferred to the parent try-block2 and looked
for the catch handlers in try-block2. Since the try-block2 is also not handling that exception, the control gets
transferred to the main (grand parent) try-block where it found the appropriate catch block for exception.
This is how the the nesting structure works.
class Nest{
public static void main(String args[]){
//Parent try block
try{
//Child try block1
try{
System.out.println("Inside block1");
int b =45/0;
System.out.println(b);
}
catch(ArithmeticException e1){
System.out.println("Exception: e1");
}
//Child try block2
try{
System.out.println("Inside block2");
int b =45/0;
System.out.println(b);
}
catch(ArrayIndexOutOfBoundsException e2){
System.out.println("Exception: e2");
}
System.out.println("Just other statement");
}
catch(ArithmeticException e3){
System.out.println("Arithmetic Exception");
System.out.println("Inside parent try catch block");
}
catch(ArrayIndexOutOfBoundsException e4){
System.out.println("ArrayIndexOutOfBoundsException");
System.out.println("Inside parent try catch block");
}
catch(Exception e5){
System.out.println("Exception");
System.out.println("Inside parent try catch block");
}
System.out.println("Next statement..");
}
}
Output:
Inside block1
Exception: e1
Inside block2
Arithmetic Exception
Inside parent try catch block
Next statement..
This is another example that shows how the nested try block works. You can see that there are two try-catch
block inside main try block’s body. I’ve marked them as block 1 and block 2 in above example.
Block1: I have divided an integer by zero and it caused an ArithmeticException, since the catch of block1 is
handling ArithmeticException "Exception: e1" displayed.
The important point to note here is that whenever the child catch blocks are not handling any exception, the
jumps to the parent catch blocks, if the exception is not handled there as well then the program will
terminate abruptly showing system generated message.
In the previous tutorials I have covered try-catch block and nested try block. In this guide, we will see finally
block which is used along with try-catch.
A finally block contains all the crucial statements that must be executed whether exception occurs or not.
The statements present in this block will always execute regardless of whether exception occurs in try block
or not such as closing a connection, stream etc.
try {
//Statements that may cause an exception
}
catch {
//Handling exception
}
finally {
//Statements to be executed
}
A Simple Example of finally block
Here you can see that the exception occurred in try block which has been handled in catch block, after that
finally block got executed.
class Example
{
public static void main(String args[]) {
try{
int num=121/0;
System.out.println(num);
}
catch(ArithmeticException e){
System.out.println("Number should not be divided by zero");
}
/* Finally block will always execute
* even if there is no exception in try block
*/
finally{
System.out.println("This is finally block");
}
System.out.println("Out of try-catch-finally");
}
}
Output:
1. A finally block must be associated with a try block, you cannot use finally without a try block. You should
place those statements in this block that must be executed always.
2. Finally block is optional, as we have seen in previous tutorials that a try-catch block is sufficient
for exception handling, however if you place a finally block then it will always run after the execution of try
block.
3. In normal case when there is no exception in try block then the finally block is executed after try block.
However if an exception occurs then the catch block is executed before finally block.
4. An exception in the finally block, behaves exactly like any other exception.
5. The statements present in the finally block execute even if the try block contains control transfer
statements like return, break or continue.
Lets see an example to see how finally works when return statement is present in try block:
You can see that even though we have return statement in the method, the finally block still runs.
class JavaFinally
{
public static void main(String args[])
{
System.out.println(JavaFinally.myMethod());
}
public static int myMethod()
{
try {
return 112;
}
finally {
System.out.println("This is Finally block");
System.out.println("Finally block ran even after return statement");
}
}
}
Output of above program:
The circumstances that prevent execution of the code in a finally block are:
– The death of a Thread
– Using of the System. exit() method.
– Due to an exception arising in the finally block.
close() statement is used to close all the open streams in a program. Its a good practice to use close() inside
finally block. Since finally block executes even if exception occurs so you can be sure that all input and
output streams are closed properly regardless of whether the exception occurs or not.
For example:
....
try{
OutputStream osf = new FileOutputStream( "filename" );
OutputStream osb = new BufferedOutputStream(opf);
ObjectOutput op = new ObjectOutputStream(osb);
try{
output.writeObject(writableObject);
}
finally{
op.close();
}
}
catch(IOException e1){
System.out.println(e1);
}
...
Finally block without catch
A try-finally block is possible without catch block. Which means a try block can be used with finally without
having a catch block.
...
InputStream input = null;
try {
input = new FileInputStream("inputfile.txt");
}
finally {
if (input != null) {
try {
in.close();
}catch (IOException exp) {
System.out.println(exp);
}
}
}
...
Finally block and System.exit()
System.exit() statement behaves differently than return statement. Unlike return statement whenever
System.exit() gets called in try block then Finally block doesn’t execute. Here is a code snippet that
demonstrate the same:
....
try {
//try block
System.out.println("Inside try block");
System.exit(0)
}
catch (Exception exp) {
System.out.println(exp);
}
finally {
System.out.println("Java finally block");
}
....
In the above example if the System.exit(0) gets called without any exception then finally won’t execute.
However if any exception occurs while calling System.exit(0) then finally block will be executed.
try-catch-finally block
Either a try statement should be associated with a catch block or with finally.
Since catch performs exception handling and finally performs the cleanup, the best approach is to use
both of them.
Syntax:
try {
//statements that may cause an exception
}
catch {
//error handling code
}
finally {
//statements to be executed
}
Examples of Try catch finally blocks
Example 1: The following example demonstrate the working of finally block when no exception occurs in
try block
class Example1{
public static void main(String args[]){
try{
System.out.println("First statement of try block");
int num=45/3;
System.out.println(num);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("ArrayIndexOutOfBoundsException");
}
finally{
System.out.println("finally block");
}
System.out.println("Out of try-catch-finally block");
}
}
Output:
First statement of try block
15
finally block
Out of try-catch-finally block
Example 2: This example shows the working of finally block when an exception occurs in try block but is
not handled in the catch block:
class Example2{
public static void main(String args[]){
try{
System.out.println("First statement of try block");
int num=45/0;
System.out.println(num);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("ArrayIndexOutOfBoundsException");
}
finally{
System.out.println("finally block");
}
System.out.println("Out of try-catch-finally block");
}
}
Output:
Example 3: When exception occurs in try block and handled properly in catch block
class Example3{
public static void main(String args[]){
try{
System.out.println("First statement of try block");
int num=45/0;
System.out.println(num);
}
catch(ArithmeticException e){
System.out.println("ArithmeticException");
}
finally{
System.out.println("finally block");
}
System.out.println("Out of try-catch-finally block");
}
}
Output:
We can define our own set of conditions or rules and throw an exception explicitly using throw keyword.
For example, we can throw ArithmeticException when we divide number by 5, or any other numbers, what
we need to do is just set the condition and throw any exception using throw keyword. Throw keyword can
also be used for throwing custom exceptions, I have covered that in a separate tutorial, see Custom
Exceptions in Java.
Lets say we have a requirement where we we need to only register the students when their age is less than 12
and weight is less than 40, if any of the condition is not met then the user should get an ArithmeticException
with the warning message “Student is not eligible for registration”. We have implemented the logic by
placing the code in the method that checks student eligibility if the entered student age and weight doesn’t
met the criteria then we throw the exception using throw keyword.
As we know that there are two types of exception checked and unchecked. Checked exception (compile
time force you to handle them, if you don’t handle them then the program will not compile.
On the other hand unchecked exception Runtime doesn’t get checked during compilation. Throws
keyword is used for handling checked exceptions . By using throws we can declare multiple exceptions in
one go.
What is the need of having throws keyword when you can handle exception using try-catch?
Well, thats a valid question. We already know we can handle exceptions using try-catch block.
The throws does the same thing that try-catch does but there are some cases where you would prefer throws
over try-catch. For example:
Lets say we have a method myMethod() that has statements that can throw either ArithmeticException or
NullPointerException, in this case you can use try-catch as shown below:
One way to overcome this problem is by using throws like this: declare the exceptions in the method
signature using throws and handle the exceptions where you are calling this method by using try-catch.
Another advantage of using this approach is that you will be forced to handle the exception when you call
this method, all the exceptions that are declared using throws, must be handled where you are calling this
method else you will get compilation error.
In this example the method myMethod() is throwing two checked exceptions so we have declared these
exceptions in the method signature using throws Keyword. If we do not declare these exceptions then the
program will throw a compilation error.
import java.io.*;
class ThrowExample {
void myMethod(int num)throws IOException, ClassNotFoundException{
if(num==1)
throw new IOException("IOException Occurred");
else
throw new ClassNotFoundException("ClassNotFoundException");
}
}
In java we have already defined, exception classes such as ArithmeticException, NullPointerException etc.
These exceptions are already set to trigger on pre-defined conditions such as when you divide a number by
zero it triggers ArithmeticException, In the last tutorial we learnt how to throw these exceptions explicitly
based on your conditions using throw keyword.
In java we can create our own exception class and throw that exception using throw keyword. These
exceptions are known as user-defined or custom exceptions. In this tutorial we will see how to create your
own custom exception and throw it on a particular condition.
To understand this tutorial you should have the basic knowledge of try-catch block and throw in java.
class Example1{
public static void main(String args[]){
try{
System.out.println("Starting of try block");
// I'm throwing the custom exception using throw
throw new MyException("This is My error Message");
}
catch(MyException exp){
System.out.println("Catch Block") ;
System.out.println(exp) ;
}
}
}
Output:
Explanation:
You can see that while throwing custom exception I gave a string in parenthesis ( throw new
MyException("This is My error Message"); . That’s why we have a parameterized constructor (with a String
parameter) in my custom exception class.
Notes:
1. User-defined exception must extend Exception class.
2. The exception is thrown using throw keyword.
Another Example of Custom Exception
In this example we are throwing an exception from a method. In this case we should use throws clause in the
method signature otherwise you will get compilation error saying that “unhandled exception in method”. To
understand how throws clause works, refer this guide: throws keyword in java.
In this tutorial, we will see examples of few frequently used exceptions. If you looking for exception
handling tutorial refer this complete guide: Exception handling in Java.
Class: Java.lang.ArithmeticException
This is a built-in-class present in java.lang package. This exception occurs when an integer is divided by
zero.
class Example1
{
public static void main(String args[])
{
try{
int num1=30, num2=0;
int output=num1/num2;
System.out.println ("Result: "+output);
}
catch(ArithmeticException e){
System.out.println ("You Shouldn't divide a number by zero");
}
}
}
Output of above program:
Class: Java.lang.ArrayIndexOutOfBoundsException
This exception occurs when you try to access the array index which does not exist. For example, If array is
having only 5 elements and we are trying to display 7th element then it would throw this exception.
class ExceptionDemo2
{
public static void main(String args[])
{
try{
int a[]=new int[10];
//Array has only 10 elements
a[11] = 9;
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println ("ArrayIndexOutOfBounds");
}
}
}
Output:
ArrayIndexOutOfBounds
In the above example the array is initialized to store only 10 elements indexes 0 to 9. Since we are try to
access element of index 11, the program is throwing this exception.
Class: Java.lang.NumberFormatException
class ExceptionDemo3
{
public static void main(String args[])
{
try{
int num=Integer.parseInt ("XYZ") ;
System.out.println(num);
}catch(NumberFormatException e){
System.out.println("Number format exception occurred");
}
}
}
Output:
Class: Java.lang.StringIndexOutOfBoundsException
An object of this class gets created whenever an index is invoked of a string, which is not in the
range.
Each character of a string object is stored in a particular index starting from 0.
To get a character present in a particular index of a string we can use a method
charAt(int) of java.lang.String where int argument is the index.
E.g.
class ExceptionDemo4
{
public static void main(String args[])
{
try{
String str="beginnersbook";
System.out.println(str.length());;
char c = str.charAt(0);
c = str.charAt(40);
System.out.println(c);
}catch(StringIndexOutOfBoundsException e){
System.out.println("StringIndexOutOfBoundsException!!");
}
}
}
Output:
13
StringIndexOutOfBoundsException!!
Exception occurred because the referenced index was not present in the String.
class Exception2
{
public static void main(String args[])
{
try{
String str=null;
System.out.println (str.length());
}
catch(NullPointerException e){
System.out.println("NullPointerException..");
}
}
}
Output:
NullPointerException..
Here, length() is the function, which should be used on an object. However in the above
example String object str is null so it is not an object due to which NullPointerException occurred.
File Handling
Files
• Files are stored are stored on disks
• Each files consist of multiple lines composed
of characters
• Each line ends with an end of line character
• The file itself may have an end of file character
• Programmers often need to read or write files
stored on disks
Streams
• Stream: an object that either delivers data to its destination (screen, file,
etc.) or that takes data from a source (keyboard, file, etc.)
– it acts as a buffer between the data source and destination
• Input stream: a stream that provides input to a program
– System.in is an input stream
• Output stream: a stream that accepts output from a program
– System.out is an output stream
• A stream connects a program to an I/O object
– System.out connects a program to the screen
– System.in connects a program to the keyboard
Text File I/O
• Important classes for text file output (to the file)
– PrintWriter
– FileOutputStream [or FileWriter]
• Important classes for text file input (from the file):
– BufferedReader
– FileReader
• FileOutputStream and FileReader take file names as arguments.
• PrintWriter and BufferedReader provide useful methods for
easier writing and reading.
• Usually need a combination of two classes
• To use these classes your program needs a line like the following:
import java.io.*;
Output to a File
Text File Output
• To open a text file for output: connect a text file to a stream for writing
FileOutputStream s = new FileOutputStream("out.txt");
PrintWriter outputStream = new PrintWriter(s);
PrintWriter FileOutputStream
Memory Disk
smileyOutStream smiley.txt
2. print
3. format
4. flush: write buffered output to disk
5. close: close the PrintWriter stream (and file)
Example: File Output
public class OutputDemo{
public static void main(String[] args)
{
PrintWriter outputStream = null;
try
{ outputStream =new PrintWriter(new FileOutputStream("out.txt"));
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file out.txt. “ + e.getMessage());
System.exit(0);
}
System.out.println("Enter three lines of text:");
int count;
for (count = 1; count <= 3; count++)
{
outputStream.println(count + " abc ");
}
outputStream.close();
System.out.println("... written to out.txt.");
}
}
Overwriting/Appending a File
• Overwriting
– Opening an output file creates an empty file
– Opening an output file creates a new file if it does not already exist
– Opening an output file that already exists eliminates the old file and creates a new,
empty one and data in the original file is lost
outputStream = new PrintWriter(new FileOutputStream("out.txt"));
• Appending to a file
– To add/append to a file instead of replacing it, use a different constructor for
FileOutputStream:
outputStream = new PrintWriter(new FileOutputStream("out.txt", true));
2. A file opened for writing must be closed before it can be opened for
reading.
Input
Input File Streams
BufferedReader FileReader
Memory Disk
inStream input.txt
• For example:
while(st.hasMoreTokens()){
System.out.println(st.nextToken());
}
}
}
Testing for End of File in a Text File
• When readLine tries to read beyond the end of a text file it returns
the special value null
– so you can test for null to stop processing a text file
• read returns -1 when it tries to read beyond the end of a text file
– the int value of all ordinary characters is nonnegative
Example: Using Null to
Test for End-of-File in a Text File
int count = 0;
String line = inputStream.readLine();
20
Using BufferedReader to Read from Keyboard
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
try {
System.out.println(st.readLine());
System.out.println(st.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Alternative with Scanner
• Instead of BufferedReader with FileReader, then
StringTokenizer
Although JDBC was designed specifically to provide a Java interface to relational databases, you may
find that you need to write Java code to access non-relational databases as well.
JDBC Architecture
Java application calls the JDBC library. JDBC loads a driver which talks to the database
In general, to process any SQL statement with JDBC, you follow these steps:
① Establishing a connection.
② Create a statement.
③ Execute the query.
④ Process the ResultSet object.
⑤ Close the connection.
First of all, you should download the JDBC Driver for your DBMS. For this class, you can use
“ojdbc6.jar” provided on class web-site. The ojdbc6.jar is a JDBC driver for Oracle Database 11g.
The below web sites are official pages for downloading official version of JDBC drivers.
Oracle : http://www.oracle.com/technetwork/database/features/jdbc/index-091264.html
Mysql : http://www.mysql.com/downloads/connector/j/
Click Add External JARs -> Select the JDBC driver. -> Open
Click Add External JARs -> Select the JDBC driver. -> Open
You can confirm the jar file is added then click OK.
2. Establishing a Connection
In this step of the jdbc connection process, we load the driver class by calling Class.forName() with
the Driver class name as an argument. Once loaded, the Driver class creates an instance of itself.
The JDBC DriverManager class defines objects which can connect Java applications to a JDBC
driver. DriverManager is considered the backbone of JDBC architecture. DriverManager class
manages the JDBC drivers that are installed on the system. Its getConnection() method is used to
establish a connection to a database. It uses a username, password, and a jdbc url to establish a
connection to the database and returns a connection object. A jdbc Connection represents a
session/connection with a specific database. Within the context of a Connection, SQL, PL/SQL
statements are executed and results are returned. An application can have one or more connections
with a single database, or it can have many connections with different databases.
catch (SQLException e) {
// Could not connect to the database
System.out.println(e.getMessage());
}
Example for loading and connection
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public TestCon() {}
} catch (ClassNotFoundException e) {
// Could not find the database driver
System.out.println("ClassNotFoundException : "+e.getMessage());
return false;
} catch (SQLException e) {
// Could not connect to the database
System.out.println(e.getMessage());
return false;
}
return true;
}
}
If the output of the previous example is “Connection : true”, your environment setting and connection
is correct. If not, try to check the jdbc driver classpath, your username and your password
To execute a query, call an execute method from Statement such as the following:
execute: Returns true if the first object that the query returns is a ResultSet object. Use this
method if the query could return one or moreResultSet objects. Retrieve the ResultSet objects
returned from the query by repeatedly calling Statement.getResutSet.
executeQuery: Returns one ResultSet object.
executeUpdate: Returns an integer representing the number of rows affected by the SQL
statement. Use this method if you are using INSERT,DELETE, or UPDATE SQL statements.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
} catch (ClassNotFoundException e) {
// Could not find the database driver
System.out.println("ClassNotFoundException : "+e.getMessage());
return false;
} catch (SQLException e) {
// Could not connect to the database
System.out.println(e.getMessage());
return false;
}
return true;
}
public void printCounryByCapital(String capital) throws SQLException{
stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String name = rs.getString(1); // or rs.getString("NAME");
String code= rs.getString(2);
String cap = rs.getString(3);
String province = rs.getString(4);
int area = rs.getInt(5);
int population = rs.getInt(6);
}
public void updateCityPopulation(String cityName,String province,
String population)throws SQLException
{
Statement stmt = null;
stmt = connection.createStatement();
String sql = "UPDATE CITY SET population='"+ population
+"' WHERE NAME='"+cityName +"' AND
PROVINCE='"+ province +"'";
stmt.executeUpdate(sql);
stmt.close();
}