Beruflich Dokumente
Kultur Dokumente
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).
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:
Java Modifiers:
Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There are two
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
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;
}
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
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.
A reference variable can be used to refer to any object of the declared type or any compatible type.
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:
\n Newline (0x0a)
\f Formfeed (0x0c)
\b Backspace (0x08)
\s Space (0x20)
\t tab
/ 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
Operator Description
C /= A is equivalent to C = C / A C |= 2 is same as C = C
|2
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 :
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:
Syntax:
The syntax of a while loop is
while(condition)
{
//statements
}
do
{
//Statements }
while(Boolean_expression);
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
}
In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression.
Syntax :
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
}
if(Boolean_expression){
//Executes when the Boolean expression is true }else{
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 {
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
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:
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 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.
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.
data member
method
constructor
block
class Student1{
int id;//data member (also instance variable)
String name;//data member(also 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.
class Student2{
int rollno;
String name;
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.
class Rectangle{
int length;
int width;
void calculateArea(){System.out.println(length*width);}
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
Output:55
45
By new keyword
By newInstance() method
By clone() method
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{
class Rectangle{
int length;
int width;
void calculateArea(){System.out.println(length*width);}
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.
In java, Method Overloading is not possible by changing the return type of the method.
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);}
}
}
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);}
}
}
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.
2. Parameterized constructor
Java Default Constructor
A constructor that have no parameter is known as default constructor.
class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
Output:
Bike is created
class Student3{
int id;
String name;
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.
class Student4{
int id;
String name;
111 Karan
222 Aryan
Output:
111 Karan 0
222 Aryan 25
3. block
4. nested class
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).
class Student8{
int rollno;
String name;
static String college ="ITS";
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);
}
}
}
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 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.
class Student9{
int rollno;
String name;
static String college = "ITS";
s1.display();
s2.display();
s3.display();
}
}
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
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.
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.
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.
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.
-1 Stack is Empty
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.
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.
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.
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.
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"
Tree:
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 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
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
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:
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.
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
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.
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.
classSuperclass-name
{
}
class Subclass-name extends Superclass-name
{
//methods and fields
}
Example:
class Employee
{
float salary=40000;
}
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
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.
A method that is declared as abstract and does not have implementation is known as abstract 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");}
}
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 Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike2 extends Vehicle{
void run(){System.out.println("Bike is running safely");}
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.
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
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");}
Whenever you create the instance of subclass, an instance of parent class is created implicitly i.e.
referred by super reference variable.
class Vehicle{
int speed=50;
}
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
class Vehicle{
Vehicle(){System.out.println("Vehicle is created");}
}
}
}
Output:Vehicle is created
Bike is created
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.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
1. import package.*;
2. import package.classname;
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.
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.
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
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
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:
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();}
}
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 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");
}
}
Exceptionthrown:java.lang.ArrayIndexOutOfBoundsException:3
Out of the block
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:
Wrong input
Advantages of Exceptions:
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.