Core Java Topics PDF
Core Java Topics PDF
Core Java Topics PDF
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:
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.
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.
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.
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
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.
//save as Student.java
package com.javatpoint;
package com.javatpoint;
class Test{
s.setname("vijay");
return name;
System.out.println(s.getName());
this.name=name
}
}
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.
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.
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
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.
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 ::
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
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.
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...