JAVA
JAVA
NOTE:
❖ Old class is also called as base class or super class or parent class
❖ New class is also called as derived class or sub class or child class
❖ Inheritance allows subclasses to inherit all the variables and methods from
their super class
1) Single inheritance:
it contains only one super class
2) Multiple inheritance:
it contains more than one super class
3) Hierarchical inheritance:
it contains one super class many sub classes
4) Multilevel inheritance:
derived from a derived class
5) Hybrid inheritance:
combination of both multilevel and hierarchical inheritance.
Page | 1
NOTE:
1) Java supports the concept of reusability.java classes can be used in many
ways .this is basically done by creating new classes, reusing the properties
of the existing class.
2) Java does not support multiple inheritance.
NOTE:
1) The keyword extends specifies the properties of superclassname are
extended to subclassname.
2) The subclass contains its own variables and methods as well as the
properties(variables,methods) that are inherited from superclass.
subclass constructor
1) subclass constructor is used to construct the variables of both superclass
and subclass.
2) subclass constructor uses super keyword to invoke the constructor
method of superclass
3) the super keyword is used under following conditions
a) super keyword is used within the subclass constructor
b) to call the superclass constructor super keyword must appear as the
first statement within the subclass constructor
c) the parameters in super keyword must match the order and type of
the instance variables declared in superclass.
Page | 2
write a program to demonstrate single inheritance
class A
{
public void methodA()
{
System.out.println("Base class method");
}
}
class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
}
class Test
{
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling sub class method
}
}
OUTPUT:
Base class method
Child class method
Page | 3
write a program to demonstrate Multi level inheritance.
class Firstclass
{
void Firstmethod()
{
System.out.println("Message from Firstclass");
}
}
Page | 4
class Test
{
public static void main(String args[])
{
Fourthclass fc = new Fourthclass();
//creating object for Fourthclass
fc.Firstmethod();
fc.Secondmethod();
fc.Thirdmethod();
fc.Fourthmethod();
OUTPUT:
METHOD OVERRIDING
when a method in subclass has the same name and type signature as a
method in its superclass then the method in its subclass is said to override the
method in superclass. This is called method overriding.
when a overridden method is called from a subclass ,it always refer to the
version of that method defined by the subclass.the version of the method
defined by superclass will be hidden.
Page | 5
write a program to demonstrate method overriding (OR) write a
program using SUPER keyword (OR) write a program using THIS
keyword
class Super
{
int x;
Super(int x)
{
this.x=x;
}
void display()
{
System.out.println("Super x=" +x);
}
}
class Sub extends Super
{
int y;
Sub(int x,int y)
{
super(x);
this.y=y;
}
void display()
{
System.out.println("Super x=" +x);
System.out.println("Sub y =" +y);
}
}
Page | 6
class OverrideTest
{
public static void main(String args[])
{
Sub s1=new Sub(100,200);
s1.display();
}
}
OUTPUT:
Super x=100
Sub y=200
2) Method overloading is performed within class. Method overriding occurs in two classes
that have IS-A (inheritance) relationship.
Page | 7
this keyword
2. this keyword can be used inside any method to refer the current object.
class Student
{
int id;
String name;
Student(int id,String name)
{
this.id = id;
this.name = name;
}
void display()
{
System.out.println(id+" "+name);
}
}
class Test
{
public static void main(String args[])
{
Student s1 = new Student(1,"Karan");
Student s2 = new Student(2,"Aryan");
s1.display();
s2.display();
}
}
Page | 8
OUTPUT:
1 Karan
2 Aryan
class B extends A
{
B(String str)
{
super(str);
System.out.println("Sub Class Constructor " + str);
}
}
class Mainclass
{
public static void main(String args[])
{
B obj = new B ("called");
}
}
OUTPUT:
Base Class Constructor called
Sub Class Constructor called
Page | 9
ABSTRACT CLASSES AND METHODS
Abstract class:
1. An abstract class is a class that is declared abstract.
2. Abstract classes may or may not include abstract methods.
3. Abstract classes cannot be instantiated, but they can be subclassed.
syntax:
Abstract Method:
1. The methods which have only declaration and no method body in the class
is called as abstract method.
2. The abstract method is declared by using the keyword abstract.
3. The abstract methods should be defined in subclass
Page | 10
write a program to demonstrate Abstract classes and Abstract methods
(or) program to demonstrate Abstract keyword.
Page | 11
final classes,methods and final variables
A)Finalvariable
{
final int hoursinday=24;
System.out.println("Hours in 5 days="+hoursinday * 5);
}
}
OUTPUT:
Hours in 5 days=120
Page | 12
B)Finalmethod
class A
{
final void math() //final method
{
System.out.println("this is final method");
}
}
class B extends A
{
void math()
{
System.out.println("illegal");
}
}
class Finalmethod
{
public static void main(String args[])
{
B obj=new B();
obj.math();
}
}
OUTPUT:
D:\mpcs>javac Finalmethod.java
Finalmethod.java:12: math() in B cannot override math() in A; overridden
method
is final
void math()
^
1 error
Page | 13
INTERFACES IN JAVA
Definition of interface
❖ interface is a kind of class which contain variables and methods
❖ difference is that interfaces define only abstract methods and final
keywords
❖ interfaces do not specify any code to implement these methods and
datafields contains only constants
❖ so it is the responsibility of class that implements an interface to define
the code by implementation of these methods
Properties of interface
❖ all the methods of interface are static and abstract by default
❖ we cannot create an object in interface
❖ an interface can extend another interface.
❖ an interface cannot implement another interface
❖ we can write a class inside an interface
❖ interface may have variables which are public,static,final by default
❖ all the abstract methods of interface should be implemented in its
implementation class
Page | 14
Difference between class and interface
class interface
we can create an object in class we cannot create object in interface
class is declared by keyword class interface is declared by keyword
interface
class has no multiple inheritance interface support multiple inheritance
class contains all types of variables interface contains only final variables
class interface contains only abstract
{ methods and final fields
variable declaration;
method declaration;
}
Extending Interfaces
Page | 15
Implementing Interfaces
Note: the above code shows that class can extend another class implementing
interfaces.
Page | 16
Understanding relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface
extends another interface but a class implements an interface.
interface Printable
{
void print();
}
{
public void print()
{
System.out.println("Hello");
}
Page | 17
class Test
{
public static void main(String args[])
{
InterfaceTest obj = new InterfaceTest();
obj.print();
obj.show();
}
}
OUTPUT:
Hello
Welcome
Page | 18
Write a program to demonstrate multiple inheritance.
interface Printable
{
void print();
}
interface Showable
{
void show();
}
class InterfaceTest implements Printable,Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
}
class Test
{
public static void main(String args[])
{
InterfaceTest obj = new InterfaceTest();
obj.print();
obj.show();
}
}
OUTPUT:
Hello
Welcome
Page | 19
STRING METHODS IN JAVA
(STRING HANDLING (OR) STRING MANIPULATION FUNCTIONS)
Creating a String
❖ By new keyword
Strings in Java are objects. Therefore you need to use the new operator to
create a new Java String object. Here is a Java String instantiation (creation)
The text inside the quotes is the text the String object will contain.
Page | 20
Methods in String class
The java string toUpperCase() method converts this string into uppercase letter and string
toLowerCase() method into lowercase letter.
String s="Sachin";
System.out.println(s.toUpperCase()); //SACHIN
System.out.println(s.toLowerCase()); //sachin
2. trim() method
The string trim() method eliminates white spaces before and after string.
System.out.println(s);// Sachin
System.out.println(s.trim());//Sachin
startsWith() method checks if this string starts with given prefix. It returns true if this string starts with given
prefix else returns false.
endsWith() method checks if this string ends with given suffix. It returns true if this string ends with given
suffix else returns false.
String s="Sachin";
System.out.println(s.startsWith("Sa")); //true
System.out.println(s.endsWith("n")); //true
Page | 21
4. charAt() method
String s="Sachin";
System.out.println(s.charAt(0));//S
System.out.println(s.charAt(3));//h
5. length() method
String s="Sachin";
System.out.println(s.length()); //6
6. replace() method
The string replace() method replaces all occurrence of first sequence of character with second
sequence of character.
System.out.println(s2);
7. equals() method
This method 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
String s1="java";
String s2="java";
String s3="JAVA";
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
Page | 22
8. equalsIgnoreCase() method
This method determines the equality of two Strings, ignoring their case (upper or lower case
doesn't matters with this function ).
System.out.println(str.equalsIgnoreCase("JAVA"));
9. substring() method:
substring() method returns a part of the string. substring() method has two forms,
The first argument represents the starting point of the subtring. If the substring() method is called
with only one argument, the subtring returned, will contain characters from specified starting point
to the end of original string.
But, if the call to substring() method has two arguments, the second argument specify the end point
of substring.
System.out.println(str.substring(4)); // 456789
System.out.println(str.substring(4,7)); // 456
String str1="Sachin";
str2=str1.concat(" Tendulkar");
System.out.println(str2); //Sachin Tendulkar
Page | 23
Methods in StringBuffer class
Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer
class in java is same as String class except it is mutable i.e. it can be changed.
StringBuffer and StringBuilder classes are used for creating mutable string
The append() method concatenates the given argument with this string.
The insert() method inserts the given string with this string at the given position.
Page | 24
3) StringBuffer replace() method
The replace() method replaces the given string from the specified beginIndex and
endIndex.
sb.replace(1,3,"Java");
The delete() method of StringBuffer class deletes the string from the specified
beginIndex to endIndex.
sb.delete(1,3);
sb.reverse();
Page | 25
Java StringBuilder class
Java StringBuilder class is used to create mutable (modifiable) string. The Java
StringBuilder class is same as StringBuffer class except that it is non-
synchronized
The StringBuilder append() method concatenates the given argument with this string.
The StringBuilder insert() method inserts the given string with this string at the given
position.
System.out.println(sb);//prints HJavaello
The StringBuilder replace() method replaces the given string from the specified
beginIndex and endIndex.
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
Page | 26
4) StringBuilder delete() method
The delete() method of StringBuilder class deletes the string from the specified
beginIndex to endIndex.
sb.delete(1,3);
System.out.println(sb);//prints Hlo
sb.reverse();
System.out.println(sb);//prints olleH
Page | 27
Java Array
An array is a very common type of data structure where in all elements
must be of the same data type.
Array in java is index based, first element of the array is stored at 0 index.
❖ It makes the code optimized, we can retrieve or sort the data easily.
❖ We can get any data located at any index position.
Array Declaration
Syntax :
datatype[ ] identifier;
or
datatype identifier[ ];
Both are valid syntax for array declaration. But the former is more readable.
Example :
int[ ] arr;
char[ ] arr;
short[ ] arr;
long[ ] arr;
Page | 28
Initialization of Array
Example :
//this creates an empty array named arr of integer type whose size is 10.
(or)
As mention ealier array index starts from 0. To access nth element of an array.
Syntax
arrayname[n-1];
The above code will print the 4th element of array arr on console.
Page | 29
Types of Array in java
Method-1
class Testarray
{
public static void main(String args[])
{
int a[]=new int[5];
a[0]=10;
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]);
}
}
Method-2
class Testarray1
{
public static void main(String args[])
{
int a[]={10,20,30,40,50};
//printing array
for(int i=0;i<a.length;i++) //length is the property of array
System.out.println(a[i]);
}
}
Page | 30
Multi-Dimensional Array in java
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
Page | 31
Example to print the 2 Dimensional array.
class Testarray3
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();
Output:
123
245
445
Page | 32
Addition of 2 matrices in java (3x3 matrices)
class Testarray5
int a[][]={{1,3,4},{3,4,5},{4,5,6}};
int b[][]={{1,3,4},{3,4,5},{5,6,7}};
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
System.out.println();//new line
Page | 33
MATRIX ADDITION BY PASSING VALUES AT RUNTIME
/*There are various ways to read input from the keyboard, the
java.util.Scanner class is one of them.
import java.util.Scanner;
public class Add1
{
public static void main(String args[])
{
int i, j;
int a[][] = new int[2][2];
int b[][] = new int[2][2];
int c[][] = new int[2][2];
Scanner scan = new Scanner(System.in);
System.out.println("Enter first Matrix Elements : ");
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
{
a[i][j] = scan.nextInt();
//Returns the next token as an int. If the next token is not an
integer, InputMismatchException is thrown.
}
}
Page | 34
System.out.println("Enter second Matrix Elements : ");
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
{
b[i][j] = scan.nextInt();
}
}
System.out.println("Adding both Matrix to form the Third Matrix...\n");
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
{
c[i][j] = a[i][j] + b[i][j];
}
}
System.out.println("The Two Matrix Added Successfully..!!\n");
System.out.println("The New Matrix will be :\n");
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
{
System.out.print(c[i][j]+ " ");
}
System.out.println();
}
}
}
Page | 35
MATRIX MULTIPLICATION
import java.util.Scanner;
public class Multiplication
{
public static void main(String args[])
{
Page | 36
System.out.print("Enter Number of Rows and Columns of Second Matrix : ");
r2 = in.nextInt();
c2 = in.nextInt();
if ( c1 != r1 )
{
System.out.print("Matrix of the entered order can't be Multiplied..!!");
}
else
{
int second[][] = new int[r2][c2];
int multiply[][] = new int[r1][c2];
System.out.print("Enter Second Matrix Elements :\n");
for(a=0; a<r2; a++)
{
for(b=0; b<c2; b++)
{
second[a][b] = in.nextInt();
}
}
System.out.print("Multiplying both Matrix...\n");
for(a=0; a<r1; a++)
{
for(b=0; b<c2; b++)
{
for(c=0; c<r2; c++)
{
sum = sum + first[a][c]*second[c][b];
}
multiply[a][b] = sum;
sum = 0;
}
}
Page | 37
System.out.print("Multiplication Successfully performed..!!\n");
System.out.print("Now the Matrix Multiplication Result is :\n");
}
}
Page | 38
TRANSPOSE OF A MATRIX
import java.util.Scanner;
int i, j;
System.out.print("Transposing Array...\n");
Page | 39
System.out.print("Transpose of the Matrix is :\n");
Page | 40
Wrapper class Example: Primitive to Wrapper
Page | 41
Page | 42