Вы находитесь на странице: 1из 51

Campus Connect Program- BVBCET

Introduction to Object oriented


programming using java

Essentials of Information Technology Page 1


OOPS Features:

What is Java?
Java is:

Object Oriented
Platform independent:
Simple
Secure
Architectural- neutral
Portable
Robust
Multi-threaded
Interpreted
High Performance
Distributed
Dynamic

Note: Java Language Features and OOPS Concepts explanation, please refer the following document.
http://www.cs.armstrong.edu/liang/JavaCharacteristics.pdf

Note: Refer Infosys Slides for discussion on Software Development Life Cycle (SDLC).

Java Environment Setup:


You download a version based on your operating system.
You can refer to installation guide for a complete detail.

Java Basic Syntax:


Object - Objects have states and behaviors. Example: A dog has states -color, name, breedas well as
behaviors -wagging, barking, eating. An object is an instance of a class.
Class - A class can be defined as a template/ blue print that describe the behaviors/statesthat object
of its type support .
Methods - A method is basically a behavior. A class can contain many methods. It is inmethods where
the logics are written, data is manipulated and all the actions are executed.
Instant Variables - Each object has its unique set of instant variables. An object's state iscreated by the
values assigned to these instant variables.

First Java Program:


Let us look at a simple code that would print the words Hello World.

public class MyFirstJavaProgram{

/* This is my first java program.

Essentials of Information Technology Page 2


* This will print 'Hello World' as the output */

public static void main(String[]args){System.out.println("Hello World");// prints


Hello World
}
}

About Java programs, it is very important to keep in mind the following points.

Case Sensitivity - Java is case sensitive which means identifier Hello and hello would havedifferent
meaning in Java.
Class Names - For all class names the first letter should be in Upper Case.

If several words are used to form a name of the class each inner words first letter should be in Upper
Case.
Example class MyFirstJavaClass

Method Names - All method names should start with a Lower Case letter.

If several words are used to form the name of the method, then each inner word's first letter should be in
Upper Case.
Example public void myMethodName()

Program File Name - Name of the program file should exactly match the class name.

When saving the file you should save it using the class name (Remember java is case sensitive) and
append '.java' to the end of the name. (if the file name and the class name do not match your program will
not compile).
Example : Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as
'MyFirstJavaProgram.java'
public static void main(String args[]) - java program processing starts from the main()method which is
a mandatory part of every java program..

Java Identifiers:
All Java components require names. Names used for classes, variables and methods are called
identifiers.
In java there are several points to remember about identifiers. They are as follows:

All identifiers should begin with a letter (A to Z or a to z ), currency character ($) or an


underscore (_ ).
After the first character identifiers can have any combination of characters.

A key word cannot be used as an identifier.

Most importantly identifiers are case sensitive.

Examples of legal identifiers:age, $salary, _value, __1_value

Examples of illegal identifiers : 123abc, -salary

Java Modifiers:
Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There are two

Essentials of Information Technology Page 3


categories of modifiers.
Access Modifiers :default, public , protected, private

Non-access Modifiers :final, abstract, strictfp

We will be looking into more details about modifiers in the next section.

Java Variables:
We would see following type of variables in Java:

Local Variables

Class Variables (Static Variables)

Instance Variables (Non static variables)

Java Arrays:
Arrays are objects that store multiple variables of the same type. However an Array itself is an object on
the heap. We will look into how to declare, construct and initialize in the upcoming chapters.

Java Enums:
Enums were introduced in Java 5.0. Enums restrict a variable to have one of only a few predefined values.
The values in this enumerated list are called enums.
With the use of enums it is possible to reduce the number of bugs in your code.

For example if we consider an application for a fresh juice shop it would be possible to restrict the glass size to
small, medium and Large. This would make sure that it would not allow anyone to order any size other than the
small, medium or large.
Example:

classFreshJuice{

enumFreshJuiceSize{SMALL,MEDIUM,LARGE}FreshJui
ceSizesize;
}

public class FreshJuiceTest{

public static void main(Stringargs[])


{FreshJuicejuice=newFreshJuice();
juice.size=FreshJuice.FreshJuiceSize.MEDIUM;System.out.pri
ntln("Size :"+juice.size);
}
}

Note: enums can be declared as their own or inside a class. Methods, variables, constructors can bedefined
inside enums as well.
Java Keywords:
The following list shows the reserved words in Java. These reserved words may not be used as constant
or variable or any other identifier names.
Essentials of Information Technology Page 4
abstract assert boolean break

Byte case catch char

Class const continue default

Do double else enum

extends final finally float

For goto if implements

import instanceof int interface

Long native new package

private protected public return

Short static strictfp super

switch synchronized this throw

throws transient try void

volatile while

Comments in Java
Java supports single line and multi-line comments very similar to c and c++. All characters available inside any
comment are ignored by Java compiler.

public class MyFirstJavaProgram{

/* This is my first java program.


* This will print 'Hello World' as the output
* This is an example of multi-line comments. */

public static void main(String[]args){


// This is an example of single line comment
/* This is also an example of single line comment. */
System.out.println("Hello World");
}
}

Data Types in Java


There are two data types available in Java:

Primitive Data Types

Reference/Object Data Types

Primitive Data Types:


There are eight primitive data types supported by Java. Primitive data types are predefined by the language and
named by a key word. Let us now look into detail about the eight primitive data types.
byte
short

Essentials of Information Technology Page 5


int
long
float
double
boolean
char

Reference Data Types:


Reference variables are created using defined constructors of the classes. They are used to access
objects. These variables are declared to be of a specific type that cannot be changed. For example,
Employee, Puppy etc.
Class objects, and various type of array variables come under reference data type.

Default value of any reference variable is null.

A reference variable can be used to refer to any object of the declared type or any compatible type.

Example : Animal animal = new Animal("giraffe");

Java Literals:

A literal is a source code representation of a fixed value. They are represented directly in the code without any
computation.
Literals can be assigned to any primitive type variable. For example:

bytea=68; char
a='A';

String literals in Java are specified like they are in most other languages by enclosing a sequence of
characters between a pair of double quotes. Examples of string literals are:

"Hello World"
"two\nlines"
"\"This is in quotes\""

Java language supports few special escape sequences for String and char literals as well. They are:

Notation Character represented

\n Newline (0x0a)

\r Carriage return (0x0d)

\f Formfeed (0x0c)

\b Backspace (0x08)

\s Space (0x20)

\t tab

\" Double quote

Essentials of Information Technology Page 6


\' Single quote
\\ backslash

\ddd Octal character (ddd)

\uxxxx Hexadecimal UNICODE character (xxxx)

Java Access Modifiers:


Java provides a number of access modifiers to set access levels for classes, variables, methods and
constructors. The four access levels are:
Visible to the package.the default. No modifiers are needed.

Visible to the class only (private).

Visible to the world (public).

Visible to the package and all subclasses (protected).

Java Basic Operators:


Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the
following groups:
The Arithmetic Operators:

Operator Description Example

+ Addition - Adds values on either side of the operator A + B will give


30
- Subtraction - Subtracts right hand operand from left hand operand A - B will give -
10
* Multiplication - Multiplies values on either side of the operator A * B will give
200

/ Division - Divides left hand operand by right hand operand B / A will give 2
% Modulus - Divides left hand operand by right hand operand and B % A will give
returns remainder 0

++ Increment - Increase the value of operand by 1 B++ gives 21

-- Decrement - Decrease the value of operand by 1 B-- gives 19


The Relational Operators:

Operator Description Example


== Checks if the value of two operands are equal or not, if yes then (A == B) is
condition becomes true. not true.
!= Checks if the value of two operands are equal or not, if values are not (A != B) is
equal then condition becomes true. true.
> Checks if the value of left operand is greater than the value of right (A > B) is
operand, if yes then condition becomes true. not true.
< Checks if the value of left operand is less than the value of right (A < B) is

Essentials of Information Technology Page 7


operand, if yes then condition becomes true. true.
>= Checks if the value of left operand is greater than or equal to the value (A >= B) is
of right operand, if yes then condition becomes true. not true.
<= Checks if the value of left operand is less than or equal to the value of (A <= B) is
right operand, if yes then condition becomes true. true.

The Logical Operators:

Operator Description Example


&& Called Logical AND operator. If both the operands are non zero then then (A && B)
condition becomes true. is false.
|| Called Logical OR Operator. If any of the two operands are non zero then (A || B) is
then condition becomes true. true.
! Called Logical NOT Operator. Use to reverses the logical state of its !(A && B)
operand. If a condition is true then Logical NOT operator will make false. is true.

The Assignment Operators:

Operator Description

= Simple assignment operator, Assigns values from right side


operands to left side operand

+= Add AND assignment operator, It adds right operand to the


left operand and assign the result to left operand
-= Subtract AND assignment operator, It subtracts right
operand from the left operand and assign the result to left
operand
*= Multiply AND assignment operator, It multiplies right operand
with the left operand and assign the result to left operand
/= Divide AND assignment operator, It divides left operand with
the right operand and assign the result to left operand
%= Modulus AND assignment operator, It takes modulus using
two operands and assign the result to left operand
<<= Left shift AND assignment operator

>>= Right shift AND assignment operator

&= Bitwise AND assignment operator

^= bitwise exclusive OR and assignment operator

|= bitwise inclusive OR and assignment operator

Essentials of Information Technology Page 8


C %= A is equivalent to C
=C%A
C <<= 2 is same as
Example C = C << 2
C >>= 2 is same as
C = A + B will assigne value of A + B into C
C = C >> 2

C += A is equivalent to C = C + A C &= 2 is same as C = C


&2
C -= A is equivalent to C = C - A
C ^= 2 is same as C = C
C *= A is equivalent to C = C * A ^2

C /= A is equivalent to C = C / A C |= 2 is same as C = C
|2

Essentials of Information Technology Page 9


Misc Operators
There are few other operators supported by Java Language.

Conditional Operator ( ? : ):
Conditional operator is also known as the ternary operator. This operator consists of three operands and is used
to evaluate boolean expressions. The goal of the operator is to decide which value should be assigned to the
variable. The operator is written as :

variable x = (expression) ?valueif true: value if false

instanceOf Operator:
This operator is used only for object reference variables. The operator checks whether the object is of a
particular type(class type or interface type). instanceOf operator is wriiten as:

( Objectreference variable ) instanceOf (class/interfacetype)

The while Loop:


A while loop is a control structure that allows you to repeat a task a certain number of times.

Syntax:
The syntax of a while loop is

while(condition)
{
//statements
}

The do...while Loop:


A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one
time.
Syntax:
The syntax of a do...while loop is:

do
{
//Statements }
while(Boolean_expression);

The for Loop:


A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a
specific number of times.
A for loop is useful when you know how many times a task is to be repeated.

Syntax:
The syntax of a for loop is:

for(initialization;Boolean_expression;update)
{
//Statements
}
Enhanced for loop in Java:
As of java 5 the enhanced for loop was introduced. This is mainly used for Arrays.

Syntax:
The syntax of enhanced for loop is:

for(declaration:expression)
{
//Statements
}

The break Keyword:


The break keyword is used to stop the entire loop. The break keyword must be used inside any loop or a switch
statement.
The break keyword will stop the execution of the innermost loop and start executing the next line of code after
the block.
The continue Keyword:
The continue keyword can be used in any of the loop control structures. It causes the loop to
immediately jump to the next iteration of the loop.
In a for loop, the continue keyword causes flow of control to immediately jump to the update statement.

In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression.
Syntax :

The syntax of a continue is a single statement inside any loop:

continue;

The if Statement:
An if statement consists of a Boolean expression followed by one or more statements.

Syntax:
The syntax of an if statement is:

if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}

The if...else Statement:


An if statement can be followed by an optional else statement, which executes when the Boolean expression
is false.
Syntax:
The syntax of a if...else is:

if(Boolean_expression){
//Executes when the Boolean expression is true }else{

//Executes when the Boolean expression is false


}

The if...else if...else Statement:


An if statement can be followed by an optional else if...else statement, which is very usefull to test various
conditions using single if...else if statement.
Syntax:
The syntax of a if...else is:

if(Boolean_expression1){
//Executes when the Boolean expression 1 is true }else
if(Boolean_expression2){
//Executes when the Boolean expression 2 is true }else
if(Boolean_expression3){
//Executes when the Boolean expression 3 is true }else {

//Executes when the one of the above condition is true.


}
Nested if...else Statement:
It is always legal to nest if-else statements. When using if , else if , else statements there are few points to
keep in mind.
An if can have zero or one else's and it must come after any else if's.

An if can have zero to many else if's and they must come before the else.

Once an else if succeeds, none of he remaining else if's or else's will be tested.

Syntax:
The syntax for a nested if...else is as follows

If(condition)
{
//statements

If(condition)

{
//statements
}
}
The switch Statement:
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a
case, and the variable being switched on is checked for each case.
Syntax:
The syntax of enhanced for loop is:

switch(expression){ case
value:
//Statements
break;//optional
casevalue://Statements
break;//optional

//You can have any number of case statements.


default://Optional
//Statements
}

Java Methods:
A Java method is a collection of statements that are grouped together to perform an operation. When you
call the System.out.println method, for example, the system actually executes several statements in order to
display a message on the console.
In general, a method has the following syntax:

modifierreturnValueTypemethodName(list of parameters) {// Method body;


}

A method definition consists of a method header and a method body. Here are all the parts of a method:

Modifiers: The modifier, which is optional, tells the compiler how to call the method. Thisdefines the
access type of the method.
Return Type: A method may return a value. The returnValueType is the data type of thevalue the
method returns. Some methods perform the desired operations without returning a value. In this case,
the returnValueType is the keyword void.
Method Name: This is the actual name of the method. The method name and the parameterlist together
constitute the method signature.
Parameters: A parameter is like a placeholder. When a method is invoked, you pass a valueto the
parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type,
order, and number of the parameters of a method. Parameters are optional; that is, a method may contain
no parameters.
Method Body: The method body contains a collection of statements that define what themethod does.

Object and Class in Java


In object-oriented programming technique, we design a program using objects and classes.

Object is the physical as well as logical entity whereas class is the logical entity only.
Object in Java

An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car etc.
It can be physical or logical (tengible and intengible). The example of integible object is banking
system.

An object has three characteristics:

state: represents data (value) of an object.

behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.

identity: Object identity is typically implemented via a unique ID. The value of the ID is not
visible to the external user. But,it is used internally by the JVM to identify each object uniquely.

For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is
used to write, so writing is its behavior.

Object is an instance of a class. Class is a template or blueprint from which objects are created.
So object is the instance(result) of a class.

Class in Java
A class is a group of objects that has common properties. It is a template or blueprint from which
objects are created.

A class in java can contain:

data member

method
constructor

block

class and interface

Syntax to declare a class:


class <class_name>{
data member;
method;
}

Simple Example of Object and Class


In this example, we have created a Student class that have two data members id and name. We are
creating the object of the Student class by new keyword and printing the objects value.

class Student1{
int id;//data member (also instance variable)
String name;//data member(also instance variable)

public static void main(String args[]){


Student1 s1=new Student1();//creating an object of Student
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Output:0 null

Instance variable in Java


A variable that is created inside the class but outside the method, is known as instance
variable.Instance variable doesn't get memory at compile time.It gets memory at runtime when
object(instance) is created.That is why, it is known as instance variable.

Method in Java
In java, a method is like function i.e. used to expose behaviour of an object.

Advantage of Method
Code Reusability

Code Optimization

new keyword
The new keyword is used to allocate memory at runtime.

Example of Object and class that maintains the records of


students
In this example, we are creating the two objects of Student class and initializing the value to these
objects by invoking the insertRecord method on it. Here, we are displaying the state (data) of the
objects by invoking the displayInformation method.

class Student2{
int rollno;
String name;

void insertRecord(int r, String n){ //method


rollno=r;
name=n;
}

void displayInformation(){System.out.println(rollno+" "+name);}//method

public static void main(String args[]){


Student2 s1=new Student2();
Student2 s2=new Student2();

s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");

s1.displayInformation();
s2.displayInformation();

}
}

111 Karan
222 Aryan

As you see in the above figure, object gets the memory in Heap area and reference variable refers
to the object allocated in the Heap memory area. Here, s1 and s2 both are reference variables that
refer to the objects allocated in memory.

Another Example of Object and Class


There is given another example that maintains the records of Rectangle class. Its exaplanation is
same as in the above Student class example.

class Rectangle{
int length;
int width;

void insert(int l,int w){


length=l;
width=w;
}

void calculateArea(){System.out.println(length*width);}

public static void main(String args[]){


Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();

r1.insert(11,5);
r2.insert(3,15);

r1.calculateArea();
r2.calculateArea();
}
}
Output:55
45

What are the different ways to create an object in Java?


There are many ways to create an object in java. They are:

By new keyword

By newInstance() method

By clone() method

By factory method etc.

We will learn, these ways to create the object later.

Annonymous object
Annonymous simply means nameless.An object that have no reference is known as annonymous
object.
If you have to use an object only once, annonymous object is a good approach.

class Calculation{

void fact(int n){


int fact=1;
for(int i=1;i<=n;i++){
fact=fact*i;
}
System.out.println("factorial is "+fact);
}

public static void main(String args[]){


new Calculation().fact(5);//calling method with annonymous object
}
}
Output:Factorial is 120

Creating multiple objects by one type only


We can create multiple objects by one type only as we do in case of primitives.

Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects


Let's see the example:

class Rectangle{
int length;
int width;

void insert(int l,int w){


length=l;
width=w;
}

void calculateArea(){System.out.println(length*width);}

public static void main(String args[]){


Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects

r1.insert(11,5);
r2.insert(3,15);

r1.calculateArea();
r2.calculateArea();
}
}
Output:55
45
Method Overloading in Java
If a class have multiple methods by same name but different parameters, it is known as Method
Overloading.

If we have to perform only one operation, having same name of the methods increases the readability
of the program.

Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three
parameters then it may be difficult for you as well as other programmers to understand the behaviour
of the method because its name differs. So, we perform method overloading to figure out the program
quickly.

Advantage of method overloading?


Method overloading increases the readability of the program.

Different ways to overload the method


There are two ways to overload the method in java

1. By changing number of arguments

2. By changing the data type

In java, Method Overloading is not possible by changing the return type of the method.

1)Example of Method Overloading by changing the no. of


arguments
In this example, we have created two overloaded methods, first sum method performs addition of two
numbers and second sum method performs addition of three numbers.

class Calculation{
void sum(int a,int b){System.out.println(a+b);}
void sum(int a,int b,int c){System.out.println(a+b+c);}

public static void main(String args[]){


Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);

}
}

Output:30
40
2)Example of Method Overloading by changing data type of
argument
In this example, we have created two overloaded methods that differs in data type. The first sum
method receives two integer arguments and second sum method receives two double arguments.

class Calculation2{
void sum(int a,int b){System.out.println(a+b);}
void sum(double a,double b){System.out.println(a+b);}

public static void main(String args[]){


Calculation2 obj=new Calculation2();
obj.sum(10.5,10.5);
obj.sum(20,20);

}
}
Output:21.0
40

Constructor in Java
Constructor in java is a special type of method that is used to initialize the object.

Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for
the object that is why it is known as constructor.

Rules for creating java constructor


There are basically two rules defined for the constructor.

1. Constructor name must be same as its class name

2. Constructor must have no explicit return type

Types of java constructors


There are two types of constructors:

1. Default constructor (no-arg constructor)

2. Parameterized constructor
Java Default Constructor
A constructor that have no parameter is known as default constructor.

Syntax of default constructor:


<class_name>(){}

Example of default constructor


In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the
time of object creation.

class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}

Output:

Bike is created

ule: If there is no constructor in a class, compiler automatically creates a default constructor.

Q) What is the purpose of default constructor?


Default constructor provides the default values to the object like 0, null etc. depending on the type.

Example of default constructor that displays the default values

class Student3{
int id;
String name;

void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display();
}
}
Output:

0 null

0 null

Explanation:In the above class,you are not creating any constructor so compiler provides you a
default constructor.Here 0 and null values are provided by default constructor.

Java parameterized constructor


A constructor that have parameters is known as parameterized constructor.

Why use parameterized constructor?


Parameterized constructor is used to provide different values to the distinct objects.

Example of parameterized constructor


In this example, we have created the constructor of Student class that have two parameters. We
can have any number of parameters in the constructor.

class Student4{
int id;
String name;

Student4(int i,String n){


id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
Output:

111 Karan
222 Aryan

Constructor Overloading in Java


Constructor overloading is a technique in Java in which a class can have any number of constructors
that differ in parameter lists. The compiler differentiates these constructors by taking into account
the number of parameters in the list and their type.
Example of Constructor Overloading
class Student5{
int id;
String name;
int age;
Student5(int i,String n){
id = i;
name = n;
}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}

Output:

111 Karan 0
222 Aryan 25

Java static keyword


The static keyword in java is used for memory management mainly. We can apply java static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than
instance of the class.

The static can be:

1. variable (also known as class variable)

2. method (also known as class method)

3. block

4. nested class

1) Java static variable


If you declare any variable as static, it is known static variable.

The static variable can be used to refer the common property of all objects (that is not unique
for each object) e.g. company name of employees,college name of students etc.

The static variable gets memory only once in class area at the time of class loading.
Advantage of static variable
It makes your program memory efficient (i.e it saves memory).

Understanding problem without static variable


class Student{
int rollno;
String name;
String college="ITS";
}
Suppose there are 500 students in my college, now all instance data members will get memory each
time when object is created.All student have its unique rollno and name so instance data member is
good.Here, college refers to the common property of all objects.If we make it static,this field will get
memory only once.

Java static property is shared to all objects.

Example of static variable


//Program of static variable

class Student8{
int rollno;
String name;
static String college ="ITS";

Student8(int r,String n){


rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}

public static void main(String args[]){


Student8 s1 = new Student8(111,"Karan");
Student8 s2 = new Student8(222,"Aryan");

s1.display();
s2.display();
}
}
Output:111 Karan ITS
222 Aryan ITS
Program of counter by static variable
As we have mentioned above, static variable will get the memory only once, if any object changes
the value of the static variable, it will retain its value.

class Counter2{
static int count=0;//will get memory only once and retain its value

Counter2(){
count++;
System.out.println(count);
}

public static void main(String args[]){

Counter2 c1=new Counter2();


Counter2 c2=new Counter2();
Counter2 c3=new Counter2();

}
}

Output:1
2
3
2) Java static method
If you apply static keyword with any method, it is known as static method.

o A static method belongs to the class rather than object of a class.

o A static method can be invoked without the need for creating an instance of a class.

o static method can access static data member and can change the value of it.

Example of static method


//Program of changing the common property of all objects(static field).

class Student9{
int rollno;
String name;
static String college = "ITS";

static void change(){


college = "BBDIT";
}

Student9(int r, String n){


rollno = r;
name = n;
}

void display (){System.out.println(rollno+" "+name+" "+college);}

public static void main(String args[]){


Student9.change();

Student9 s1 = new Student9 (111,"Karan");


Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo");

s1.display();
s2.display();
s3.display();
}
}
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT

this keyword in java


There can be a lot of usage of java this keyword. In java, this is areference variable that refers to
the current object.

Usage of java this keyword


Here is given the 6 usage of java this keyword.
1. this keyword can be used to refer current class instance variable.

2. this() can be used to invoke current class constructor.

3. this keyword can be used to invoke current class method (implicitly)

4. this can be passed as an argument in the method call.

5. this can be passed as argument in the constructor call.

6. this keyword can also be used to return the current class instance.

Suggestion: If you are beginner to java, lookup only two usage of this keyword.

//example of this keyword


class Student11{
int id;
String name;

Student11(int id,String name){


this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student11 s1 = new Student11(111,"Karan");
Student11 s2 = new Student11(222,"Aryan");
s1.display();
s2.display();
}
}
Output111 Karan
222 Aryan
Data Structures

Introduction:

In computer science, a data structure is a particular way of organizing data in a computer so that it can be
used efficiently.

Data Structures is about rendering data elements in terms of some relationship, for better organization and
storage.

For example, we have data player's name "Virat" and age 26. Here "Virat" is of String data type and 26 is
of integer data type. We can organize this data as a record like Player record. Now we can collect and
store player's records in a file or database as a data structure. For example: "Dhoni" 30, "Gambhir" 31,
"Sehwag" 33
In simple language, Data Structures are structures programmed to store ordered data, so that various
operations can be performed on it easily.

Basic types of Data Structures:

As we discussed above, anything that can store data can be called as a data strucure, hence Integer, Float,
Boolean, Char etc, all are data structures. They are known as Primitive Data Structures.
Then we also have some complex Data Structures, which are used to store large and connected data.
Some example of Abstract Data Structure are :
Linked List
Tree
Graph
Stack, Queue etc.
All these data structures allow us to perform different operations on data. We select these data structures
based on which type of operation is required. We will look into these data structures in more details in our
later lessons.

Linear Data Structures:

Linear Data Structure are :

Stack, Queue etc.


Linked List

Stack:

Stack is a linear data structure which follows a particular order in which the operations are
performed. The order may be LIFO (Last In First Out) or FILO(First In Last Out).

Mainly the following three basic operations are performed in the stack:

Push: Adds an item in the stack. If the stack is full, then it is said to be an Overflow condition.
Pop: Removes an item from the stack. The items are popped in the reversed order in which they are
pushed. If the stack is empty, then it is said to be an Underflow condition.
Peek: Get the topmost item.

How to understand a stack practically?


There are many real life examples of stack. Consider the simple example of plates stacked over one
another in canteen. The plate which is at the top is the first one to be removed, i.e. the plate which has
been placed at the bottommost position remains in the stack for the longest period of time. So, it can be
simply seen to follow LIFO/FILO order.

There are two ways to implement a stack:


Using array
Using linked list
Position of Top Status of Stack

-1 Stack is Empty

0 Only one element in Stack

N-1 Stack is Full

N Overflow state of Stack

Queue:

Queue is also an abstract data type or a linear data structure, in which the first element is inserted from one end
called REAR(also called tail), and the deletion of exisiting element takes place from the other end called
as FRONT(also called head). This makes queue as FIFO data structure, which means that element inserted first will
also be removed first.

The process to add an element into queue is called Enqueue and the process of removal of an element from queue is
called Dequeue.
Basic features of Queue:

1. Like Stack, Queue is also an ordered list of elements of similar data types.

2. Queue is a FIFO( First in First Out ) structure.

3. Once a new element is inserted into the Queue, all the elements inserted before the new
element in the queue must be removed, to remove the new element.

4. peek( ) function is oftenly used to return the value of first element without dequeuing it.

Applications of Queue:

Queue, as the name suggests is used whenever we need to have any group of objects in an order in which the first
one coming in, also gets out first while the others wait for there turn, like in the following scenarios :

1. Serving requests on a single shared resource, like a printer, CPU task scheduling etc.

2. In real life, Call Center phone systems will use Queues, to hold people calling them in an order,
until a service representative is free.

3. Handling of interrupts in real-time systems. The interrupts are handled in the same order as they
arrive, First come first served.

Queue can be implemented by using two types of java collections framework

Linked list
Priority queue

Linked list:
A linked list is a data structure consisting of a group of nodes which together represent a sequence.
Under the simplest form, each node is composed of data and a reference (in other words, a link) to the next node in
the sequence; more complex variants add additional links. This structure allows for efficient insertion or removal of
elements from any position in the sequence.

Each element (we will call it a node) of a list is comprising of two items - the data and a reference to
the next node. The last node has a reference to null. The entry point into a linked list is called
the head of the list. It should be noted that head is not a separate node, but the reference to the first
node. If the list is empty then the head is a null reference.

A linked list is a dynamic data structure. The number of nodes in a list is not fixed and can grow and
shrink on demand. Any application which has to deal with an unknown number of objects will need to
use a linked list.

Types of Linked Lists

A singly linked list is described above


A doubly linked list is a list that has two references, one to the next node and another to previous node.

Another important type of a linked list is called a circular linked list where last node of the list points back to the first
node (or the head) of the list.

Linked List Operations

addFirst

The method creates a node and prepends it at the beginning of the list.

Traversing
Start with the head and access each node until you reach null. Do not change the head reference.
addLast
The method appends the node to the end of the list. This requires traversing, but make sure you stop at the last node

Inserting "after"
Find a node containing "key" and insert a new node after it. In the picture below, we insert a new node after "e":

Inserting "before"
Find a node containing "key" and insert a new node before that node. In the picture below, we insert a new node
before "a":

Deletion
Find a node containing "key" and delete it. In the picture below we delete a node containing "A"

Non Linear Data Structures:


Trees
Graphs
Hash Tables

Tree:

A tree is a collection of nodes connected by directed (or undirected) edges.

A tree is a nonlinear data structure, compared to arrays, linked lists, stacks and queues which are linear
data structures.

A tree can be empty with no nodes or a tree is a structure consisting of one node called the root and
zero or one or more sub trees.

A tree has following general properties:

One node is distinguished as a root;


Every node (exclude a root) is connected by a directed edge from exactly one other node; A
direction is: parent -> children

A is a parent of B, C, D,
B is called a child of A.
on the other hand, B is a parent of E, F, K

In the above picture, the root has 3 subtrees.

Each node can have arbitrary number of children. Nodes with no children are called leaves, or external nodes. In the
above picture, C, E, F, L, G are leaves. Nodes, which are not leaves, are called internal nodes. Internal nodes have at
least one child.

Nodes with the same parent are called siblings. In the picture, B, C, D are called siblings. The depth of a node is the
number of edges from the root to the node. The depth of K is 2. The height of a node is the number of edges from the
node to the deepest leaf. The height of B is 2. The height of a tree is a height of a root.

Binary Tree:
A binary tree in which each node has exactly zero or two children is called a full binary tree. In a full tree, there are
no nodes with exactly one child.
A complete binary tree is a tree, which is completely filled, with the possible exception of the bottom level, which is
filled from left to right. A complete binary tree of the height h has between 2 h and 2(h+1)-1 nodes.
Full binary tree complete binary tree

Binary Search Tree(BST):

A binary search tree is a rooted binary tree, whose internal nodes each store a key (and optionally, an associated
value) and each have two distinguished sub-trees, commonly denoted left and right. The tree additionally satisfies the
binary search tree property, which states that the key in each node must be greater than all keys stored in the left sub-
tree and smaller than all keys in right sub-tree.

Operations on a BST:

Searching;
Searching a binary search tree for a specific key can be a recursive or an iterative process.

We begin by examining the root node. If the tree is null, the key we are searching for does not exist in the tree.
Otherwise, if the key equals that of the root, the search is successful and we return the node. If the key is less than
that of the root, we search the left sub tree. Similarly, if the key is greater than that of the root, we search the right sub
tree. This process is repeated until the key is found or the remaining sub tree is null. If the searched key is not found
before a null sub tree is reached, then the item must not be present in the tree.

Insertion:
Insertion begins as a search would begin; if the key is not equal to that of the root, we search the left or right sub trees
as before. Eventually, we will reach an external node and add the new key-value pair (here encoded as a record
'newNode') as its right or left child, depending on the node's key. In other words, we examine the root and recursively
insert the new node to the left sub tree if its key is less than that of the root, or the right sub tree if its key is greater
than or equal to the root.

Deletion:

There are three possible cases to consider:

Deleting a node with no children: simply remove the node from the tree.

Deleting a node with one child: remove the node and replace it with its child.
Deleting a node with two children: call the node to be deleted N. Do not delete N. Instead,
choose either its in-order successor node or its in-order predecessor node, R. Copy the value
of R to N, then recursively call delete on R until reaching one of the first two cases. If you choose in-
order successor of a node, as right sub tree is not NIL (Our present case is node has 2 children),
then its in-order successor is node with least value in its right sub tree, which will have at a
maximum of 1 sub tree, so deleting it would fall in one of first 2 cases.

Traversal:

Once the binary search tree has been created, its elements can be retrieved in-
order by recursively traversing the left sub tree of the root node, accessing the node itself, then
recursively traversing the right sub tree of the node, continuing this pattern with each node in the tree
as it's recursively accessed.

There are three types of tree traversals:


Pre-order

1. Display the data part of root element (or current element)

2. Traverse the left sub tree by recursively calling the pre-order function.

3. Traverse the right sub tree by recursively calling the pre-order function.

Pre-order: F, B, A, D, C, E, G, I, H
In-order (symmetric)

1. Traverse the left sub tree by recursively calling the in-order function

2. Display the data part of root element (or current element)

3. Traverse the right sub tree by recursively calling the in-order function
In-order: A, B, C, D, E, F, G, H, I
Post-order

1. Traverse the left sub tree by recursively calling the post-order function.

2. Traverse the right sub tree by recursively calling the post-order function.

3. Display the data part of root element (or current element).

Post-order: A, C, E, D, B, H, I, G, F

INHERITANCE:
Inheritance is a feature that is present in many object-oriented languages such as C++, Eiffel, Java, Ruby, and
Smalltalk, but each language implements it in its own way.
Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an
application. This also provides an opportunity to reuse the code functionality and fast implementation time.
When creating a class, instead of writing completely new data members and member functions, the programmer can
designate that the new class should inherit the members of an existing class. This existing class is called
the base class, and the new class is referred to as the derived class.
The idea of inheritance implements the is a relationship. For example, mammal IS-A animal, dog IS-A mammal hence
dog IS-A animal as well and so on.

Base & Derived Classes:


A class can be derived from more than one classes, which means it can inherit data and functions from multiple base
classes. To define a derived class, we use a class derivation list to specify the base class(es). A class derivation list
names one or more base classes and has the form:
Where access-specifier is one of default,public, protected, or private, and base-class is the name of a previously
defined class. If the access-specifier is not used, then it is default.
Syntax:-

classSuperclass-name
{
}
class Subclass-name extends Superclass-name
{
//methods and fields
}
Example:

class Employee
{
float salary=40000;
}

class Programmer extends Employee


{
int bonus=10000;
public static void main(String args[])
{
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}

Derived Classes:-
Inheritance is a feature of an object-oriented language that allows classes or objects to be defined as extensions or
Specializations of other classes or objects. In java, classes inherit from other classes. Inheritance is useful when a project contains many
similar, but not identical, types of objects. In this case, the task of the programmer/software engineer is to find commonality in this set of
similar objects, and create a class that can serve as an archetype for this set of classes. 1.1.2
Examples
Squares, triangles, circles, and hexagons are all 2D shapes; hence a Shape class could be an archetype.
Faculty, administrators, office assistants, and technical support staff are all employees, so an Employee class could be an archetype.
Cars, trucks, motorcycles, and buses are all vehicles, so a Vehicle class could be an archetype. When this type of relationship exists
among classes, it is more efficient to create a class hierarchy rather than replicating member functions and p

When this type of relationship exists among classes, it is more efficient to create a class hierarchy rather than replicating member
functions and properties in each of the classes. Inheritance provides the mechanism for achieving this.
Abstract class in Java:

A class that is declared with abstract keyword, is known as abstract class in java. It can have abstract and non-abstract methods
(method with body).
Abstraction in Java:

Abstraction is a process of hiding the implementation details and showing only functionality to the user.

Another way, it shows only important things to the user and hides the internal details for example sending sms, you just type the text and
send the message. You don't know the internal processing about the message delivery.

Abstraction lets you focus on what the object does instead of how it does it.

Before learning java abstract class, let's understand the abstraction in java first.
Ways to achieve Abstaction

There are two ways to achieve abstraction in java

Abstract class (0 to 100%)


Interface (100%)
Abstract class in Java:

A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It cannot be
instantiated.

Example abstract class


1. abstract class A{}
abstract method

A method that is declared as abstract and does not have implementation is known as abstract method.

Example abstract method


1. abstract void printStatus();//no body and abstract

Understanding the real scenario of abstract class


In this example, Shape is the abstract class, its implementation is provided by the Rectangle and Circle classes. Mostly, we don't know
about the implementation class (i.e. hidden to the end user) and object of the implementation class is provided by the factory method.

A factory method is the method that returns the instance of the class. We will learn about the factory method later.

In this example, if you create the instance of Rectangle class, draw() method of Rectangle class will be invoked.
abstract class Shape{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}

class Circle1 extends Shape{


void draw(){System.out.println("drawing circle");}
}

//In real scenario, method is called by programmer or user


class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();//In real scenario, object is provided through method e.g. getShape() meth
od
s.draw();
}
}

Abstract class having constructor, data member, methods etc.

An abstract class can have data member, abstract method, method body, constructor and even main()
method.
//example of abstract class that have method body
abstract class Bike{
Bike(){System.out.println("bike is created");}
abstract void run();
void changeGear(){System.out.println("gear changed");}
}

class Honda extends Bike{


void run(){System.out.println("running safely..");}
}
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}

Method Overriding in Java


If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in java.
In other words, If subclass provides the specific implementation of the method that has been provided
by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding


o Method overriding is used to provide specific implementation of a method that is already
provided by its super class.

o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. method must have same name as in the parent class

2. method must have same parameter as in the parent class.

3. must be IS-A relationship (inheritance).

Example of method overriding


In this example, we have defined the run method in the subclass as defined in the parent class but it
has some specific implementation. The name and parameter of the method is same and there is IS-A
relationship between the classes, so there is method overriding.

class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike2 extends Vehicle{
void run(){System.out.println("Bike is running safely");}

public static void main(String args[]){


Bike2 obj = new Bike2();
obj.run();
}
Output:Bike is running safely

Runtime Polymorphism in Java


Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden
method is resolved at runtime rather than compile-time.

In this process, an overridden method is called through the reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the reference
variable.

Let's first understand the upcasting before Runtime Polymorphism.

Upcasting
When reference variable of Parent class refers to the object of Child class, it is known as upcasting. For
example:
class A{}
class B extends A{}
A a=new B();//upcasting

Example of Java Runtime Polymorphism


In this example, we are creating two classes Bike and Splendar. Splendar class extends Bike class and
overrides its run() method. We are calling the run method by the reference variable of Parent class.
Since it refers to the subclass object and subclass method overrides the Parent class method, subclass
method is invoked at runtime.

Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.

class Bike{
void run(){System.out.println("running");}
}
class Splender extends Bike{
void run(){System.out.println("running safely with 60km");}

public static void main(String args[]){


Bike b = new Splender();//upcasting
b.run();
}
}
Output:running safely with 60km.

super keyword in java


The super keyword in java is a reference variable that is used to refer immediate parent class object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly i.e.
referred by super reference variable.

Usage of java super Keyword


1. super is used to refer immediate parent class instance variable.

2. super() is used to invoke immediate parent class constructor.

3. super is used to invoke immediate parent class method.


1) super is used to refer immediate parent class instance
variable.
//example of super keyword

class Vehicle{
int speed=50;
}

class Bike4 extends Vehicle{


int speed=100;

void display(){
System.out.println(super.speed);//will print speed of Vehicle now
}
public static void main(String args[]){
Bike4 b=new Bike4();
b.display();

}
}
Output:50

2) super is used to invoke parent class constructor.


The super keyword can also be used to invoke the parent class constructor as given below:

class Vehicle{
Vehicle(){System.out.println("Vehicle is created");}
}

class Bike5 extends Vehicle{


Bike5(){
super();//will invoke parent class constructor
System.out.println("Bike is created");
}
public static void main(String args[]){
Bike5 b=new Bike5();

}
}
Output:Vehicle is created
Bike is created

Note: super() is added in each class constructor automatically by compiler.

As we know well that default constructor is provided by compiler automatically but it also adds super()
for the first statement.If you are creating your own constructor and you don't have either this() or
super() as the first statement, compiler will provide super() as the first statement of the constructor.
Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form, built-in package and user-defined package.

There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Here, we will have the detailed learning of creating and using user-defined packages.

Advantage of Java Package


1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

Simple example of java package


The package keyword is used to create a package in java.

//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

How to access package from another package?


There are three ways to access the package from outside the package.

1. import package.*;

2. import package.classname;

3. fully qualified name.

1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.

The import keyword is used to make the classes and interface of another package accessible to the
current package.

Example of package that import the packagename.*


//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java

package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello

2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.

Example of package by import package.classname


//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java

package mypack;
import pack.A;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello

3) Using fully qualified name


If you use fully qualified name then only declared class of this package will be accessible. Now there is
no need to import. But you need to use fully qualified name every time when you are accessing the
class or interface.

It is generally used when two packages have same class name e.g. java.util and java.sql packages
contain Date class.
Example of package by import fully qualified name
//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java

package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello

Access Control and Inheritance:


A derived class can access all the non-private members of its base class. Thus base-class members that should not
be accessible to the member functions of derived classes should be declared private in the base class.
We can summarize the different access types according to who can access them in the following way:

A derived class inherits all base class methods,constructor, members including overloaded, abstract methods

Interfaces:
An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract
methods of the interface.

An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A
class describes the attributes and behaviors of an object. An interface contains behaviors that a class implements.

Declaring Interfaces:

The interface keyword is used to declare an interface. Here is a simple example to declare an interface:
Example:

Let us look at an example that depicts encapsulation:

importjava.lang.*;
//Any number of import statements
publicinterfaceNameOfInterface{
//Any number of final, static fields
//Any number of abstract method declarations\
}

Implementing Interfaces:

When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the
specific behaviours of the interface. If a class does not perform all the behaviours of the interface, the class must
declare itself as abstract.

A class uses the implements keyword to implement an interface. The implements keyword appears in the class
declaration following the extends portion of the declaration.

PublicclassMammalIntimplementsAnimal{
Publicvoideat(){
System.out.println("Mammal eats");
}
Publicvoidtravel(){
System.out.println("Mammal travels");
}
PublicintnoOfLegs(){
return0;
}
Publicstaticvoidmain(String args[]){
MammalInt m =newMammalInt();
m.eat();
m.travel();}
}

This would produce the following result:

Mammal eats
Mammal travels
Exceptions:
An exception is a problem that arises during the execution of a program. An exception can occur for many different
reasons, including the following:

A user has entered invalid data.

A file that needs to be opened cannot be found.

A network connection has been lost in the middle of communications or the JVM has run out of memory.

Some of these exceptions are caused by user error, others by programmer error, and others by physical resources
that have failed in some manner.

To understand how exception handling works in Java, you need to understand the three categories of exceptions:

Checked exceptions: A checked exception is an exception that is typically a user error or a problem that
cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an
exception occurs. These exceptions cannot simply be ignored at the time of compilation.

Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided
by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of
compilation.

Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the
programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For
example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.

Catching Exceptions:

A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed
around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and
the syntax for using try/catch looks like the following:

try
{
//Protected code
}catch(ExceptionName e1)
{
//Catch block
}

A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected
code, the catch block (or blocks) that follow the try is checked. If the type of exception that occurred is listed in a
catch block, the exception is passed to the catch block much as an argument is passed into a method parameter.
The throws/throw Keywords:

If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws
keyword appears at the end of a method's signature.

You can throw an exception, either a newly instantiated one or an exception that you just caught, by using
the throw keyword. Try to understand the different in throws and throw keywords.

Example:

The following is an array is declared with 2 elements. Then the code tries to access the 3rd element of the array
which throws an exception.

import java.io.*;
publicclassExcepTest{
publicstaticvoid main(Stringargs[]) {
try{
int a[]=newint[2];
System.out.println("Access element three :"+ a[3]);
} catch(ArrayIndexOutOfBoundsException e) {System.out.println("Exception thrown :"+ e);
}
System.out.println("Out of the block");
}
}

This would produce the following result:

Exceptionthrown:java.lang.ArrayIndexOutOfBoundsException:3
Out of the block

User defined Exception:

This example shows how to create user defined exception by extending Exception Class.

classWrongInputExceptionextendsException{
WrongInputException(String s){
super(s);
}
}
classInput{
void method()throwsWrongInputException{
thrownewWrongInputException("Wrong input");
}
}
classTestInput{
publicstaticvoid main(String[]args) {
try{
newInput().method();
}
catch(WrongInputExceptionwie){System.out.println(wie.getMessage());
}
}
}

Result:

The above code sample will produce the following result.

Wrong input

Advantages of Exceptions:

Advantage 1: Separating Error-Handling Code from "Regular" Code

Advantage 2: Propagating Errors Up the Call Stack

Advantage 3: Grouping and Differentiating Error Types


Note the following:

A catch clause cannot exist without a try statement.

It is not compulsory to have finally clauses whenever a try/catch block is present.

The try block cannot be present without either catch clause or finally clause.

Any code cannot be present in between the try, catch, finally blocks.

Вам также может понравиться