An Introduction To Core Java Unit-1
An Introduction To Core Java Unit-1
Introduction
Java is a pure object oriented programming language.
It was developed by ‘James Gosling’ at Sun Microsystems.
First version of Java was released in 1995.
Java provides the functionality of ‘write once, run anywhere’ (WORA).
The latest released version of Java standard edition is 1.8.
Functionalities of Java
Java provides important functionalities like:
Java provides a huge library.
Auto memory cleanup process i.e. automatic garbage collection.
Platform independent means it is portable on every operating system.
Code reusability which allows us to use the previous methods in next class.
Features of Java
Simple: Java is simple to understand because it eliminates lot of confusing properties like
pointer, operator overloading, header files, goto statement etc.
Portable: When we compile Java code it generates byte-code that can be run on any operating
system.
Secure: Java doesn’t support pointer, so without authorization we cannot access memory
location. It also uses some cryptography for data security. JVM provides a virtual machine for
running the Java programs.
Platform independent: It is one of the most important features of Java as it follows ‘write once
and run anywhere’ function. After compilation Java code gets converted into byte-code and this
code can run on any operating system.
Robust: Java uses strong memory management which is handled by automatic garbage
collection. Exception handling provides the code checking mechanism.
High Performance: JIT compiler which interprets the Java code into byte-code will increase the
performance of java.
Distributed: Java is basically designed for internet to have the distributed nature.
Dynamic: Java can carry lots of information on run time as it provides a link on different classes
and objects dynamically.
Interpreted: Java compiler accepts the source code, converts it into byte-code and in second
stage it converts into machine code with the help of interpreter.
JDCB RowSet: For sending the tabular format between remote components to distributed
application JDBC RowSet is used as it provides direct access to the database.
Java does not support pointer. C++ supports the pointer concept.
Java doesn’t support structure and union. Structure and union are supported in C++.
Java is pure object oriented language. C++ is only an extension of object oriented language.
Java does not support multiple inheritance. Multiple inheritance is supported by C++.
Java does not support global variable. C++ supports global variable.
Java uses instanceof operator for identifying an object. instanceof operator is not available in C++.
Write once, run anywhere (WORA). Write once, compile anywhere (WOCA)
Java supports documentation comment. C++ does not support documentation comment.
Java doesn’t have any preprocessor. Preprocessor concept is available in C++, so it supports the
#define or macros.
Java uses right shift operator (>>>) for inserting zeros at C++ uses right shift operator (>>).
the top end.
Java supports the multithreading concept. C++ does not support any built in function for multithreading.
An Overview of Java
JVM (Java Virtual Machine)
JVM is a virtual machine and it stays on top of the operating system. It provides the runtime
environment where Java byte-code can be run. JVM is different for every operating system so it
is platform dependent.
What does JVM do?
Locates a file and loads the code.
Verifies the code.
Converts byte-code into machine code (executed code).
Allocates the memory into RAM.
Executes the code.
JIT Compiler
JIT stands for just in time compiler. It converts the byte code of one operating system to current
operating system executable code. This instruction is given by JVM of the current operating
system. This byte-code converts into native platform code.
Java Runtime Environment (JRE)
JRE provides the runtime environment. It contains the JVM and many other library files. It is the
part of Java development kit (JDK) and it cannot be downloaded separately. It physically exits.
Java Development Kit (JDK)
JDK is the software development environment. It is used for developing java program and
applet. It includes the JRE (Java runtime environment), javac (Java compiler), jar, javap, etc.
Procedure to develop Java program
Save: FirstProgram.java
Compile: C:\> javac FirstProgram.java
Run: C:\> java FirstProgram
Explanation:
class is a keyword in Java and everything is written under the class.
public is an access modifier which provides the accessibility of main method to all.
static is a keyword and main methods are always declared as static. There is no need to create
an object to invoke the static method.
void shows the main methods that do not return any kind of value.
String args[] is used for command line argument.
System.out.println() is used for printing the statement.
Variables in Java
A variable is a piece of memory location that contains a data value. Variables are used to store
information which is needed to develop Java programs.
Types of variables
There are three types of variables available in Java.
1. Instance variable
2. Static variable
3. Local variable
Instance variable
Instance variable is also known as non-static variable. It has the unique value for each object
(instance).
Instance variable is created when an object is created with new keyword and destroyed when
object is destroyed.
Static variable
Static variable is the class level variable which is declared with static keyword.
Static variable tells the compiler that there is only one copy of this variable in existence.
Static variable is created when program starts and destroyed when the program stop.
Local variable
Local variable is declared inside the method, constructor and block.
There is no special keyword for declaring local variable.
Local variable can be accessed only inside the method, constructor and block.
Example: Simple program to understand the variable types
File Name: VariableType.java
class VariableType
{
int a=10; //instance variable
static int b=20; //static variable
public int m1()
{
int c = 30; //local variable
System.out.println("c = "+c);
return 0;
}
public static void main(String args[])
{
VariableType v = new VariableType ();
System.out.println("a = "+v.a+" b = "+b);
v.m1(); //invoke the m1 method
}
}
Output:
a = 1 b = 20
c = 30
Keyword in Java
Keywords are the reserved words that have some predefined meaning.
They cannot be used as a variable, literal and class name.
Java has 50 reserved keywords.
Operator Precedence
arithmetic * / % + -
equality == !=
bitwise & ^ |
logical && | |
conditional ? :
Assignment Operator
Assignment operator is used for assigning the value of any variable.
It assigns the value on its right to the operand on its left.
Example: int a =10;
Arithmetic Operator
Arithmetic operators are used to perform arithmetic operation.
Example: +, -, *, /, %
Example: Java program for arithmetic and assignment operator
class ArithmeticDemo
{
public static void main(String args[])
{
int num1 = 15, num2 = 6;
System.out.println( "num1 + num2 : " + (num1+num2) );
System.out.println( "num1 - num2 : " + (num1-num2) );
System.out.println( "num1 * num2 : " + (num1*num2) );
System.out.println( "num1 / num2 : " + (num1/num2) );
System.out.println( "num1 % num2 : " + (num1%num2) );
}
}
Output:
num1 + num2 : 21
num1 - num2 : 9
num1 * num2 : 90
num1 / num2 : 2
num1 % num2 : 3
Unary Operator
It requires only one operand. Unary operator performs the operations like increment, decrement
etc.
Example: Simple program for unary operator
class IncreDecreDemo
{
public static void main(String[] args)
{
int i = 5;
i++
System.out.println(i); // prints 6
++i;
System.out.println(i); // prints 7
System.out.println(++i); // prints 8
System.out.println(i++); // prints 8
System.out.println(++i); // prints 10
}
}
Relational Operator
Relational operators are used to comparison between two operands. They generate the result in
form of true and false i.e. boolean value.
Example: Simple program for relational operator
class RelationalDemo
{
public static void main(String args[])
{
int num1 = 15;
int num2 = 30;
System.out.println("num1 == num2 = " + (num1 == num2) );
System.out.println("num1 != num2 = " + (num1 != num2) );
System.out.println("num1 > num2 = " + (num1 > num2) );
System.out.println("num1 < num2 = " + (num1 < num2) );
System.out.println("num1 >= num2 = " + (num1 >= num2) );
System.out.println("num1 <= num2 = " + (num1 <= num2) );
}
}
Output:
num1 == num2 = false
num1 != num2 = true
num1 > num2 = false
num1 < num2 = true
num2 >= num1 = false
num2 <= num1 = true
Bitwise Operator
Bitwise operator works on the binary value. It performs only on 1 and 0.
Example: Simple program for bitwise operator
class BitDemo
{
public static void main(String args[])
{
int x = 5;
int y = 3;
System.out.println("x | y = "+(x | y));
System.out.println("x & y = "+(x & y));
System.out.println("x ^ y = "+(x ^ y));
System.out.println("x >> 1 = "+(x >> 1));
System.out.println("x << 1 = "+(x << 1));
System.out.println("x >>> 1 = "+(x >>> 1));
}
}
Output:
x|y=7
x&y=1
x^y=6
x >> 1 = 2
x << 1 = 10
x >>> 1 = 2
Logical Operator
Logical operator gives the true or false result.
It is used for checking more than one condition.
Example: Program for logical operator
class LogicalTest
{
public static void main(String args[])
{
boolean b1 = false;
boolean b2 = true;
System.out.println("b1 && b2 = " + (b1&&b2));
System.out.println("b1 || b2 = " + (b1||b2) );
System.out.println("! (b1 && b2) = " + ! (b1 && b2));
}
}
Output:
b1 && b2 = false
b1 || b2 = true
! (b1 && b2) = true
Conditional Operator (? :)
Conditional operator is also known as ternary operator in Java. It works like if else statement.
Expr1 ? Expr2 : Expr3 (if Expr1 is true it return Expr2 else Expr3)
Write a java program to find maximum and minimum number from given three numbers
using conditional operator.
Example: Program for conditional operator
class MaxMinTest
{
public static void main(String args[])
{
int a = 15;
int b = 30;
int c = 25;
int max = (a > b & a > c) ? a : (b > c) ? b : c;
int min = (a<b & a<c) ? a : (b<c) ? b : c;
System.out.println("Maximum value is: "+max);
System.out.println("Minimum value is: "+min);
}
}
Output:
Maximum value is: 30
Minimum value is: 15
Data Types in Java
Data type is used for declaring variable.
Data type tells about the size and value type which is stored in the variable.
Data types hold different kind of information.
Types of Data Type
Type Size Range
char
The char data type is a single 16-bit Unicode character.
It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).
boolean
The boolean data type has only two possible values: true and false.
Classes
Class is reference data type in Java.
All the objects & methods are declared inside the class.
Syntax:
class Test
{
Variable declaration;
Method declaration:
}
Interfaces
Interface is also a kind of class.
An interface does not implement any code because it defines only abstract method and final
variable.
Syntax:
interface Test
{
variable declaration;
method declaration;
}
Arrays
Array is collection of similar data type.
Array can be declared in any data type.
Syntax:
int a[];
char b[] = new char b[];
Control Flow Statements in Java
In Java there are three types of control flow statements:
Flow Diagram
Syntax:
if (boolean expr)
{
statement 1; //expr true
}
else
{
statement 2; //expr false
}
Flow Diagram
Output:
Largest number is: 30
Switch Case Statement
It is type of selection mechanism that provides multi-way selection.
Flow Diagram
Output:
Friday
Loop Statements in Java
While statement
While loop is used for continually executing a block of statement.
It repeats the statement while a given condition is true.
Syntax:
while (expresison)
{
Statements ;
}
Output:
Fibonacci series is: 0 1 1 2 3 5 8 13 21 34
For loop
The for loop also repeats until given condition is met.
Syntax:
for (initialization; condition; increment/decrement)
{
statements ;
}
Example: Program for "for loop"
Write a Java program to print even numbers between the given ranges using for loop.
class EvenNumber
{
public static void main(String args[])
{
int n;
System.out.print("Even number are: ");
for( n = 0; n <= 20; ++n)
{
if (n % 2 == 0)
System.out.print(" "+n);
}
}
}
Output:
Even number are: 0 2 4 6 8 10 12 14 16 18 20
do-while loop
The statement inside the do block executes at least once until the condition of while is either true
or false.
Syntax:
do
{
Statements ;
}
while (condition) ;
Example: Simple program for do-while loop
class DoWhile
{
public static void main(String args[])
{
int a = 1;
do
{
System.out.println("Value of a : "+a);
++a;
}
while (a<10);
}
}
Output:
Value of a : 1
Value of a : 2
Value of a : 3
Value of a : 4
Value of a : 5
Value of a : 6
Value of a : 7
Value of a : 8
Value of a : 9
Break Statement
Break statement is basically used for exit from loop.
In case of break it goes completely out of all the nested loops.
Example: Simple program for break statement
class BreakDemo
{
public static void main(String args[])
{
int arr[] = {5,10,15,20,25,30};
int n ;
int search = 15;
boolean b = false;
for(n = 0; n < arr.length; n++)
{
if(arr[n] == search)
{
b = true;
break;
}
}
if(b)
System.out.println("Number found " +search+" at index of "+n);
else
System.out.println("Element is not found");
}
}
Output:
Number found 15 at index of 2
Continue Statement
Continue statement is used to skip the current iteration of while, for or do-while loop.
It causes the immediate jump to next iteration of loop.
Example: Program for Continue statement
Program for printing odd and even number is different columns.
class ContinueDemo
{
public static void main(String []args)
{
for (int j = 1; j <= 10; j++)
{
System.out.print(j+" ");
if (j % 2 != 0)
continue;
System.out.println(" ");
}
}
}
Output:
1 2
3 4
5 6
7 8
9 10
Arrays in Java
Introduction to Arrays
An array is a container object that contains the similar type of data. It can hold both primitive
and object type data.
Each item in an array is called an element and each element is accessed by its numeric index.
Features of Arrays
Retrieve and sort the data easily.
Arrays are created during runtime.
Arrays can hold the reference variables of other objects.
Arrays are fixed in size.
Types of Arrays
1. Single dimensional arrays
2. Multidimensional arrays
Single Dimensional Arrays
Declaration of Single Dimensional Arrays
Give the name and type to the arrays called declaration of the array.
For example,
int[ ] arr or int [ ]arr or int arr[ ];
byte[ ] arr;
short[ ] arr;
long[ ] arr;
char[ ] chr;
String[ ] str ect.
Creating, Initializing and Accessing an Array
int arr = new int[10]; // creation of integer array of size 10
Example: An example of single dimensional array in Java.
public class ArrayDemo
{
public static void main(String args[])
{
int arr[] = {2, 4, 5, 7, 9, 10};
for(int i = 0; i < arr.length; i++)
{
System.out.println("arr["+i+"] = "+arr[i]);
}
}
}
Output:
arr[0] = 2
arr[1] = 4
arr[2] = 5
arr[3] = 7
arr[4] = 9
arr[5] = 10
Example: A java program to find the maximum and minimum number in the arrays.
public class MaxMinDemo
{
static void max(int arr[])
{
int max = arr[0];
for( int i = 1; i < arr.length; ++i)
{
if(arr[i] > max)
max = arr[i];
}
System.out.println("Max value is: "+max);
}
static void min(int arr[])
{
int min = arr[0];
for( int i = 1; i < arr.length; ++i)
{
if(arr[i] < min)
min = arr[i];
}
System.out.println("Min value is: "+min);
}
public static void main(String args[])
{
int arr[] = {10, 2, 7 , 3, 16, 21, 9};
max(arr);
min(arr);
}
}
Output:
Max value is: 21
Min value is: 2
The foreach loop
The foreach loop introduced in JDK 1.5 provides the traverse the complete array sequentially
without using index variable.
Example: A simple program to understand the foreach loop.
public class ForEachDemo
{
public static void main(String[] args)
{
int[] arr = {3, 5, 7, 11, 13, 17};
for (int element: arr)
{
System.out.print(element+" ");
}
}
}
Output:
3 5 7 11 13 17
Multidimensional Arrays
In multidimensional array data is stored in form of rows and columns.
Output:
987
654
321
Copying Arrays
System class has a method called arraycopy(), that is used to copy data from one array to
another.
Example: Simple program to copy data from one array to another.
public class ArrayCopyDemo
{
public static void main(String[] args)
{
char[] source = { 'a', 'T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 'R','i', 'd', 'e' };
char[] dest = new char[12];
System.arraycopy(source, 1, dest, 0, 12 );
System.out.println(new String(dest));
}
}
Output:
TutorialRide
Where emp is an object of Employee class. Employee ( ) is the default constructor of that class.
Output:
Employee Id: 101
Employee Name: ABC
Company Name: TutorialRide.com
Classes
Introduction to Class
Class is a blueprint to create different objects.
It encapsulates the object, class, methods, constructor, block and data member.
class keyword is used to declare a class.
Syntax:
class ClassName
{
datatype variablename ;
datatype methodname( parameter )
{
method – body
}
}
Example: Sample of a Class
public class Employee
{
String Name;
int EmpId;
int age;
double salary;
void empDept()
{
}
void empProject()
{
}
}
Nested class
Defining a class within another class, it is called as nested class.
Syntax:
class OuterClass
{
class NestedClass
{
}
}
Inner class
Non-static nested class is known as inner class.
Java inner class provides code optimization.
Inner class can be declared private.
Example: Sample program for inner class
class OuterDemo
{
private int id = 101;
private String name = "CareerRide Info";
private class InnerDemo
{
void method()
{
System.out.println ("Id : "+id+" Name : "+name);
}
}
public static void main(String args[])
{
OuterDemo outer=new OuterDemo();
OuterDemo.InnerDemo innner=outer.new InnerDemo();
innner.method();
}
}
Output:
Id : 101 Name : CareerRide Info
Local class
A class which is declared inside the method body is known as local class.
Output:
a + b + c = 150
Anonymous class
A class is declared without name is known as anonymous class. The instance of anonymous class
is created at the time of its object creation.
Output:
Speed of Bike : 50 Km/h
Constructor in Java
A special type of method that is used to initialize the object, is known as constructor.
Both the constructor and class name must be same.
They are invoked automatically when an object creates.
Java compiler creates a default constructor for a class when any explicit constructor of that class
is not declared.
Types of Constructor
Java provides two types of constructors:
1. Default constructor
2. Parameterized constructor
Default constructor
Default constructor is also known as no-args constructor because it has no parameter.
Example: Sample program for default constructor
class DefaultCon
{
int length = 25;
int width = 20;
DefaultCon()
{
System.out.println("Area of rectangle: "+(length*width));
}
public static void main(String args[])
{
DefaultCon emp = new DefaultCon();
}
}
Output:
Area of Rectangle: 375
Constructor Overloading
Constructor overloading means declaring multiple constructors with different parameter in the
similar class.
Example: Sample program for constructor Overloading
class Employee
{
String name;
int age;
String company;
Employee (String a, int b)
{
name = a ;
age = b ;
}
Employee (String a, int b, String c)
{
name = a ;
age = b ;
company = c;
}
Employee (String a, String b)
{
name = a ;
company = b ;
}
void display()
{
System.out.println(name+" "+age+" "+company);
}
public static void main(String args[])
{
System.out.println("Name Age Company");
Employee emp1 = new Employee("ABC", 23);
Employee emp2 = new Employee("XYZ",30,"TutorialRide.com");
Employee emp3 = new Employee("PQR", "CareerRide Info");
emp1.display();
emp2.display();
emp3.display();
}
}
Output:
Name Age Company
ABC 23 null
XYZ 30 TutorialRide.com
PQR 0 CareerRide Info
Output:
Area of Rectangle: 2385
Output:
Default constructor:
Employee ID: 100 Name: XYZ
Methods in Java
Methods
A method is the block of code that can be called anywhere in a program. It contains a group of
statements to perform an operation.
Combination of method name and parameter is known as method signature.
Required elements of method declaration are the method name, return type, a pair of parenthesis
and body between braces {}.
Syntax:
modifier returntype methodName (parameter)
{
// body
}
Example:
public static int display (int a, String b)
{
//method body
}
where,
public static: modifiers
int: return type
display: method name
int a, String b: parameters
display (int a, String b): method signature
class SwapNumber
{
public static void main(String[] args)
{
int n1 = 30;
int n2 = 45;
int temp;
System.out.println("Before swapping, n1 = " + n1 + " and n2 = " + n2);
swapMethod(n1, n2);
}
public static void swapMethod(int n1, int n2)
{
n1 = n1 + n2;
n2 = n1 - n2;
n1 = n1 - n2;
System.out.println("After swapping, n1 = " + n1 + " and n2 = " + n2);
}
}
Output:
Before swapping, n1 = 30 and n2 = 45
After swapping, n1 = 45 and n2 =30
Static Method
When a method is declared with static keyword, it is known as a static method.
A static method can be invoked without creating an object of the class.
Static method belongs to class level.
Static Block
Static block is also called as an initialization block.
It is executed only once before main method at the time of class loading.
A class can have any number of a static block.
Syntax:
class classname
{
Static
{
//code
}
}
Example: Sample program for static method
public class StaticMethod
{
static
{
System.out.println("First static block"); //static block
}
static void m1 ()
{
System.out.println("Static method");
}
void m2()
{
System.out.println("Non-static method");
}
Static
{
System.out.println("Second static block"); //static block
}
public static void main(String args[])
{
m1(); //invoked static method
StaticMethod sm = new StaticMethod();
sm.m2(); // invoked non static method
}
}
Output:
First static block
Second static block
Static method
Non-static method
The “finalize ()” method
Java runtime calls finalize () method when an object is about to get garbage collector.
It is called explicitly to identify the task to be performed.
The finalize() method is always declared as protected because it prevents access to the outside
class.
Syntax:
protected void finalize ()
{
// finalize code
}
Output:
50 50 100
Unboxing
Converting an object of wrapper class into corresponding primitive data type is known as
unboxing. For example Integer to int.
Example: Sample program for unboxing
class UnBoxDemo
{
public static void main(String args[])
{
Integer x = new Integer(15);
int y = x.intValue();
int z = x * y;
System.out.println(x+" "+y+" "+z);
}
}
Output:
15 15 225
boolean Boolean
byte Byte
char Character
float Float
int Integer
long Long
short Short
double Double
1. Built-in packages
Built-in packages are already defined in java API. For example: java.util, java.io, java,lang,
java.awt, java.applet, java.net, etc.
2. User defined packages
The package we create according to our need is called user defined package.
Creating a Package
We can create our own package by creating our own classes and interfaces together. The package
statement should be declared at the beginning of the program.
Syntax:
package <packagename>;
class ClassName
{
……..
……..
}
How to compile?
Syntax: javac –d directory javafilename
For Example: javac –d . Demo.java
How to run?
To run: java p1.Demo
//Bike.java
package vehicles;
public class Bike implements Vehicle
{
public void run()
{
System.out.println("Bike is running.");
}
public void speed()
{
System.out.println("Speed of Bike: 50 Km/h");
}
public static void main(String args[])
{
Bike bike = new Bike();
bike.run();
bike.speed();
}
}
Compile:
javac –d . Vehicle.java
javac –d . Bike.java
Run:
java vehicles.Bike
Output:
Bike is running
Speed of Bike: 50 Km/h
The “import” keyword
The import keyword provides the access to other package classes and interfaces in current
packages.
“import” keyword is used to import built-in and user defined packages in java program.
Interface
Note: A class can implement more than one interface. Java can achieve multiple inheritances by
using interface.
Output:
Area of Rectangle: 582.61
Are of square: 100.0
Area of Circle: 84.905594
Output:
Vehicle is running.
Bike is stop.
Marker Interface
An interface which does not contain any fields and methods is known as marker or tag interface.
It is an empty interface.
Example:
package java.util;
public interface EventListner
{
}
It contains both abstract and non abstract method. It contains only abstract method.
Abstract class is the partially implemented class. Interface is fully unimplemented class.
It can have main method and constructor. It cannot have main method and constructor.
It can have static, non-static, final, non-final variables. It contains only static and final variable.
Output:
The square of the 25 is: 625
The cube of the 25 is: 15625
Types of inheritance
There are three types of inheritance in Java.
1. Single level
2. Multilevel inheritance
3. Hierarchical
Single Level Inheritance
When a class extends only one class, then it is called single level inheritance.
Syntax:
class A
{
//code
}
class B extends A
{
//code
}
Example: Sample program for single level inheritance
class Parent
{
public void m1()
{
System.out.println("Class Parent method");
}
}
public class Child extends Parent
{
public void m2()
{
System.out.println("Class Child method");
}
public static void main(String args[])
{
Child obj = new Child();
obj.m1();
obj.m2();
}
}
Output:
Class Parent method
Class Child method
Multilevel Inheritance
Multilevel inheritance is a mechanism where one class can be inherited from a derived class
thereby making the derived class the base class for the new class.
Syntax:
class A
{
//code
}
class B extends A
{
//code
}
class C extends B
{
//code
}
Example: Sample program for multilevel inheritance
class Grand
{
public void m1()
{
System.out.println("Class Grand method");
}
}
class Parent extends Grand
{
public void m2()
{
System.out.println("Class Parent method");
}
}
class Child extends Parent
{
public void m3()
{
System.out.println("Class Child method");
}
public static void main(String args[])
{
Child obj = new Child();
obj.m1();
obj.m2();
obj.m3();
}
}
Output:
Class Grand method
Class Parent method
Class Child method
Hierarchical Inheritance
When one base class can be inherited by more than one class, then it is called hierarchical
inheritance.
Syntax:
class A
{
// code
}
class B extends A
{
// code
}
class C extends A
{
//code
}
Example: Sample program for hierarchical inheritance
class A
{
public void m1()
{
System.out.println("method of Class A");
}
}
class B extends A
{
public void m2()
{
System.out.println("method of Class B");
}
}
class C extends A
{
public void m3()
{
System.out.println("method of Class C");
}
}
class D extends A
{
public void m4()
{
System.out.println("method of Class D");
}
}
public class MainClass
{
public void m5()
{
System.out.println("method of Class MainClass");
}
public static void main(String args[])
{
A obj1 = new A();
B obj2 = new B();
C obj3 = new C();
D obj4 = new D();
obj1.m1();
obj2.m1();
obj3.m1();
obj4.m1();
}
}
Output:
method of Class A
method of Class A
method of Class A
method of Class A
Multiple Inheritances
In multiple inheritance, one derive class can extend more than one base class.
Multiple inheritances are basically not supported by Java, because it increases the complexity of
the code.
But they can be achieved by using interfaces.
Fig: Multiple Inheritance
Access modifiers are simply a keyword in Java that provides accessibility of a class and its
member. They set the access level to methods, variable, classes and constructors.
Types of access modifier
There are 4 types of access modifiers available in Java.
public
default
protected
private
public
The member with public modifiers can be accessed by any classes. The public methods,
variables or class have the widest scope.
Output:
Employee Id : 101
Employee name : Jack
Employee Department : Networking
private
The private methods, variables and constructor are not accessible to any other class. It is the most
restrictive access modifier. A class except a nested class cannot be private.
Output:
Private int a = 101
String s = TutorialRide
101 TutorialRide
private Yes No No No
Output:
Constructor of Animal: super call from Lion constructor
Constructor of Lion.
Output:
50
100
The final keyword in Java indicates that no further modification is possible. Final can be
Variable, Method or Class
Final Variable
Final variable is a constant. We cannot change the value of final variable after initialization.
Output:
Compile time error
Final Class
When a class is declared as a final, it cannot be extended.
Output:
Compile time error
Abstraction & Encapsulation in Java
Abstraction
Abstraction is the technique of hiding the implementation details and showing only functionality
to the user.
For example, when we call any person we just dial the numbers and are least bothered about the
internal process involved.
Abstract class
A class that can contain abstract keyword is known as an abstract class.
Abstract methods do not have body.
It forces the user to extend the implementation rather than modification.
An abstract class cannot be instantiated.
Abstract Method
If a method is declared as an abstract, then it is called abstract method.
It does not have implementation.
It contains method signature but not method body.
Syntax:
abstract class Student
{
private String name;
private int Rollno
private String course;
public abstract int m1()
{
}
}
Output:
Speed of Bike is: 60 Km/h
Speed of Car is: 70 Km/h
Encapsulation
Encapsulation is the mechanism to bind together code (methods) and data (variables) into a
single unit.
Encapsulation is used for information hiding.
Encapsulation can be achieved by declaring variables of class as private.
Advantages of Encapsulation
Using getter and setter method, the field of the class can be made read-only or write-only.
It improves the flexibility & maintainability of the code.
By encapsulation we can hide the implementation details.
Class has total control over the data.
Example: Program to use setter getter method in Java.
// EmpSetGet.java
Output:
Employee Id : 101
Name : ABC
Age : 25
Department : Testing
Polymorphism in Java
Polymorphism is derived from two Greek words: poly and morph
Poly means many and morph means form.
Polymorphism is the ability to present same interface in different forms.
So, polymorphism describes a pattern in which classes have different functionalities while
sharing a common interface.
Types of Polymorphism
1. Runtime polymorphism
Compiler cannot determine the method at compile time.
Method overriding is the perfect example of runtime polymorphism.
It is also called as dynamic polymorphism.
Example: Program for runtime polymorphism
class A
{
A()
{
System.out.println("Constructor of A ");
}
public void show()
{
System.out.println ("method of class A");
}
}
class B extends A
{
B()
{
System.out.println("Constructor of B");
}
public void show()
{
System.out.println ("method of class B");
}
}
class C extends B
{
C()
{
System.out.println("Constructor of C");
}
public void show()
{
System.out.println("method of class C");
}
}
public class D
{
public static void main (String args [])
{
A obj1 = new A();
A obj2 = new B();
B obj3 = new C();
obj1.show();
obj2.show();
obj3.show();
}
}
Output:
Constructor of A
Constructor of A
Constructor of B
Constructor of A
Constructor of B
Constructor of C
method of class A
method of class B
method of class C
Output:
The sum of integer: 80
The sum of double: 107.0
The sum of String: Java Tutorial
Method Overloading
If a class has more than one method with the same name but different parameter, it is known as
method overloading.
Code readability of the program can be increased by method overloading.
Example: Program for method overloading
class OverLoadDemo
{
void sum (int a, int b)
{
System.out.println ("The sum of integer: "+(a+b));
}
void sum (double a, double b)
{
System.out.println ("The sum of double: "+(a+b));
}
void sum (int a, double b)
{
System.out.println ("The sum of int and double: "+(a+b));
}
void sum (String a, String b)
{
System.out.println ("The sum of String: "+(a+b));
}
public static void main(String args[])
{
OverLoadDemo over = new OverLoadDemo();
over.sum(20,35);
over.sum(21.3,18.7);
over.sum(17, 24.6);
over.sum("CareerRide", " Info");
}
}
Output:
The sum of integer: 55
The sum of double: 40.0
The sum of int and double: 41.6
The sum of String: CareerRide Info
Method Overriding
In method overriding, both base and derived class have the same method signature. It means
method name and arguments are same in both classes.
Output:
show method of Derive class
display method of Base class
Exception Handling in Java
Exception
Exception is an event that arises during the execution of the program, and it terminates the
program abnormally. It then displays system generated error message.
Exception Handling
Exception handling is the mechanism to handle the abnormal termination of the program.
For example :ClassNotFoundException, NumberFormatException, NullPointerException etc.
Need for Exception Handling
A program rarely executes without any errors for the first time. Users may run applications in
unexpected ways. A program should be able to handle these abnormal situations.
Exception handling allows executing the code without making any changes to the original code.
It separates the error handling code from regular code.
Exception Hierarchy in Java
Errors are by default unchecked type. Exception can be either checked or unchecked type.
Errors are generally caused by environment in which Exceptions are generally caused by application itself.
application is running.
1. Checked Exceptions
Checked exceptions are also known as compiled time exception, because such exceptions occur
at compile time.
Java compiler checks if the program contains the checked exception handler or not at the time
of compilation.
All these exceptions are subclass of exception class.
Developer has overall control to handle them.
For example: SQLException, IOException, ClassNotFoundException etc.
Output:
error: FileNotFoundException
2. Unchecked Exceptions
Unchecked exceptions are also known as runtime exception.
These include logic errors or improper use of API.
For example: ArrayIndexOutOfBoundException, NullPointerException, ArithmeticException.
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
Exception Handling Keywords in Java
There are five keywords used in Java for exception handling. They are:
i. try
ii. catch
iii. throw
iv. throws
v. finally
The try block
The try block contains the code that might throw an exception. The try block contains at least
one catch block or finally block.
The catch block
A catch block must be declared after try block. It contains the error handling code. A catch block
executes if an exception generates in corresponding try block.
Syntax
try
{
//code that cause exception;
}
catch(Exception_type e)
{
//exception handling code
}
Output :
Divided by zero: java.lang.ArithmeticException: / by zero
Result2 = 5
Output :
Access element two: 5
Exception thrown: java.lang.ArrayIndexOutOfBoundsException: 7
End of the block
Syntax
try
{
// code which generate exception
}
catch(Exception_type1 e1)
{
//exception handling code
}
catch(Exception_type2 e2)
{
//exception handling code
}
Example : A program illustrating multiple catch block using command line argument
public class MultipleCatch
{
public static void main(String args[])
{
try
{
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int c = a / b;
System.out.println("Result = "+c);
}
catch(ArithmeticException ae)
{
System.out.println("Enter second value except zero.");
}
catch (ArrayIndexOutOfBoundsException ai)
{
System.out.println("Enter at least two numbers.");
}
catch(NumberFormatException npe)
{
System.out.println("Enter only numeric value.");
}
}
}
Output:
10 5
Result = 2
10 0
Enter second value except zero.
5
Enter at least two numbers.
10 a
Enter only numeric value.
The finally block
The code present in finally block will always be executed even if try block generates some
exception.
Finally block must be followed by try or catch block.
It is used to execute some important code.
Finally block executes after try and catch block.
Syntax
try
{
// code
}
catch(Exception_type1)
{
// catch block1
}
Catch(Exception_type2)
{
//catch block 2
}
finally
{
//finally block
//always execute
}
Output:
Exception thrown: java.lang.ArrayIndexOutOfBoundsException: 7
First element value: 5
The finally statement is executed
The throw keyword in Java
The throw keyword in Java is used to explicitly throw our own exception.
It can be used for both checked and unchecked exception.
Syntax:
throw new Throwable_subclass;
Output:
Inside test()
Inside main(): java.lang.ArithmeticException: Not valid
The throws keyword in Java
The throws keyword is generally used for handling checked exception.
When you do not want to handle a program by try and catch block, it can be handled by throws.
Without handling checked exceptions program can never be compiled.
The throws keyword is always added after the method signature.
Example : A program to illustrate uses of throws keyword
public class ThrowsDemo
{
static void throwMethod1() throws NullPointerException
{
System.out.println ("Inside throwMethod1");
throw new NullPointerException ("Throws_Demo1");
}
static void throwMethod2() throws ArithmeticException
{
System.out.println("Inside throwsMethod2");
throw new ArithmeticException("Throws_Demo2");
}
public static void main(String args[])
{
try
{
throwMethod1();
}
catch (NullPointerException exp)
{
System.out.println ("Exception is: " +exp);
}
try
{
throwMethod2();
}
catch(ArithmeticException ae)
{
System.out.println("Exception is: "+ae);
}
}
}
Throw Throws
It is used to throw own exception. It is used when program does not handle exception via try block.
Output:
Inside throwMethod1
Exception is: java.lang.NullPointerException: Throws_Demo1
Inside throwsMethod2
Exception is: java.lang.ArithmeticException: Throws_Demo2
Difference between throw and throws keyword in Java
final, finally and finalize () in Java
final
final is a keyword.
It is used to apply restriction on class, method and variables.
final class cannot be inherited, final method cannot be overridden and final variable cannot be
changed.
finally
finally is a block followed by try or catch block.
finally block is executed whether exceptions are handled or not.
We put clean up code in finally block.
finalize ()
finalize is a method.
This method is associated with garbage collection, just before collecting the garbage by system.
It is called automatically.
Creating Custom Exceptions
The exceptions that we create on our own are known as custom exception.
These exceptions are created to generate a solution for anticipated errors as per programmer’s
need.
A “Custom exception class” must be extended from “Exception class”.
Example : Program to create custom exception in Java
// CustomException.java
// CustomDemo.java
Output:
i= 2
i= 4
i= 6
i= 8
Exception in thread "main" CustomException: My Exception Occurred
at CustomDemo.display(CustomDemo.java:11)
at CustomDemo.main(CustomDemo.java:4)