0% found this document useful (0 votes)
4 views

An Introduction To Core Java Unit-1

The document provides an introduction to Core Java, detailing its features, functionalities, and differences from C++. It covers key concepts such as the Java Virtual Machine (JVM), Java Development Kit (JDK), data types, variables, operators, and control flow statements. Additionally, it includes examples of Java programs to illustrate various programming concepts.

Uploaded by

AFSHA SAYYED
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

An Introduction To Core Java Unit-1

The document provides an introduction to Core Java, detailing its features, functionalities, and differences from C++. It covers key concepts such as the Java Virtual Machine (JVM), Java Development Kit (JDK), data types, variables, operators, and control flow statements. Additionally, it includes examples of Java programs to illustrate various programming concepts.

Uploaded by

AFSHA SAYYED
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 97

Introduction to Core Java

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.

Object-Oriented: Java is a pure object-oriented programming language. It is totally based on


object and class. It follows all basic concepts of OOP e.g. inheritance, abstraction, encapsulation
and polymorphism.

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.

Multithreaded: Java is a multithreaded programming language because it allows multiple tasks


to be performed simultaneously to share the same memory.

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.

Difference between Java and C++


Java C++

Java does not support pointer. C++ supports the pointer concept.

Java doesn’t support structure and union. Structure and union are supported in C++.

Header file is not required. Header file is necessary in C++.

Java does not support operator overloading. It supports operator overloading.


Java uses finalize() method for memory cleanup. C++ uses destructor for memory destroying.

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 has no goto statement. C++ has goto statement.

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

Fig: Procedure to develop Java Program

Example: First Java program


class FirstProgram
{
public static void main(String args[])
{
System.out.println(“Welcome Java”);
}
}

Save: FirstProgram.java
Compile: C:\> javac FirstProgram.java
Run: C:\> java FirstProgram

Output: Welcome Java

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.

abstract continue for new switch

assert defualt goto package synchronized

boolean do if private this

break double implements protected throw

byte else import public throws

case enum instanceof return transient

catch extends int short try

char final interface static void

class finally long strictfp volatile

const float native super while

Added in Java 1.2 = strictfp


Added in Java 1.4 = assert
Added in Java 5.0 = enum
Not used = goto, const
Operators in Java
Operators are special symbols that perform specific operation on one, two or three operands and

Operator Precedence

postfix expr++ expr--

unary ++expr --expr +expr -expr

arithmetic * / % + -

shift << >> >>>

Relational < > <= >= instanceof

equality == !=

bitwise & ^ |

logical && | |

conditional ? :

assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

give the results.

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

byte 1 byte -128 to 127

short 2 byte -32768 to 32767

int 4 byte -2147483648 to 2147483647

long 8 byte -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

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:

1. Decision making statements: if, if else, nested if else


2. Looping statements: while, for, do-while
3. Branching statements: return, break, continue
if statement
 It instructs the program to execute only certain part of the code if the condition is true.
 If boolean value is true then statement1 will be executed.
Syntax:
if (boolean expr)
{
statement 1: //expr true
}
statement 2;

Flow Diagram

Fig: Flow diagram of if statement


if else statement
In this case, when if clause is false then else part will be executed.

Syntax:
if (boolean expr)
{
statement 1; //expr true
}
else
{
statement 2; //expr false
}
Flow Diagram

Fig: Flow diagram of if else statement


Nested if else
Syntax:
if (boolean expr1)
{
statement 1; // expr1 true
}
else if (boolean expr2)
{
Statement 2; // expr 1 false and expr 2 true
}
else
{
statement 3; // expr 2 false
}
Example: Program for nested if else statement
Program to find largest number of three given numbers using if else.
class Test
{
public static void main(String args[])
{
int x = 20;
int y = 15;
int z = 30;
if (x > y)
{
if (x > z)
System.out.println("Largest number is: "+x);
else
System.out.println("Largest number is: "+z);
}
else
{
if (y > z)
System.out.println("Largest number is: "+y);
else
System.out.println("Largest number is: "+z);
}
}
}

Output:
Largest number is: 30
Switch Case Statement
It is type of selection mechanism that provides multi-way selection.
Flow Diagram

Fig: Flow diagram of switch statement

Example: Simple program of switch statement


class SwitchDemo
{
public static void main(String[] args)
{
int day = 6;
String dayString;
switch (day)
{
case 1: dayString = "Sunday";
break;
case 2: dayString = "Monday";
break;
case 3: dayString = "Tuesday";
break;
case 4: dayString = "Wednesday";
break;
case 5: dayString = "Thursday";
break;
case 6: dayString = "Friday";
break;
case 7: dayString = "Saturday";
break;
default: dayString = "Invalid day";
break;
}
System.out.println (dayString);
}
}

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 ;
}

Example: Program for while statement


Program to print the Fibonacci series using while loop
class FiboTest
{
public static void main(String args[])
{
int a = 0;
int b = 1;
int max = 50;
int fib = 1;
System.out.print("Fibonacci series is: "+a);
while ( fib <= max )
{
System.out.print(" "+fib);
fib = a+b;
a = b;
b = fib;
}
}
}

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.

Declaration of Multidimensional Arrays


 int arr[ ][ ], or int[ ][ ] arr, or int [ ][ ]arr.
 char arr[ ][ ] or char[ ][ ] arr or char [ ][ ]arr
 double arr[ ][ ] or double[ ][ ] arr or double [ ][ ]arr.
Example: A sample program to create a multidimensional array.
public class MultiDimeDemo
{
public static void main(String args[])
{
int arr[] [] = {{9,8,7},{6,5,4},{3,2,1}};
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}

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

Classes & Objects


Object
In object-oriented programming everything comes under the object and class.
 Object is a physical entity which has states and behavior e.g. dog, car, fan, bicycles, pen etc.
 Dogs have states (color, name, breed) and behaviors (barking, eating etc)
 Cars have states (color, brand, speed, gear) and behavior (changing gear, applying breaks).
Object Creation
 Creation of an object is also called as instantiation of an object.
 The new operator is used to create an object of a class.
Example:
Employee emp = new Employee ( );

Where emp is an object of Employee class. Employee ( ) is the default constructor of that class.

Example: Program for use of new keyword


class Employee
{
String companyName = "TutorialRide.com";
public Employee(int empId, String name)
{
System.out.println("Employee Id : "+empId+"\nEmployee Name : "+name);
}
public void EmpMethod()
{
System.out.println("Company Name : "+companyName);
}
public static void main(String args[])
{
Employee emp = new Employee(101,"ABC");
emp.EmpMethod();
}
}

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.

Example: Sample program for local class


class OuterDemo
{
private int a = 40;
private int b =50;
void display()
{
int c = 60;
class LocalDemo
{
void method()
{
System.out.println("a + b + c = "+(a+b+c));
}
}
LocalDemo l = new LocalDemo();
l.method();
}
public static void main(String args[])
{
OuterDemo obj=new OuterDemo();
obj.display();
}
}

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.

It can be created by two ways.

1. Using class variable


2. Using interface

Example: Sample program for anonymous class


abstract class Bike
{
abstract void speed();
}
public class AnonymousDemo
{
public static void main(String args[])
{
int s = 50;
Bike bike=new Bike()
{
void speed()
{
System.out.println ("Speed of Bike : "+s+" Km/h" );
}
};
bike.speed();
}
}

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: 500


Parameterized Constructor
A constructor that contains argument list is known as parameterized constructor.
Example: Sample program for parameterized Constructor
class Rectangle
{
int length;
int width;
Rectangle (int a, int b)
{
length = a ;
width = b ;
}
int calculateArea()
{
return(length*width);
}
public static void main(String args[])
{
Rectangle rec = new Rectangle (25, 15);
long area = rec.calculateArea();
System.out.println("Area of Rectangle: "+area);
}
}

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

“this” Keyword in Java


“this” Keyword in Java
 this keyword is a reference to the current object within instance method or a constructor.
 this () is used to invoke current class constructor.
 this can also be used to pass an argument in the method call.
Example: Sample program for using this keyword
public class Rectangle
{
int length, width;
Rectangle(int length, int width)
{
this.length = length;
this.width = width;
}
int areaCal()
{
return (length*width);
}
public static void main(String args[])
{
Rectangle rec = new Rectangle(53, 45);
int area = rec.areaCal();
System.out.println ("Area of Rectangle: "+area);
}
}

Output:
Area of Rectangle: 2385

Example: Sample program for constructor calling


class ConDemo
{
int empId;
String name;
ConDemo()
{
System.out.println("Default Constructor:");
}
ConDemo(int empId, String name)
{
this(); // invoked default constructor
this.empId = empId;
this.name = name;
}
void show()
{
System.out.println("Employee ID: "+empId+" Name: "+name);
}
public static void main(String args[])
{
ConDemo con = new ConDemo(100,"XYZ");
con.show();
}
}

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

Example: Program for method


Program for swapping two numbers without using third variable.

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
}

Wrapper class in Java


 Wrapper classes allow primitive data types to be accessed as objects and objects as a primitive
data types.
 The various wrapper classes for primitive data type are: Boolean, Byte, Character, Double,
Float, Integer, Long and Short.
 Wrapper classes make the primitive type data to act as objects.
Autoboxing
Autoboxing is the process of converting a primitive data type into corresponding wrapper class
object. E.g. int to Integer.
Example: Sample program for autoboxing
class AutoBoxDemo
{
public static void main(String args[])
{
int x = 50;
Integer y = Integer.valueOf(x);
Integer z = x + y;
System.out.println(x+" "+y+" "+z);
}
}

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

Primitive type and their corresponding wrapper class

Primitive type Wrapper class

boolean Boolean

byte Byte

char Character

float Float
int Integer

long Long

short Short

double Double

Features of Wrapper class


 Wrapper classes convert numeric strings into numeric values.
 They provide a way to store primitive data into the object.
 The valueOf() method is available in all wrapper classes except Character.
 All wrapper classes have typeValue() method. This method returns the value of the object as its
primitive type.
Character class method
isDigit(): to determine whether the character is digit.

isLower(): to determine whether the character is lower case alphabet.

isLetter(): to determine whether the character is an alphabet.


Byte class method
byteValue(): returns the Byte value as byte value.

parseByte(): returns byte value from a byte string.


Integer class method
intValue(): returns the Integer value as int value.

parseInt(): returns the int value from a int string.


Packages & Interfaces in Java
Introduction to Packages
A package is a mechanism to group the similar type of classes, interfaces and sub-packages and
provide access control. It organizes classes into single unit.
In Java already many predefined packages are available, used while programming.
For example: java.lang, java.io, java.util etc.
Advantages of Packages
 Packages provide code reusability, because a package has group of classes.
 It helps in resolving naming collision when multiple packages have classes with the same name.
 Package also provides the hiding of class facility. Thus other programs cannot use the classes
from hidden package.
 Access limitation can be applied with the help of packages.
 One package can be defined in another package.
Types of Packages
There are two types of packages available in Java.

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
{
……..
……..
}

Example: Creating a Package


// Demo.java
package p1;
class Demo
{
public void m1()
{
System.out.println("Method m1..");
}
}

How to compile?
Syntax: javac –d directory javafilename
For Example: javac –d . Demo.java

How to run?
To run: java p1.Demo

Example: Program to create and use a user defined ackage in Java.


// Vehicle.java
package vehicles;
interface Vehicle
{
public void run();
public void speed();
}

//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.

There are different 3 ways to access a package from other packages.

1. Using full qualified name


Example
class Demo extends java.util.Scanner
{
//statements
}

2. import only single class


Example
import java.util.Scanner;
class Demo
{
// statements
}

3. import all classes


Example
import java.util.*;
class Demo
{
// statements
}

Interface

 Interface is similar to a class, but it contains only abstract methods.


 By default the variables declared in an interface are public, static and final.
 Interface is a mechanism to achieve full abstraction.
 An interface does not contain any constructor.
Syntax:
interface InterfaceName
{
public void method1();
public void method2();
<type> variableName = value;
}

Example: Sample of an interface


interface Employee
{
static final Id = 101;
static final String name = “ABC”;
void show();
void getSalary(double salary);
}
Extending interfaces
An interface has to extend another interface as it happens in class. It cannot implement another
interface.

Example: Sample program for extending interfaces


interface Base
{
public void display ();
}
interface Derive extends Base
{
public void show ();
}
Implementing interfaces
 A class implements an interface. After that, class can perform the specific behavior on an
interface.
 The implements keyword is used by class to implement an interface.
Syntax:
class ClassName implements interfacename
{
// body of class
}

Note: A class can implement more than one interface. Java can achieve multiple inheritances by
using interface.

Example: Sample program to implements interface in Java


interface Results
{
final static float pi = 3.14f;
float areaOf(float l, float b);
}
class Rectangle implements Results
{
public float areaOf(float l, float b)
{
return (l * b);
}
}
class Square implements Results
{
public float areaOf(float l, float b)
{
return (l * l);
}
}
class Circle implements Results
{
public float areaOf(float r, float b)
{
return (pi * r * r);
}
}
public class InterfaceDemo
{
public static void main(String args[])
{
Rectangle rect = new Rectangle();
Square square = new Square();
Circle circle = new Circle();
System.out.println("Area of Rectangle: "+rect.areaOf(20.3f, 28.7f));
System.out.println("Are of square: "+square.areaOf(10.0f, 10.0f));
System.out.println("Area of Circle: "+circle.areaOf(5.2f, 0));
}
}

Output:
Area of Rectangle: 582.61
Are of square: 100.0
Area of Circle: 84.905594

Example: Sample program to implements multiple inheritance


interface Vehicle
{
void run();
}
interface Bike extends Vehicle
{
void stop();
}
public class Demo implements Bike
{
public void run()
{
System.out.println("Vehicle is running.");
}
public void stop()
{
System.out.println("Bike is stop.");
}
public static void main(String args[])
{
Demo obj = new Demo();
obj.run();
obj.stop();
}
}

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.

For example Serializable, EventListener, MouseListner, Remote, Cloneable etc.

Example:
package java.util;
public interface EventListner
{
}

Differences between Abstract class and Interface

Abstract class Interface

It cannot support multiple inheritances. Interface supports multiple inheritances.

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.

Inheritance & Access Modifiers in Java


Inheritance
 Inheritance can be defined as the process of acquiring the properties of parent’s class by child
class.
 It provides the mechanism of code re-usability and represents IS-A relationship.
For example Bike is the super class (parent’s class) and Honda, Bajaj, TVS are the subclass
(child class, derived class). Honda, Bajaj and TVS have the property of Bike class.
 extends keyword is used for inheritance.
Syntax:
class Base
{
// code
}
class Derive extends Base
{
// code
}

Example: Sample program for inheritance


class SuperDemo
{
int result;
public void square(int a)
{
result = a * a;
System.out.println("The square of the "+a+" is: "+result);
}
}
public class SubDemo extends SuperDemo
{
public void cube(int a)
{
result = a * a * a;
System.out.println("The cube of the "+a+" is: "+result);
}
public static void main(String args[])
{
int a = 25;
SubDemo sub = new SubDemo();
sub.square(a);
sub.cube(a);
}
}

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.

Fig: 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.

Fig: Multilevel Inheritance

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.

Fig: 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

Example: Sample program for multiple inheritance


class X
{
void display()
{
System.out.println("class X dispaly method ");
}
}
class Y
{
void display()
{
System.out.println("class Y display method ");
}
}
public class Z extends X,Y
{
public static void main(String args[])
{
Z obj=new Z();
obj.display();
}
}
Output:
Compile time error
Access Modifiers

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.

Example: Sample program for public access modifier


public static void main(String args[])
{
// code
}
default
When we do not mention any access modifier, it is treated as default. It is accessible only within
same package.

Example: Sample program for default access modifier


int a = 25;
String str = "Java";
boolean m1()
{
return true;
}
protected
The protected modifier is used within same package. It lies between public and default access
modifier. It can be accessed outside the package but through inheritance only.
A class cannot be protected.

Example: Sample program for protected access modifier


class Employee
{
protected int id = 101;
protected String name = "Jack";
}
public class ProtectedDemo extends Employee
{
private String dept = "Networking";
public void display()
{
System.out.println("Employee Id : "+id);
System.out.println("Employee name : "+name);
System.out.println("Employee Department : "+dept);
}
public static void main(String args[])
{
ProtectedDemo pd = new ProtectedDemo();
pd.display();
}
}

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.

Example: Sample program for private access modifier


public class PrivateDemo
{
private int a = 101;
private String s = "TutorialRide";
public void show()
{
System.out.println("Private int a = "+a+"\nString s = "+s);
}
public static void main(String args[])
{
PrivateDemo pd = new PrivateDemo();
pd.show();
System.out.println(pd.a+" "+pd.s);
}
}

Output:
Private int a = 101
String s = TutorialRide
101 TutorialRide

Table for Access Modifier


Access modifier In class In package Outside package by subclass Outside pack
public Yes Yes Yes No

protected Yes Yes Yes No

default Yes Yes No No

private Yes No No No

The super keyword in Java

 super keyword is similar to this keyword in Java.


 It is used to refer to the immediate parent class of the object.
Use of super keyword in Java
 super () calls the parent class constructor with no argument.
 super.methodname calls method from parents class.
 It is used to call the parents class variable.
Example: Sample program for invoking parents class constructor
class Animal
{
public Animal(String str)
{
System.out.println("Constructor of Animal: " + str);
}
}
class Lion extends Animal
{
public Lion()
{
super("super call Lion constructor");
System.out.println("Constructer of Lion.");
}
}
public class Test
{
public static void main(String[] a)
{
Lion lion = new Lion();
}
}

Output:
Constructor of Animal: super call from Lion constructor
Constructor of Lion.

Example: Sample program for calling parents class variable


class Base
{
int a = 50;
}
public class Derive extends Base
{
int a = 100;
void display()
{
System.out.println(super.a);
System.out.println(a);
}
public static void main(String[] args)
{
Derive derive = new Derive();
derive.display();
}
}

Output:
50
100

The final keyword in Java

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.

Example: Sample program for final keyword in Java


class FinalVarDemo
{
final int a = 10;
void show()
{
a = 20;
System.out.println("a : "+a);
}
public static void main(String args[])
{
FinalVarDemo var = new FinalVarDemo();
var.show();
}
}
Output:
Compile time error
Final method
When we declare any method as final, it cannot be override.

Example: Sample program for final method in Java


class Animal
{
final void eat()
{
System.out.println("Animals are eating");
}
}
public class Dear extends Animal
{
void eat()
{
System.out.println("Dear is eating");
}
public static void main(String args[])
{
Dear dear = new Dear();
dear.eat();
}
}

Output:
Compile time error
Final Class
When a class is declared as a final, it cannot be extended.

Example: Sample program for final class in Java


final class Animal
{
void eat()
{
System.out.println("Animals are eating");
}
}
class Dear extends Animal
{
void eat()
{
System.out.println("Dear is eating");
}
public static void main(String args[])
{
Dear dear = new Dear();
dear.eat();
}
}

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()
{
}
}

Example: Program for abstract class and method


abstract class Vehicle
{
abstract int getSpeed();
}
class Bike extends Vehicle
{
int getSpeed()
{
return 60;
}
}
class Car extends Vehicle
{
int getSpeed()
{
return 70;
}
}
public class TestVehicle
{
public static void main(String args[])
{
Vehicle bike = new Bike();
Vehicle car = new Car();
int bikespeed = bike.getSpeed();
int carspeed = car.getSpeed();
System.out.println("Speed of Bike is: "+bikespeed+" Km/h");
System.out.println("Speed of Car is: "+carspeed+" Km/h");
}
}

Output:
Speed of Bike is: 60 Km/h
Speed of Car is: 70 Km/h

Difference between Abstract Class and Final Class


Abstract Class Final Class

Inheritance can be allowed. Inheritance cannot be allowed.


It contains abstract method. It cannot contain abstract method.

Abstract method must be overridden. Final method cannot be overridden.

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

public class EmpSetGet


{
private int empId;
private String name;
private int age;
private String dept;

public int getEmpId()


{
return empId;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String getDept()
{
return dept;
}
public void setEmpId( int empId)
{
this.empId = empId;
}
public void setName(String name)
{
this.name = name;
}
public void setAge( int age)
{
this.age = age;
}
public void setDept(String dept)
{
this.dept = dept;
}
}
Example:
//Employee.java

public class Employee


{
public static void main(String args[])
{
EmpSetGet emp = new EmpSetGet();
emp.setEmpId(101);
emp.setName("ABC");
emp.setAge(25);
emp.setDept("Testing");
System.out.print("Employee Id : "+emp.getEmpId() + "\nName : " + emp.getName() +
"\nAge : " + emp.getAge() + "\nDepartment : "+emp.getDept());
}
}

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

2. Compile Time Polymorphism


 Method overloading is nothing but compile time polymorphism in Java.
 It is checked by the compiler at compile time.
 Compile time polymorphism is also known as static polymorphism.
Example: Program for compile time polymorphism
class Base
{
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 (String a, String b)
{
System.out.println ("The sum of String: "+(a+b));
}
}
public class Derive
{
public static void main(String args[])
{
Base base = new Base();
base.sum(45,35);
base.sum(61.3,45.7);
base.sum("Java", " Tutorial");
}
}

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.

Rules for method overriding


 Method must be written in child class, not in same class.
 Method name and argument must be same.
 A final method cannot be overridden.
 Method should be inherited means IS-A relationship.
 Return type should be same.
Example: Program for method overriding
class Base
{
public void show(int a)
{
System.out.println("show method of Base class");
}
public void display()
{
System.out.println("display method of Base class");
}
}
public class Derive extends Base
{
public void show(int a)
{
System.out.println("show method of Derive class");
}
public void xyz()
{
System.out.println("xyz() method of derive class");
}
public static void main( String args[])
{
Base obj = new Derive();
obj.show(2);
obj.display();
}
}

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

Difference between error and exception


Error Exception

It cannot be caught. It can be handled by try and catch block.

Errors are by default unchecked type. Exception can be either checked or unchecked type.

It is defined in java.lang.Error package. It is defined in java.lang.Exception package.

Errors are generally caused by environment in which Exceptions are generally caused by application itself.
application is running.

Example: StackOverflowError, OutOfMemoryError etc. Example: SQLException, IOException, ClassCastException,


ArrayOutOfBoundException
Types of Exceptions
Java has two types of exceptions.
1. Checked exception
2. Unchecked exception

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.

Example : Sample program for checked exception


import java.io.File;
import java.io.PrintWriter;
public class Checked_Demo
{
public static void main(String args[])
{
File file=new File("E://abc.txt");
PrintWriter pw = new PrintWriter("file");
}
}

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.

Example : Sample program for unchecked exception


class Uncheked_Demo
{
public static void main(String args[])
{
int a = 10;
int b = 0;
int c = a/b;
System.out.println(c);
}
}

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
}

Example : An examples to uses try and catch block in java


class TryCatchDemo
{
public static void main(String args[])
{
int a = 30, b = 3, c = 3;
int result1, result2;
try
{
result1 = a / (b - c);
}
catch(ArithmeticException ae)
{
System.out.println("Divided by zero: "+ae);
}
result2 = a / (b + c);
System.out.println("Result2 = "+result2);
}
}

Output :
Divided by zero: java.lang.ArithmeticException: / by zero
Result2 = 5

Example : A program to illustrate the uses of try and catch block


class ExceptionDemo
{
public static void main(String args[])
{
try
{
int arr[] = new int[5];
arr[2] = 5;
System.out.println("Access element two: " + arr[2]);
arr[7] = 10;
System.out.println("Access element seven: "+ arr[7]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception thrown:" + e);
}
System.out.println("End of the block");
}
}

Output :
Access element two: 5
Exception thrown: java.lang.ArrayIndexOutOfBoundsException: 7
End of the block

Multiple catch blocks


If more than one exception is generated by the program then it uses multiple catch blocks. A
single try block can contain multiple catch blocks.

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
}

Example : A program to implement finally block


class FinallyTest
{
public static void main(String args[])
{
int arr[] = new int[5];
try
{
arr[7] = 10;
System.out.println("Seventh element value: " + arr[7]);
}
catch(ArrayIndexOutOfBoundsException ai)
{
System.out.println("Exception thrown : " + ai);
}
finally
{
arr[0] = 5;
System.out.println("First element value: " +arr[0]);
System.out.println("The finally statement is executed");
}
}
}

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;

Example : A program to illustrate throw keyword in java


public class ThrowTest
{
static void test()
{
try
{
throw new ArithmeticException("Not valid ");
}
catch(ArithmeticException ae)
{
System.out.println("Inside test() ");
throw ae;
}
}
public static void main(String args[])
{
try
{
test();
}
catch( ArithmeticException ae)
{
System.out.println("Inside main(): "+ae);
}
}
}

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.

It handles explicitly thrown exceptions. It handles all exceptions generated by program.

Cannot throw multiple exceptions. Declare multiple exception e.g.


public void method() throws, IOException, SQLException.

It is used within the method. It is used within method signature.

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

public class CustomException extends Exception


{
public CustomException(String msg)
{
super(msg);
}
}

// CustomDemo.java

public class CustomDemo


{
public static void main(String args[]) throws Exception
{
CustomDemo custom = new CustomDemo();
custom.display();
}
public void display() throws CustomException
{
for(int i=2;i<20;i=i+2)
{
System.out.println("i= "+i);
if(i==8)
{
throw new CustomException("My Exception Occurred");
}
}
}
}

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)

You might also like