Vous êtes sur la page 1sur 40

Core Java Topics

Introduction
OOPs Concepts
Collections
Exception Handling

Introduction
What is Java?
Java is a programming language and a platform.
Java is a high level, robust, secured and object-oriented programming language.
Platform: Any hardware or software environment in which a program runs, is known as a platform. Since Java has its own runtime
environment (JRE) and API, it is called platform.
Java Example
Let's have a quick look at java programming example. A detailed description of hello java example is given in next page.
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
} }
Where it is used?
According to Sun, 3 billion devices run java. There are many devices where java is currently used. Some of them are as follows:

Desktop Applications such as acrobat reader, media player, antivirus etc.


Web Applications such as irctc.co.in, javatpoint.com etc.
Enterprise Applications such as banking applications.

Introduction

Mobile
Embedded System
Smart Card
Robotics
Games etc.

Features of Java
1.

simple
According to Sun, Java language is simple because:

syntax is based on C++ (so easier for programmers to learn it after C++).
removed many confusing and/or rarely-used features e.g., explicit pointers, operator overloading etc.
No need to remove unreferenced objects because there is Automatic Garbage Collection in java.

2.

Object-oriented

Object-oriented means we organize our software as a combination of different types of objects that incorporates both data
and behaviour.
Object-oriented programming(OOPs) is a methodology that simplify software development and maintenance by providing
some rules.

Basic concepts of OOPs are: 1.Object 2.Class 3.Inheritance 4.Polymorphism 5.Abstraction 6.Encapsulation

Introduction
Platform Independent
Java code can be run on multiple platforms e.g.Windows,Linux,Sun Solaris,Mac/OS
etc. Java code is compiled by the compiler and converted into bytecode.This
bytecode is a platform independent code because it can be run on multiple
platforms i.e. Write Once and Run Anywhere(WORA).

Secured
Java is secured because:

No explicit pointer
Programs run inside virtual machine sandbox.

Classloader- adds security by separating the package for the


classes of the local file system from those that are imported
from network sources.
Bytecode Verifier- checks the code fragments for illegal code
that can violate access right to objects.

Introduction
Security Manager- determines what resources a class can access such as reading and writing to the local disk.
These security are provided by java language
Robust
Robust simply means strong. Java uses strong memory management. There are lack of pointers that avoids security problem.
There is automatic garbage collection in java. There is exception handling and type checking mechanism in java. All these points
makes java robust.
Portable
We may carry the java bytecode to any platform.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at once by
defining multiple threads. The main advantage of multi-threading is that it shares the same memory. Threads are important for
multi-media, Web applications etc.

Java OOPs Concepts ::


Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a methodology or paradigm to
design a program using classes and objects. It simplifies the software development and maintenance by providing some concepts:

Object

Class

Inheritance

Polymorphism

Abstraction

Encapsulation
Object ::
Any entity that has state and behavior is known as an object.
For example: chair, pen, table, keyboard, bike etc. It can be physical and logical.
Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name, color, breed, hungry) and behavior
(barking, fetching, wagging tail). Bicycles also have state (current gear, current pedal cadence, current speed) and behavior (changing gear,
changing pedal cadence, applying brakes). Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of
object-oriented programming.
Software objects are conceptually similar to real-world objects: They too consist of state and related behavior. An object stores its state in fields
(variables in some programming languages) and exposes its behavior through methods (functions in some programming languages). Methods
operate on an object's internal state and serve as the primary mechanism for object-to-object communication. Hiding internal state and
requiring all interaction to be performed through an object's methods is known as data encapsulation a fundamental principle of objectoriented programming.

Java OOPs Concepts ::


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 ::
Collection of objects is called class. It is a logical entity.
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

Java OOPs Concepts ::


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

Java OOPs Concepts ::


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

Java OOPs Concepts ::


Rules for creating java constructor
There are basically two rules defined for the constructor.

Constructor name must be same as its class name


Constructor must have no explicit return type

Types of java constructors


There are two types of constructors:
1.
2.

Default constructor (no-arg constructor)


Parameterized constructor

Java Default Constructor


A constructor that have no parameter is known as default constructor.
Purpose Of Default Constructor
Default constructor provides the default values to the object like 0, null etc. depending on the type.
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.

Java OOPs Concepts ::


class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
Rule: If there is no constructor in a class, compiler automatically creates a default constructor.

Java OOPs Concepts ::


Inheritance ::
Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.
The idea behind inheritance in java is that you can create new classes that are built upon existing classes. When you inherit from
an existing class, you can reuse methods and fields of parent class, and you can add new methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-child relationship.
Why use inheritance in java
For Method Overriding (so runtime polymorphism can be achieved).
For Code Reusability.
Syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an existing class.
In the terminology of Java, a class that is inherited is called a super class. The new class is called a subclass.

Java OOPs Concepts ::


Types Of Inheritance In Java ::

Note: Multiple inheritance is not supported in java through class.This Problem is overcome through the Concept of Interface.
When a class extends multiple classes i.e. known as multiple inheritance.
Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B classes have same
method and you call it from child class object, there will be ambiguity to call method of A or B class.

Java OOPs Concepts ::


Since compile time errors are better than runtime errors, java renders compile time error if you inherit 2 classes. So whether you
have same method or different, there will be compile time error now.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were
Public Static void main(String args[]){
C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Output :: Compile Time Error

Java OOPs Concepts ::


Polymorphism ::
Polymorphism in java is a concept by which we can perform a single action by different ways. Polymorphism is derived from 2 greek
words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in java: compile time polymorphism and runtime polymorphism. We can perform
polymorphism in java by method overloading and method overriding.
If you overload static method in java, it is the example of compile time polymorphism. Here, we will focus on runtime polymorphism
in java.
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:

Java OOPs Concepts ::


class A{}
class B extends A{}
A a=new B();//upcasting
Real example of Java Runtime Polymorphism
Consider a scenario, Bank is a class that provides method to get the rate of interest. But, rate of interest may differ according to
banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7% and 9% rate of interest.
class Bank{int getRateOfInterest(){return 0;} }
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
class ICICI extends Bank{
int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}

Java OOPs Concepts ::


class Test3{
public static void main(String args[]){
Bank b1=new SBI();
Bank b2=new ICICI();
Bank b3=new AXIS();
System.out.println("SBI Rate of Interest: "+b1.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+b2.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+b3.getRateOfInterest());
}
}
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

Java OOPs Concepts ::


Encapsulation ::
Encapsulation in java is a process of wrapping code and data together into a single unit,
for example capsule i.e. mixed of several medicines.
We can create a fully encapsulated class in java by making all the data members of the class private. Now we can use setter and
getter methods to set and get the data in it.
The Java Bean class is the example of fully encapsulated class.
Advantage of Encapsulation in java
By providing only setter or getter method, you can make the class read-only or write-only.
It provides you the control over the data. Suppose you want to set the value of id i.e. greater than 100 only, you can write the logic
inside the setter method.
Simple example of encapsulation in java
Let's see the simple example of encapsulation that has only one field with its setter and getter methods.

Java OOPs Concepts ::


//save as Test.java

//save as Student.java

package com.javatpoint;

package com.javatpoint;

class Test{

public class Student{

public static void main(String[] args){

private String name;

Student s=new Student();

public String getName(){

s.setname("vijay");

return name;

System.out.println(s.getName());

public void setName(String name){

this.name=name
}
}

Compile By: javac -d . Test.java


Run By: java com.javatpoint.Test
Output: vijay

Java OOPs Concepts ::


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.
Ways to achieve Abstraction
There are two ways to achieve abstraction in java
1.
2.

Abstract class (0 to 100%)


Interface (100%)

Abstract Class ::
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).It needs to be extended and its method implemented. It cannot be instantiated.
Example abstract class
abstract class A{}
abstract method
A method that is declared as abstract and does not have implementation is known as abstract method.

Java OOPs Concepts ::


Example abstract method
abstract void printStatus();//no body and abstract
Example of abstract class that has abstract method
In this example, Bike the abstract class that contains only one abstract method run. It implementation is provided by the Honda
class.
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely..");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
} }
Output : running safely..

Java OOPs Concepts ::


Interface in Java ::
An interface in java is a blueprint of a class. It has static constants and abstract methods only.
The interface in java is a mechanism to achieve fully abstraction. There can be only abstract methods in the java interface not
method body. It is used to achieve fully abstraction and multiple inheritance in Java.
Java Interface also represents IS-A relationship.
It cannot be instantiated just like abstract class.
Why use Java interface?
There are mainly three reasons to use interface. They are given below.

It is used to achieve fully abstraction.


By interface, we can support the functionality of multiple inheritance.
It can be used to achieve loose coupling.

Note : The java compiler adds public and abstract keywords before the
interface method and public, static and final keywords before data members.
In other words, Interface fields are public, static and final bydefault,
and methods are public and abstract.

Java OOPs Concepts ::


Understanding relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends another interface but a class implements
an interface.
Simple example of Java interface
In this example, Printable interface have only one method,
its implementation is provided in the A class.
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
} }
Output:Hello

Java OOPs Concepts ::


Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as multiple inheritance.
interface Printable{ void print(); }
interface Showable{ void show(); }
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
A7 obj = new A7();
obj.print();
obj.show();
}
}
Output:Hello
Welcome

Collections ::
Collections in Java
Collections in java is a framework that provides an architecture to store and manipulate the group of objects.
All the operations that you perform on a data such as searching, sorting, insertion, manipulation, deletion etc. can be performed by
Java Collections.
Java Collection simply means a single unit of objects. Java Collection framework provides many interfaces (Set, List, Queue,
Deque etc.) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).
What is framework in java

provides readymade architecture.


represents set of classes and interface.
is optional.

What is Collection framework


Collection represents a single unit of objects i.e. a group.
Collection framework represents a unified architecture for storing and manipulating group of objects. It has:

Interfaces and its implementations i.e. classes


Algorithm

Collections ::
Hierarchy of Collection Framework
Let us see the hierarchy of collection framework.The java.util package
contains all the classes and interfaces for Collection framework.
Java ArrayList class
1 . Java ArrayList class uses a dynamic array for storing the elements.
It extends AbstractList class and implements List interface.
2 . Java ArrayList class can contain duplicate elements.
3 . Java ArrayList class maintains insertion order.
4 . Java ArrayList class is non synchronized.
5 . Java ArrayList allows random access because array works at the
index basis.
6 . In Java ArrayList class, manipulation is slow because a lot of
shifting needs to be occurred if any element is removed from the
array list.

Collections ::
Let's see the example of creating java collection.
ArrayList<String> al=new ArrayList<String>();//creating arraylist
Example of Java ArrayList class
import java.util.*;
class TestCollection1{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();//creating arraylist
al.add("Ravi");//adding object in arraylist
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator itr=al.iterator();//getting Iterator from arraylist to traverse elements
while(itr.hasNext()){
System.out.println(itr.next());
}}}
Output : Ravi
Vijay
Ravi
Ajay

Collections ::
Java Map Interface
A map contains values based on the key i.e. key and value pair.Each pair is known as an entry.Map contains only unique elements.
Commonly used methods of Map interface:

public Object put(object key,Object value): is used to insert an entry in this map.
public void putAll(Map map):is used to insert the specified map in this map.
public Object remove(object key):is used to delete an entry for the specified key.
public Object get(Object key):is used to return the value for the specified key.
public boolean containsKey(Object key):is used to search the specified key from this map.
public boolean containsValue(Object value):is used to search the specified value from this map.
public Set keySet():returns the Set view containing all the keys.
public Set entrySet():returns the Set view containing all the keys and values.

Entry
Entry is the subinterface of Map.So we will access it by Map.Entry name.It provides methods to get key and value.
Methods of Entry interface:
1 . public Object getKey(): is used to obtain key.

2 . public Object getValue():is used to obtain value.

Java HashMap class

1 . A HashMap contains values based on the key. It implements the Map interface and extends AbstractMap class.
2 . It contains only unique elements.

Collections ::

It may have one null key and multiple null values.


It maintains no order.

Example of HashMap class:


import java.util.*;
class TestCollection13{
public static void main(String args[]){
HashMap<Integer,String> hm=new HashMap<Integer,String>();
hm.put(100,"Amit");
hm.put(101,"Vijay");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
} }}
Output:102 Rahul
100 Amit
101 Vijay

Hierarchy of HashMap class:

Exceptions ::
Exception Handling in Java
Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL, Remote etc.
In java, exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the application. Exception normally disrupts the normal
flow of the application that is why we use exception handling. Let's take a scenario:
statement 1;
statement 2;
statement 3;//exception occurs
statement 4;
statement 5;
Suppose there is 5 statements in your program and there occurs an exception at statement 3, rest of the code will not be executed
i.e. statement 4 to 5 will not run. If we perform exception handling, rest of the statement will be executed. That is why we use
exception handling in java.

Exceptions ::
Types of Exception

Hierarchy of Java Exception classes

There are mainly two types of exceptions: checked and unchecked where
error is considered as unchecked exception. The sun microsystem
says there are three types of exceptions:
1 . Checked Exception
2 . Unchecked Exception
3 . Error
Difference between checked and unchecked exceptions
1) Checked Exception
The classes that extend Throwable class except RuntimeException and
Error are known as checked exceptions e.g.IOException, SQLException
etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime.

Exceptions ::
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Following are the Common scenarios where exceptions may occur
Scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException
Scenario where NullPointerException occurs
If we have null value in any variable, performing any operation by the variable occurs an NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException
Scenario where NumberFormatException occurs
The wrong formatting of any value, may occur NumberFormatException. Suppose I have a string variable that have characters,
converting this variable into digit will occur NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
Scenario where ArrayIndexOutOfBoundsException occurs
If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException as shown below:
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException

Exceptions ::
Java try block
Java try block is used to enclose the code that might throw an exception. It must be used within the method.
Java try block must be followed by either catch or finally block.
Syntax of java try-catch
try{
//code that may throw exception
}catch(Exception_class_Name ref){}
Syntax of try-finally block
try{
//code that may throw exception
}finally{}
Java catch block
Java catch block is used to handle the Exception. It must be used after the try block only.
You can use multiple catch block with a single try.

Exceptions ::
Problem without exception handling
Let's try to understand the problem if we don't use try-catch block.
public class Testtrycatch1{
public static void main(String args[]){
int data=50/0;//may throw exception
System.out.println("rest of the code...");
}
}
Output : Exception in thread main java.lang.ArithmeticException:/ by zero
As displayed in the above example, rest of the code is not executed (in such case, rest of the code... statement is not printed).
There can be 100 lines of code after exception. So all the code after exception will not be executed.

Exceptions ::
Solution by exception handling
Let's see the solution of above problem by java try-catch block.
public class Testtrycatch2{
public static void main(String args[]){
try{
int data=50/0;
}catch(ArithmeticException e){System.out.println(e);}
System.out.println("rest of the code...");
}
}
Output : Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
Now, as displayed in the above example, rest of the code is executed i.e. rest of the code... statement is printed.

Exceptions ::
Internal working of java try-catch block
The JVM firstly checks whether the exception is
handled or not. If exception is not handled, JVM
provides a default exception handler that performs
the following tasks:
1 . Prints out exception description.
2 . Prints the stack trace (Hierarchy of methods where
the exception occurred).
3 . Causes the program to terminate.
But if exception is handled by the application
programmer, normal flow of the application is
maintained i.e. rest of the code is executed.

Exceptions ::
Java finally block

Java finally block is a block that is used to execute important code such as
closing connection, stream etc.

Java finally block is always executed whether exception is handled or not.


Java finally block must be followed by try or catch block.

Note: If you don't handle exception, before terminating the program,JVM executes
finally block(if any).
Why use java finally?
Finally block in java can be used to put "cleanup" code such as closing a
file, closing connection etc.
Rule: For each try block there can be zero or more catch blocks, but only one
finally block.
Note: The finally block will not be executed if program exits(either by calling
System.exit() or by causing a fatal error that causes the process to abort).

Exceptions ::
Usage of Java finally : Let's see the different cases where java finally block can be used.
Case 1 : Let's see the java finally example where exception doesn't occur.
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}

Output:5
finally block is always executed
rest of the code...

Exceptions ::
Case 2 : Let's see the java finally example where exception occurs and not handled.
class TestFinallyBlock1{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output: finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero

Exceptions ::
Case 3 : Let's see the java finally example where exception occurs and handled.
public class TestFinallyBlock2{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output : Exception in thread main java.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code...