About Java
• It is one of the programming language or technology used for
developing web applications.
• Using this technology you can develop distributed application.
• A Java language developed at SUN Micro Systems in the year 1995
under the guidance of James Gosling and their team.
• In other word It is a programming language suitable for the
development of web applications.
• It is also used for developing desktop and mobile application.
2
Java Version History
• JDK Alpha and Beta (1995)
• JDK 1.0 (23rd Jan, 1996)
• JDK 1.1 (19th Feb, 1997)
• J2SE 1.2 (8th Dec, 1998)
• J2SE 1.3 (8th May, 2000)
• J2SE 1.4 (6th Feb, 2002)
• J2SE 5.0 (30th Sep, 2004)
• Java SE 6 (11th Dec, 2006)
• Java SE 7 (28th July, 2011)
• Java SE 8 (18th March, 2014)
3
First Java Program
7
class First {
public static void main(String[] args) {
System.out.println("Hello Java");
System.out.println("My First Java Program");
}
}
Difference between JDK, JVM and JRE
• JDK has all the tools used for develop applications.
• JVM is responsible for compiling and executing Java programs.
• JRE provides environment to run Java Applications.
9
Data Types in Java
10
Data Type Default Value Default size
boolean false 1 bit
char 'u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte
Assignment-1 (Data types and Operators)
1. Write a Java program to print 'Hello' on screen and then print your
name on a separate line.
2. Write a Java program to print the sum of two numbers.
3. Write a Java program to print the sum (addition), multiply, subtract,
divide and remainder of two numbers.
4. Write a Java program to swap two numbers.
12
If Statement
• Syntax:
if(condition)
{
//code to be executed
}
14
Example:
public class IfExample {
public static void main(String[] args) {
int age=20;
if(age>18){
System.out.print("Age is greater than 18");
}
}
}
If Else statement
• Syntax:
if(condition)
{
//code if condition is true
}
else
{
//code if condition is false
}
15
Example:
public class IfElseExample {
public static void main(String[] args) {
int number=13;
if(number%2==0){
System.out.println("even number");
}else{
System.out.println("odd number");
}
}
}
IF-else-if
• Syntax:
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are fals
e
}
16
public class IfElseIfExample {
public static void main(String[] args) {
int marks=65;
if(marks<50){
System.out.println("fail");
}
else if(marks>=50 && marks<60){
System.out.println("D grade");
}
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade");
}
else if(marks>=80 && marks<90){
System.out.println("A grade");
}else if(marks>=90 && marks<100){
System.out.println("A+ grade");
}else{
System.out.println("Invalid!");
}
} }
Switch Statement
• Syntax:
switch(expression){
case value1:
//code to be executed;
break;
case value2:
//code to be executed;
break;
......
default:
code to be executed if all cases are not matched;
}
17
Example:
public class SwitchExample {
public static void main(String[] args) {
int number=20;
switch(number)
{
case 10: System.out.println("10");break;
case 20: System.out.println("20");break;
case 30: System.out.println("30");break;
default:System.out.println("Not in 10, 2
0 or 30");
}
}
}
Assignment-2(Conditional statements)
1. Write a Java program to check a number is even or odd.
2. Write a Java program that prints weekday based the week number(1 to 7).
3. Print the greatest number of 3 numbers.
4. Write a Java program to check whether number is negative, zero, or positive.
5. Write a program will show if the person is eligible to vote.
6. Write a program to print month name based month number as an input using
switch...Case statement.
18
20
While loop
• Syntax:
while(condition){
//code to be executed
}
Example:
public class WhileExample {
public static void main(String[] args)
{
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
}
}
Do..while loop
• Syntax:
do{
//code to be executed
}while(condition);
21
• Example:
public class DoWhileExample {
public static void main(String[] args)
{
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
}
}
For-each Loop
• Syntax:
for(Type var:array)
{
//code to be executed
}
23
• Example:
public class ForEachExample {
public static void main(String[] args)
{
int arr[]={12,23,44,56,78};
for(int i:arr){
System.out.println(i);
}
}
}
Java Break Statement
• The Java break is used to break loop or
switch statement. It breaks the current
flow of the program at specified
condition. In case of inner loop, it
breaks only inner loop.
• Syntax:
jump-statement;
break;
24
Output: 1 2 3 4
Example:
public class BreakExample {
public static void main(String[] args) {
for(int i=1;i<=10;i++){
if(i==5){
break;
}
System.out.println(i);
}
}
}
Java Break Statement with Inner Loop
• It breaks inner loop only if you use break statement inside the inner
loop.
• Example:
25
• Output:
1 1
2 2
1 3
2 1
3 1
3 2
3 3
public class BreakExample2 {
public static void main(String[] args) {
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break;
}
System.out.println(i+" "+j);
}
}
}
}
Java Continue Statement
• The Java continue statement is used to
continue loop. It continues the current
flow of the program and skips the
remaining code at specified condition.
In case of inner loop, it continues only
inner loop.
• Syntax:
jump-statement;
continue;
26
Output: 1 2 3 4 6 7 8 9 10
Example:
public class ContinueExample {
public static void main(String[] args)
{
for(int i=1;i<=10;i++){
if(i==5){
continue;
}
System.out.println(i);
}
}
}
Java continue Statement with Inner Loop
• It continues inner loop only if you use continue statement inside
the inner loop.
• Example:
27
• Output:
1 1
2 2
1 3
2 1
2 3
3 1
3 2
3 3
public class ContinueExample2 {
public static void main(String[] args) {
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
if(i==2&&j==2){
continue;
}
System.out.println(i+" "+j);
}
}
}
}
Assignment-3(Loops)
1. Write a program in Java to display the first 10 natural numbers in ascending
order using while loop.
2. Write a program in Java to display the first 10 natural numbers in descending
order using do..while loop.
3. Write a program in Java to display the multiplication table of a number using
for loop.
4. Write a java program to split number into digits.
5. Write a java program to sum digits of a number.
6. Write a java program to reverse a number.
28
Arrays
• Array is a collection of similar type of elements that have contiguous memory
location.
• Java array is an object the contains elements of similar data type. It is a data
structure where we store similar elements.
• We can store only fixed set of elements in a java array.
• Array in java is index based, first element of the array is stored at 0 index.
29
Types of Arrays
• There are two types of array.
• Single Dimensional Array
• Multidimensional Array
30
Single Dimensional Array in java
• Syntax to Declare an Array in java
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
• Instantiation of an Array in java
arrayRefVar=new datatype[size];
31
• Example to Declare an Array in java
int[] a; (or)
int []a; (or)
int a[];
• Instantiation of an Array in java
a=new datatype[size];
• Declaration with instantiation
Int a[]=new int[];
Example of single dimensional java array
• Example of java array, where we are going to declare, instantiate, initialize and
traverse an array.
32
class Testarray{
public static void main(String args[]){
int a[]=new int[5]; //declaration and instantiation
a[0]=10; //initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Multidimensional array in java
• data is stored in row and column based index (also known as matrix
form).
• Syntax to Declare Multidimensional Array in java
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
• Example to instantiate Multidimensional Array in java
int[][] arr=new int[3][3]; //3 rows and 3 columns
33
Example of Multidimensional java array
• Example to declare, instantiate, initialize and print the 2Dimensional
array.
34
• Output:
1 2 3
2 4 5
4 4 5
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
Limitations in an array
• Array is fixed limit.
• We should know size of an array before declaration.
• Array cannot hold multiple datatype elements.
35
Object class in Java
• Object is the pre-defined main class of all the Java classes.
• We can create a variable with Object type, it can hold any data type
values.
• For Example:
Object a;
a=10; a=“Welcome”; a=15.5;
• We can also create Object type array.
36
Object type array
• Syntax to Declare an Object type Array
Object[] obj; (or)
Object []obj; (or)
Object obj[];
• Instantiation of an Array in java
obj=new Object[size];
37
• Example to Declare an Object type Array
Object[] a; (or)
Object []a; (or)
Object a[];
• Instantiation of an Array in java
a=new Object[size];
• Declaration with instantiation
Object a[]=new Object[];
Example of single dimensional
Object Type array
• Example of Object type java array, where we are going to declare, instantiate,
initialize and traverse an array.
38
class TestObjectArray{
public static void main(String args[]){
Object a[]=new Object[5]; //declaration and instantiation
a[0]=10; //initialization
a[1]=20.5;
a[2]=“Welcome”;
a[3]=‘A’;
a[4]=true;
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Assignment-4(Arrays)
1. Define a single dimensional array and store some values and read them using for loop.
2. Define a single dimensional array and store some values and read them using
for…each loop.
3. Define a single array with 5 elements and Search an element present or not in the
array.
4. Define a string array with 5 strings and search for a string in the array.
5. Define string array with 5 strings and print them using for..each loop.
6. Define two-dimensional array with 3 rows and 3 columns and read all the values using
classic for loop.
7. Do the 6th program using for each loop (enhanced loop)
8. Define an Object array with multiple data type values and print them using for..each
loop.
39
String class in java
• Generally, string is a sequence of characters. But in java, string is an
object that represents a sequence of characters.
• The java.lang.String class is used to create string object.
• Create a String object in 2 ways.
• String s=“Welcome”;
• String s=new String(“Welcome”);
• char ch[]={‘w',‘e',‘l',‘c',‘o',‘m',‘e'};
• String s=new String(ch); //converting char array to string
40
Java String Example
41
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by java string literal
char ch[]={'s','e','l','e','n','i','u','m'};
String s2=new String(ch);//converting char array to string
String s3=new String("training");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
• charAt(): Returns a char value at the given index number. The index
number starts from 0
Output : o
43
public class CharAtExample{
public static void main(String args[]){
String name="Welcome";
char ch=name.charAt(4);
//returns the char value at the 4th index
System.out.println(ch);
}
}
• Concat() : Combines specified string at the end of this string. It
returns combined string
• Output:
Welcome
Welcome to java training
44
public class ConcatExample{
public static void main(String args[]){
String s1="Welcome";
System.out.println(s1);
s1=s1.concat(" to java training");
System.out.println(s1);
}}
• contains() : searches the sequence of characters in this string. It
returns true if sequence of char values are found in this string
otherwise returns false.
Output: true true false
45
class ContainsExample{
public static void main(String args[]){
String name="what do you know about me";
System.out.println(name.contains("do you know"));
System.out.println(name.contains("about"));
System.out.println(name.contains("hello"));
}}
• equals() : compares the two given strings based on the content of the
string. If any character is not matched, it returns false. If all characters
are matched, it returns true.
46
public class EqualsExample{
public static void main(String args[]){
String s1="welcome";
String s2="welcome";
String s3="WELCOME";
String s4="training";
System.out.println(s1.equals(s2));//true because content and case is same
System.out.println(s1.equals(s3));//false because case is not same
System.out.println(s1.equals(s4));//false because content is not same
}
}
• equalsIgnoreCase(): compares the two given strings on the basis of content of
the string irrespective of case of the string. It is like equals() method but doesn't
check case. If any character is not matched, it returns false otherwise it returns
true.
47
public class EqualsExample{
public static void main(String args[]){
String s1="welcome";
String s2="welcome";
String s3="WELCOME";
String s4="training";
System.out.println(s1.equalsIgnoreCase(s2));//true because content is same
System.out.println(s1.equalsIgnoreCase(s3));//true because case is ignored
System.out.println(s1.equalsIgnoreCase(s4));//false because content is not same
}
}
• length(): length of the string. It returns count of total number of
characters. The length of java string is same as the unicode code units
of the string.
48
public class LengthExample{
public static void main(String args[]){
String s1="welcome";
String s2="python";
System.out.println("string length is: "+s1.length());//7
System.out.println("string length is: "+s2.length());//6
}
}
• replace(): Returns a string replacing all the old char or CharSequence
to new char or CharSequence.
49
public class ReplaceExample1{
public static void main(String args[]){
String s1="software testing is a very course";
String replaceString=s1.replace('a','e');//replaces all occu
rrences of 'a' to 'e'
System.out.println(replaceString);
}}
• split(): splits this string against given regular expression and returns a
char array.
50
public class SplitExample{
public static void main(String args[]){
String s1="java string split method ";
String[] words=s1.split("s");//splits the string based on whitespace
//using java foreach loop to print elements of string array
for(String w:words){
System.out.println(w);
}
}
}
• substring() : returns a part of the string.
• We pass begin index and end index number position in the java substring method
where start index is inclusive and end index is exclusive. In other words, start
index starts from 0 whereas end index starts from 1.
• Parameters
• startIndex : starting index is inclusive
• endIndex : ending index is exclusive
51
public class SubstringExample{
public static void main(String args[]){
String s1="javatpoint";
System.out.println(s1.substring(2,4));//returns va
System.out.println(s1.substring(2));//returns vatpoint
}
}
• toLowerCase(): returns the string in lowercase letter. In other words,
it converts all characters of the string into lower case letter.
52
public class StringLowerExample
{
public static void main(String args[])
{
String s1="Welcome to TRAINING";
String s1lower=s1.toLowerCase();
System.out.println(s1lower);
}
}
• toUpperCase(): returns the string in uppercase letter. In other words,
it converts all characters of the string into upper case letter.
53
public class StringUpperExample
{
public static void main(String args[])
{
String s1="hello string";
String s1upper=s1.toUpperCase();
System.out.println(s1upper);
}
}
• valueOf() : converts different types of values into string. By the help
of string valueOf() method, you can convert int to string, long to
string, boolean to string, character to string, float to string, double to
string, object to string and char array to string.
54
public class StringValueOfExample{
public static void main(String args[])
{
int value=30;
String s1=String.valueOf(value);
System.out.println(s1+10);//concatenating string with 10
}
}
Java - Date and Time
• Java provides the Date class available in java.util package.
• Date( )
• This constructor initializes the object with the current date and time.
55
Getting Current Date and Time
56
import java.util.Date;
public class DateDemo {
public static void main(String args[]) {
// Instantiate a Date object
Date date = new Date();
// display time and date using toString()
System.out.println(date.toString());
}
}
Assignment-5(String methods)
1. Write a Java program to get the character at the given index within the String.
2. Write a Java program to concatenate two strings.
3. Write a Java program to test if a given string contains the specified sequence
of char values.
4. Write a Java program to compare a given strings.
5. Write a Java program to compare a given string to another string, ignoring case
considerations.
6. Write a java program to get the length of a given string.
7. Java program to remove vowels from a string.
57
8. Define a string variable called ‘s’
s=" Welcome to selenium java training"
Do the following:
• Count how many words are present in a string.
• Display all the words in upper case
• Display all the words in lower case
• Verify presence of "selenium"
• Display all the words in reverse order
58
Classes and Objects
• A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created.
• It is a logical entity. It can't be physical.
• A class in Java can contain:
• fields
• methods
• constructors
• Syntax to declare a class:
class <class_name>{
field;
method;
}
59
Objects
• Object is the physical as well as logical entity whereas class is the
logical entity only.
• Object is an instance of a class. Class is a template or blueprint from
which objects are created. So object is the instance(result) of a class.
• Object Definitions:
• Object is a real world entity.
• Object is a run time entity.
• Object is an entity which has state and behavior.
• Object is an instance of a class.
60
Object and Class Example: main within class
File: Student.java
62
class Student{
int id=101; //field or data member or instance variable
String name=“Anil”;
public static void main(String args[]){
Student s1=new Student();//creating an object of Student
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}
Object and Class Example: main outside class
• In real time development, we create classes and use it from another
class. It is a better approach than previous one.
• We can have multiple classes in different java files or single java file.
• If you define multiple classes in a single java source file, it is a good
idea to save the file name with the class name which has main()
method.
63
File: TestStudent1.java
64
class Student{
int id=101;;
String name=“Anil;
}
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
3 Ways to initialize object
• There are 3 ways to initialize object in java.
• By reference variable
• By method
• By constructor
65
Object and Class Example: Initialization
through reference
• File: TestStudent2.java
66
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name=“Anil";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
}
Object and Class Example: Initialization
through method
67
File: TestStudent4.javaclass 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 and Class Example: Initialization
through constructor
68
File: TestStudent5.javaclass Student{
int rollno;
String name;
void Student(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(111,”Kiran”);
Student s2=new Student(222,”arya”);
s1.displayInformation();
s2.displayInformation();
}
}
Call by Value
70
public class ByVal {
int x;
public void addition(int a)
{
x = a + 5;
}
}
public class CallByVal {
public static void main(String args[])
{
ByVal b=new ByVal();
Int x=10;
b.addition(x);
System.out.println(x); // 10
}
}
Call by Reference
71
public class ByRef {
int x;
public void addition(ByRef a) {
x = a.x + 5;
}
}
public class CallByRef {
public static void main(String args[])
{
ByRef b=new ByRef();
Int b.x=10;
b.addition(b);
System.out.println(b.x); //15
}
}
Assignment-6 (Class and Objects)
1. Create an Employee class contains the following variables and methods.
Class Name: Employee:
EmpID
Ename
Esal
Job
getEmpData() Should take the Employee details externally and assign them to
class variables
displayEmpData() Should display the employee details
Now, create objects from Employee class emp1, emp2 etc.
Then call Employee class methods by passing values.
72
2. Create a Student class contains the following variables and methods.
Class Name: Student
SID
Sname
Sub1
Sub2
Sub3
getStuData() Should take the Student details SID and Sname externally and assign them to class
variables
getStuMarks() Should take the Student marks externally and assign them to Sub1, Sub2, Sub3
CalTotalMarks() Should calculate total marks and print the student details with total marks
Now, create objects from Student class stu1, stu2 etc.
Then call Student class methods by passing values.
73
Java Constructor
• Constructor in java is a special type of method that is used to initialize
the object.
• Java constructor is invoked at the time of object creation.
• Rules for creating java constructor:
• Constructor name must be same as its class name
• Constructor must have no explicit return type
• Types of java constructors
• Default constructor (no-arg constructor)
• Parameterized constructor
74
Default constructor
• A constructor that have no parameter is known as default constructor.
• Example of default constructor.
75
class Bike1
{
Bike1()
{
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike1 b=new Bike1();
}
}
Parameterized constructor
• A constructor that have parameters is known as parameterized
constructor.
• Parameterized constructor is used to provide different values to the
distinct objects.
76
Example of parameterized constructor
77
class Student4{
int id;
String name;
Student4(int i, String n){
id = i;
name = n;
}
void display() {
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
Assignment-7 (Constructors)
1. Write a program to demonstrate constructor.
Create a class ‘Calculation’ with 3 integer variables and create constructor for
assign the values into variables. Then create another method to calculate sum of 3
numbers.
2. Write a program to demonstrate constructor overloading.
Create a class with name ‘Sum’ with 5 i variables and create constructors as following.
Variables:
integers a b
doubles c d
Define constructor for take 2 integers as input and assign to a, b
Define constructor for take 2 double as input and assign to c, d
Define a method for adding two numbers.
78
Method Overloading
• If a class has multiple methods having same name but different in
parameters, it is known as Method Overloading.
• Different ways to overload the method
• By changing number of arguments
• By changing the data type
79
Method Overloading: changing no. of
arguments
80
class Adder{
int add(int a,int b)
{
return a+b;
}
int add(int a,int b,int c)
{
return a+b+c;
}
}
class TestOverloading1
{
public static void main(String[] args)
{
Adder ad=new Adder();
System.out.println(ad.add(11,11));
System.out.println(ad.add(11,11,11));
}
}
Method Overloading: changing data type of
arguments
81
class Adder{
int add(int a,int b)
{
return a+b;
}
int add(double a,double b)
{
return a+b;
}
}
class TestOverloading2
{
public static void main(String[] args)
{
Adder ad=new Adder();
System.out.println(ad.add(11,11));
System.out.println(ad.add(11.5,12.5));
}
}
Can we overload java main() method?
• Yes, by method overloading. You can have any number of main methods in a class
by method overloading. But JVM calls main() method which receives string array
as arguments only.
82
class TestOverloading4
{
public static void main(String[] args)
{ System.out.println("main with String[]");
}
public static void main(String args)
{
System.out.println("main with String");
}
public static void main()
{
System.out.println("main without args");
} }
Constructor Overloading in Java
83
class Student5
{
int id;
String name;
int age;
Student5(int i,String n){
id = i;
name = n;
}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display()
{
System.out.println(id+" "+name+" "+age);
}
public static void main(String args[]){
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
Assignment-8(Overloading)
1. Create a class Calculation with the following methods. (Method
Overloading concept)
Class Name: Calculation
sum(int x, int y) Should accept two integer parameters and returns sum of two
numbers.
sum(int x, int y, int z) Should accept three integer parameters and returns sum of
three numbers.
sum(double x, double y) Should accept two double type parameters and returns
sum of two numbers.
sum(double x, double y, double z) Should accept three double type parameters and
returns sum of three numbers.
Now, create object for Calculations class ‘cal’ then call different methods by passing
different inputs.
84
Static variables and static methods
• Static methods can access static methods and static variables directly with
class name.
• Static methods can access Non static methods and non static variables
using object.
• Non static methods can access static and non static variable and methods
directly with class name.
• Static keyword should be used for defining static variables and methods.
• Static variable values are common across the all the objects for the class.
85
Assignment-9 (static variables and methods)
1. Write a program to demonstrate static methods and static variables
as follows.
• Define a Class A contains 2 static integer variables and one static
method which displays sum of two numbers.
• Try to access variables and method from another static method i.e
main method.
86
Java Inheritance
• Inheritance in java is a mechanism in which one object acquires all the
properties and behaviors of parent object.
• The idea behind inheritance in java is that you can create new classes that
are built upon existing classes.
• When you inherit from an existing class, you can reuse methods and fields
of parent class, and you can add new methods and fields also.
• Syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
87
Types of inheritance
• Single inheritance
• Multilevel inheritance
• Hierarchical inheritance
• Multiple inheritance
• Hybrid inheritance
88
Method Overriding in Java
• If subclass (child class) has the same method as declared in the parent
class, it is known as method overriding in java.
• Rules for Java Method Overriding
• method must have same name as in the parent class
• method must have same parameter as in the parent class.
90
Example of method overriding
Output: Bike is running safely
91
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike2 extends Vehicle{
void run(){System.out.println("Bike is running safely");
}
public static void main(String args[]){
Bike2 obj = new Bike2();
obj.run();
}
93
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
class Bank{
int getRateOfInterest(){return 0;}
}
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
class ICICI extends Bank{
int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateO
fInterest());
System.out.println("ICICI Rate of Interest: "+i.getRat
eOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRate
OfInterest());
}
}
super keyword in java
• The super keyword in java is a reference variable which is used to
refer immediate parent class object.
• Usage of java super Keyword
1) super can be used to refer immediate parent class instance
variable.
2) super can be used to invoke immediate parent class method.
3) super() can be used to invoke immediate parent class
constructor.
94
super is used to refer immediate parent
class instance variable.
95
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog
class
System.out.println(super.color);//prints color
of Animal class
}
} class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
super can be used to invoke parent class
method
96
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread..."
);}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}
super is used to invoke parent class
constructor.
97
class Animal{
Animal(){System.out.println("animal is created"
);}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
} class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}
}
Final Keyword In Java
• The final keyword in java is used to restrict the user. The java final
keyword can be used for variables, methods and classes.
• variable
• method
• class
98
Java final variable
• If you make any variable as final, you cannot change the value of final variable(It
will be constant).
• Example of final variable
• Output:Compile Time Error
99
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
Java final method
• If you make any method as final, you cannot override it.
• Example of final method
100
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
Output:Compile Time Error
Java final class
• If you make any class as final, you cannot extend it.
• Example of final class
• Output:Compile Time Error
101
final class Bike{}
class Honda1 extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda1 honda= new Honda();
honda.run();
}
}
Assignment-10 (Inheritance)
1. Write a program to demonstrate Single Inheritance.
• Class A int a, int b m1() m2()
• Class B int c, int d m3() m4()
• Class Test try to access all the variables and methods from parent
classes.
• Note: Class B should extends from Class A, Class Test should extends
from Class B.
102
2. Write a program to demonstrate Multi level Inheritance with
method over riding concept.
• Class A Define two methods m1() and m2().
• Class B Change body of m1() & m2() methods (override)
• Class Test try to access all the variables and methods from parent
classes.
• Note: Class B should extends from Class A, Class Test should extends
from Class B.
103
3. Write a program to demonstrate Hierarchy Inheritance.
• Class A int a, int b m1() m2()
• Class B int c, int d m3() m4()
• Class Test try to access all the variables and methods from parent
classes.
• Note: Class Test should extends from Class A, Class B should extends
from Class A.
104
Java Interfaces
• An interface in java is a blueprint of a class. It has static constants and abstract
methods.
• By interface, we can support the functionality of multiple inheritance.
• We can define interface with interface keyword.
• A class extends another class, an interface extends another interface but a class
implements an interface.
• We can create Object reference for Interface but we cannot instantiate interface.
105
Java Interface Example
106
interface printable{
void print();
}
class A6 implements printable
{
public void print(){System.out.println("Hello");
}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}
Java Interface Example: Bank
TestInterface2.java
107
interface Bank{
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest(){return 9.15f;}
}
class PNB implements Bank{
public float rateOfInterest(){return 9.7f;}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}}
109
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable
{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
A7 obj = new A7();
obj.print();
obj.show();
}
}
Assignment-11 (Interfaces)
1. Write a program to demonstrate interface.
• Interface A int a, int b m1() m2()
• Class B Implements methods from A and calculate sum of a and b
2. Write a program for multiple inheritance by using interface.
• Interface A int a, int b m1() m2()
• Interface B int a, int b m3() m4()
• Class A Implements methods from A and B interfaces.
110
Java Packages
• A java package is a group of similar types of classes, interfaces and
sub-packages.
• Package in java can be categorized in two form, built-in package and
user-defined package.
• There are many built-in packages such as java, lang, awt, javax, swing,
net, io, util, sql etc.
111
Access package from another package
• There are three ways to access the package from outside the package.
• import package.*;
• import package.classname;
• fully qualified name.
112
Access Modifiers in java
• The access modifiers in java specifies accessibility (scope) of a data
member, method, constructor or class.
• There are 4 types of java access modifiers:
• private
• default
• protected
• public
113
private access modifier
• The private access modifier is accessible only within class.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
114
default access modifier
• If you don't use any modifier, it is treated as default by default. The
default modifier is accessible only within package.
115
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
* In the above example, the scope of class A and its method msg() is default so it cannot be accessed from
outside the package.
protected access modifier
• The protected access modifier is accessible within package and
outside the package but through inheritance only.
• The protected access modifier can be applied on the data member,
method and constructor. It can't be applied on the class.
116
117
//save by A.java
package pack;
public class A
{
protected void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B extends A
{
public static void main(String args[]
)
{
B obj = new B();
obj.msg();
}
}
public access modifier
• The public access modifier is accessible everywhere. It has the widest scope
among all other modifiers.
118
//save by A.java
package pack;
public class A{
public void msg()
{System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
All java access modifiers
119
Access Modifier within class within package outside package
by subclass only
outside package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Java Exceptions
• Exception is an abnormal condition.
• In java, exception is an event that disrupts the normal flow of the
program.
• There are two types of exceptions.
1. Checked Exceptions
2. Un-checked Exceptions
120
Un Checked Exceptions
• Exceptions that are NOT checked by compiler are called Un-Checked
Exceptions.
• Un checked Exceptions successfully compiled by Java compiler.
• At run time it throws exception.
• Examples:
• ArithmeticException
• NullPointerException
• NumberFormatException
• ArrayIndexOutOfBoundsException
121
Common Un-Checked exceptions
• ArithmeticException
• If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0; //ArithmeticException
• NullPointerException
• If we have null value in any variable, performing any operation by the
variable occurs an NullPointerException.
String s=null;
System.out.println(s.length()); //NullPointerException
122
• NumberFormatException
• The wrong formatting of any value, may occur
NumberFormatException. Suppose I have a string variable that have
characters, converting this variable into digit will occur
NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
123
• ArrayIndexOutOfBoundsException
• If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
124
Checked Exceptions
• Exceptions that are checked by compiler are called Checked
Exceptions.
• If a program contains checked-Exception code is not compiled.
• Examples:
• InterruptedException
• IOException
• FileNotFoundException etc.
125
Common Checked exceptions
• InterruptedException
Thread.sleep(3000); //Throws InterruptedException
• FileNotFoundException & IOException
FileReader fr = new FileReader("C:Test.txt"); //FileNotException
BufferedReader bfr = new BufferedReader(fr);
System.out.println(bfr.readLine()); //IOException
126
Java try..catch block
• Java try block is used to enclose the code that might throw an exception.
• It must be applied at statement level within the method.
• Java try block must be followed by either catch or finally block.
• Used for both Un-checked and Checked Exceptions.
• Syntax of java try-catch
try{
//code that may throw exception
}catch(Exception_class_Name ref){}
• Syntax of try-finally block
try{
//code that may throw exception
}finally{}
128
Java catch block
• Java catch block is used to handle the Exception. It must be used after
the try block only.
• You can use multiple catch block with a single try.
129
Problem without exception handling
• Output: Exception in thread main java.lang.ArithmeticException:/ by zero
130
public class Testtrycatch1{
public static void main(String args[])
{
int data=50/0; //may throw exception
System.out.println("rest of the code...");
}
}
Solution by exception handling
Output: Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
131
public class Testtrycatch2{
public static void main(String args[]){
try{
int data=50/0;
}catch(ArithmeticException e){System.out.println(e);}
System.out.println("rest of the code...");
}
}
Java Multi catch block
• If you have to perform different tasks at the occurrence of different Exceptions,
use java multi catch block.
133
Output:task1 completed
rest of the code...
public class TestMultipleCatchBlock{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e){System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
catch(Exception e){System.out.println("common task completed");}
System.out.println("rest of the code...");
}
}
Java finally block
• Java finally block is a block that is used to execute important
code such as closing connection, stream etc.
• Java finally block is always executed whether exception is handled or
not.
• Java finally block follows try or catch block.
134
Usage of Java finally
• Cases
1. Exception doesn't occur.
2. Exception occurs and not handled.
3. Exception occurs and handled.
136
Case 1: Java finally example
where exception doesn't occur
137
Output:5
finally block is always executed
rest of the code...
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always exec
uted");}
System.out.println("rest of the code...");
}
}
Case 2: Java finally example
where exception occurs and not handled.
138
Output:finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero
class TestFinallyBlock1{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Case 3: Java finally example
where exception occurs and handled.
139
Output:Exception in thread main
java.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code...
public class TestFinallyBlock2{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
throws
• Used for only Checked Exceptions.
• It should be applied at Method level.
140
throws – Example1
141
public class Test {
public static void main(String[] args) throws
InterruptedException
{
System.out.println("Test started");
System.out.println("Test is in progress");
Thread.sleep(3000); // InterruptedException
System.out.println("Test is completed");
System.out.println("Test is exited");
}
}
throws – Example2
142
public class Test {
public static void main(String[] args) throws IOException
{
FileReader fr = new FileReader("C:Test.txt");
//FileNotException
BufferedReader bfr = new BufferedReader(fr);
System.out.println(bfr.readLine()); //IOException
}
}
Assignment-12(Exception Handling)
1. Write a java program for the following and handle exceptions by using
try..catch and finally blocks.
• Any number divide by zero.
• int a[]=null;
• a.length
• String s="abc";
• int i=Integer.parseInt(s);
2. Write a java program to handle IO Exception by using throws.
144
ArrayList
• ArrayList is pre defined class in Java used for dynamic array for storing
elements.
• ArrayList can contains duplicate elements.
• We can add, insert and remove elements from ArrayList.
• Syntax:
• ArrayList al=new ArrayList();//allows all data types
• ArrayList<String> al=new ArrayList<String>();//Allows only String data types
145
Java ArrayList Example
146
import java.util.*;
class TestCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Iterating Array List through for-each loop
147
import java.util.*;
class TestCollection2{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
for(String obj:al)
System.out.println(obj);
}
}
ArrayList Methods
148
import java.util.*;
public class ArrayListDemo {
public static void main(String args[]) {
// create an array list
ArrayList al = new ArrayList();
System.out.println("Initial size of al: " +
al.size());
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: "
+ al.size());
// display the array list
System.out.println("Contents of al: " + al);
// Remove elements from the array list
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: "
+ al.size());
System.out.println("Contents of al: " + al);
}
}
Assignment-13(ArrayList)
1. Define an array list and store some values and read them using
for…each loop.
2. Define an array list with 5 elements and Search an element present
or not in the arraylist.
3. Define a string array list with 5 integers and print them in reverse
order.
149
HashMap
• The important points about Java HashMap class are:
• A HashMap contains values based on the key.
• It contains only unique elements.
• It may have one null key and multiple null values.
• It maintains no order.
150
Java HashMap Example
151
Output:102 Rahul
100 Amit
101 Vijay
import java.util.*;
class TestCollection13{
public static void main(String args[]){
HashMap<Integer,String> hm=new HashMap<Integer,String>();
hm.put(100,"Amit");
hm.put(101,"Vijay");
hm.put(102,"Rahul");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Java HashMap Example: remove()
152
Output:
Values before remove: {102=Operating System, 103=Data Communication and Networking, 101=Let us C}
Values after remove: {103=Data Communication and Networking, 101=Let us C}
import java.util.*;
public class HashMapExample {
public static void main(String args[]) {
// create and populate hash map
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put(101,"Let us C");
map.put(102, "Operating System");
map.put(103, "Data Communication and Networking");
System.out.println("Values before remove: "+ map);
// Remove value for key 102
map.remove(102);
System.out.println("Values after remove: "+ map);
}
}
Assignment-14 (HashMap)
• Create a HashMap and do the following.
• Add the following keys(EMPID’s) and their values(ENAME’s) to the HashMap
• EMPID ENAME
• 101 DAVID
• 102 SCOTT
• 103 JOHN
• Read and print all the keys and their values using for each loop.
• Remove a pair from HashMap
• 101 DAVID
• Print the keysets in HashMap.
153
JDBC – Java Database Connectivity
• Java JDBC is a java API to connect and execute query with the
database.
• JDBC API uses jdbc drivers to connect with the database.
154
5 Steps to connect to the database in java
1. Register the driver class
2. Creating connection
3. Creating statement
4. Executing queries
5. Closing connection
155
• Example to register the OracleDriver class
Class.forName("oracle.jdbc.driver.OracleDriver");
• Create the connection object
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","password");
• Create the Statement object
Statement stmt=con.createStatement();
• Execute the query
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
• Close the connection object
con.close();
156
Select data from database table
157
import java.sql.*;
public class DBConnection {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
// 1 - Register the OracleDriver class
Class.forName("oracle.jdbc.driver.OracleDriver");
// 2-Create the connection object
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@INVRLX61ILM40:1521:ORA11G",
“scott",“tiger");
// 3 - Create the Statement object
Statement stmt = con.createStatement();
// 4-Execute the query
ResultSet rs = stmt.executeQuery("select * from employee order by EMPLOYEE_ID");
while (rs.next()) {
System.out.print(rs.getString("first_name"));
System.out.println(" " + rs.getInt("salary"));
}
// 5- close connection objects
rs.close();
con.close(); }
}
Insert data into database table
159
import java.sql.*;
public class DBConnection {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
// 1 - Register the OracleDriver class
Class.forName("oracle.jdbc.driver.OracleDriver");
// 2-Create the connection object
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@INVRLX61ILM40:1521:ORA11G",
“scott",“tiger");
// 3 - Create the Statement object
Statement stmt = con.createStatement();
// 4-Execute the query
stmt.executeQuery("insert into employee(EMPLOYEE_ID,LAST_NAME,FIRST_NAME) values(1234,'ABC','XYX')");
// 5- close connection objects
rs.close();
con.close();
}
}
Update data in database table
160
import java.sql.*;
public class DBConnection {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
// 1 - Register the OracleDriver class
Class.forName("oracle.jdbc.driver.OracleDriver");
// 2-Create the connection object
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@INVRLX61ILM40:1521:ORA11G",
“scott",“tiger");
// 3 - Create the Statement object
Statement stmt = con.createStatement();
// 4-Execute the query
stmt.executeQuery("update employee set FIRST_NAME='abc' WHERE EMPLOYEE_ID=7778");
// 5- close connection objects
rs.close();
con.close();
}
}
Delete data from database table
161
import java.sql.*;
public class DBConnection {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
// 1 - Register the OracleDriver class
Class.forName("oracle.jdbc.driver.OracleDriver");
// 2-Create the connection object
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@INVRLX61ILM40:1521:ORA11G",
“scott",“tiger");
// 3 - Create the Statement object
Statement stmt = con.createStatement();
// 4-Execute the query
stmt.executeQuery("delete from employee where EMPLOYEE_ID=1234");
// 5- close connection objects
rs.close();
con.close();
}
}
Assignment-15(JDBC)
• Connect to database and check how many number of records present
in the Employee table.
• Connect to database and display all the employees details where
employees belongs to deptno 10.
• Connect oracle database and Display employee details whose is
earning highest salary.
162