Differences between HashMap and Hash-table



Java provides different types of Map implementations, two of the most commonly used being HashMap and Hashtable. Both of these classes implement the Map< interface and store key-value pairs, but they differ significantly in terms of synchronization, performance, and usage. In this article, we will explore the differences in detail.

Introduction

Map in Java is a collection of key-value pairs where each key is unique. Both HashMap and Hashtable use a hashing mechanism to store and retrieve data efficiently. However, they have different characteristics that make them suitable for different use cases.

Key Differences Between HashMap and Hashtable

The table below provides a summary of the key differences between HashMap and Hashtable:

FeatureHashMapHashtable
SynchronizationNot synchronized (not thread-safe)Synchronized (thread-safe)
PerformanceFaster (no overhead of synchronization)Slower (due to synchronization)
Null Keys/ValuesAllows one null key and multiple null valuesDoes not allow null keys or values
IterationUses Iterator (fail-fast)Uses Enumerator (legacy, not fail-safe)
InheritanceExtends AbstractMapExtends Dictionary (legacy class)
Thread SafetyRequires external synchronization for multi-threadingThread-safe, but may impact performance
Use CaseBest for non-threaded applicationsSuitable for multi-threaded environments


Differences between HashMap and Hash-table
  •  Synchronization or Thread Safe : One of the major differences between HashMap and Hashtable is that HashMap is non-synchronized whereas Hashtable is synchronized, which means Hashtable is thread-safe and can be shared between multiple threads but HashMap cannot be shared between multiple threads without proper synchronization. Java 5 introduced ConcurrentHashMap which is an alternative of Hashtable and provides better scalability than Hashtable in Java.Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.
  • Null keys and null values : The HashMap class is roughly equivalent to Hashtable, except that it permits nulls. (HashMap permits one null key and multiple null values.
    Hashtable doesn't permit any sort of nulls (key or values).).
  • Iterating the values: The third significant difference between HashMap vs Hashtable is that Iterator in the HashMap is a fail-fast iterator while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator’s own remove() method. But this is not a guaranteed behavior and will be done by JVM on best effort. This is also an important difference between Enumeration and Iterator in Java.
  • Default Capacity: 
  •  Hashmap: static final int DEFAULT_INITIAL_CAPACITY =16  static final float DEFAULT_LOAD_FACTOR = 0.75f;  
  • Hashtable:  static final int DEFAULT_INITIAL_CAPACITY = 11;   static final float DEFAULT_LOAD_FACTOR = 0.75f;
  • HashMap does not guarantee that the order of the map will remain constant over time.
HashMap can be synchronized by using Collections.synchronizedMap() method
Map m = Collections.synchronizedMap(hashMap);
Example:

Here is example of a C program that uses a for loop to calculate the sum of 'n' numbers:

  1. import java.util.HashMap;
  2. import java.util.Hashtable;

  3. public class HashMapHashtableExample {
  4.    
  5.     public static void main(String[] args) {      

  6.  

  7.         Hashtable<String,String> hashtableobj = new Hashtable<String, String>();
  8.         hashtableobj.put("name", "ramu");
  9.         hashtableobj.put("petname", "ram");
  10.         System.out.println("Hashtable object output :"+ hashtableobj);



  11.         HashMap hashmapobj = new HashMap();
  12.         hashmapobj.put("name", "ramu"); 
  13.         hashmapobj.put("pertname", "ram");
  14.         System.out.println("HashMap object output :"+hashmapobj);

  15.  }
  16. }




hashmap vs hashtable

HashMap in Java

What is HashMap?

HashMap<K, V> is a part of the java.util package and implements the Map<K, V> interface. It stores key-value pairs using a hashing mechanism, which allows efficient insertion, deletion, and retrieval operations.

Characteristics of HashMap

  • Not synchronized: Multiple threads can access a HashMap concurrently, but this can lead to inconsistent data if modifications occur.

  • Allows null values and a single null key.

  • Unordered: Does not guarantee any specific order of keys.

  • Performance: Fast for most operations since there is no synchronization overhead.

Hashtable in Java

 What is Hashtable?

Hashtable<K, V> is a legacy class from Java 1.0 that implements the Map<K, V> interface and extends the Dictionary<K, V> class. It stores key-value pairs using hashing and provides built-in synchronization, making it thread-safe.

Characteristics of Hashtable

  • Synchronized: All methods are thread-safe but can lead to performance bottlenecks.

  • Does not allow null keys or values.

  • Unordered: Similar to HashMap, it does not guarantee the order of keys.

  • Uses Enumerator instead of Iterator (legacy mechanism, should be avoided).


Java String

String:

  • Series of characters is known as string.
  • String is final class in java.
    public final class String
    extends Object
    implements Serializable, Comparable<String>, CharSequence.
  • We can create a String object in two ways.
  • 1. By using new operator
        String str= new String("Java");
    2.By using String literal.
       String str= "Java".

Difference between string object and string literal  :


     
  • Whenever you call new() in JAVA it create an object in heap.
  • String literals will go into String Constant Pool.
  • For objects JVM used String constant pool which is for efficient memory management in java. Unlike other Java Objects, instead of managing String object on heap area, they introduced String constant pool. One of important characteristic of String constant pool is that it does not create same String object if there is already String constant in the pool.
Example program:

  1. public class StringCreationDemo {     
  2.                                                                                   
  3. public static void main (String args[]) {
  4.  
  5.     String str1 = "Hello"; 
  6.     String str2 = "Hello";
  7.  
  8.     System.out.println("str1 and str2 : literal");   
  9.     System.out.println("str1 == str2 is " + (str1 == str2)); 
  10.  
  11.     String str3 = new String("Hello"); 
  12.     String str4 = new String("Hello");
  13.  
  14.     System.out.println("str3 and str4 : new operator");   
  15.     System.out.println(" str3 == str4 is " + (str3 == str4)); 
  16.  
  17.     String str5 = "Hel"+ "lo"; 
  18.     String str6 = "He" + "llo";
  19.  
  20.     System.out.println("str5 and str6 : expression.");   
  21.     System.out.println("    str5 == str6 is " + (str5 == str6)); 
  22.  
  23.   }
  24. }  

                                                                      
      
Output:


  1. str1 and str2 : literal 
  2. str1 == str2 is true. 
  3. str3 and str4 : new operator str3 == str4 is false. 
  4. str5 and str6 : expression 
  5. str5 == str6 is true.

       
                                                                                                                                        

String is immutable. What exactly is the meaning??

  • String is immutable means that you cannot change the object itself, but you can change the reference to the object. 
  •  String a="a";
           a = "str";
  • When you called a = "str", you are actually changing the reference of a to a new object created by the String literal "str". 
  • Changing an object means to use its methods to change one of its fields (or the fields are public and not final, so that they can be updated from outside without accessing them via methods)
  • String str="smiley";
    str=str+"bird";
    here new String object will be created.

Why Strings are immutable in java?

  • Security: Parameters are typically represented as String in network connections, database connection urls, usernames/passwords etc. If it were mutable, these parameters could be easily changed.
  • Synchronization and concurrency: making String immutable automatically makes them thread safe thereby solving the synchronization issues.
  • Caching: when compiler optimizes your String objects, it sees that if two objects have same value (a="test", and b="test") and thus you need only one string object (for both a and b, these two will point to the same object).
  • Class loading: String is used as arguments for class loading. If mutable, it could result in wrong class being loaded (because mutable objects change their state).

How to prove Strings are immutable?


  1. package com.instanceofjava;
  2.  
  3. public class StringImmutableDemo {
  4. public static void main(String[] args) {
  5.  
  6. String s1="Java";
  7. String s2 = "Rocks!";
  8.  
  9. System.out.println("The hascode of s1 = " + s1.hashCode());
  10. System.out.println("The hascode of s2 = " + s2.hashCode());
  11.  
  12. s1=s1 + s2;
  13.  
  14. System.out.println("The hascode [AFTER] s1 is changed = " + s1.hashCode());
  15.  
  16. }

 Output:


  1. The hascode of s1 = 2301506
  2. The hascode of s2 = -1841810349
  3. The hascode [AFTER] s1 is changed = 1248336149

String class constructors:

  • String class has 8 important constructors.

1.String():

  • Creates empty string object.

2.String(String value):

  •  Creates String objects with the string value

3.String(StringBuffer sb):

  • Creates String object with the given StringBuffer object.

4. String(StringBuilder sb):

  • Creates String object with the given StringBuilder object.

5.String(char[] ch):

  •  Creates String object  with the given array values.

6.String(char ch, int offset, int count):

  • Creates String object with the given array values start with offset by including with the  given count of characters.

7.String(byte[] b):

  • Creates String object with the given byte array values.

8.String(byte[] b, int offset, int count):

  • Creates String object with the given byte array values starts with offset by including with the given count of bytes

String methods:

1.isEmpty():

  • This method used to check whether String is empty or not

 2.length():

  • To find the length of given string.
  1. package com.instanceofjavaforus;
  2. public Class StringMethodsDemo{
  3. public static void main (String args[]) {
  4. String str="";
  5. System.out.println(str.isEmpty()) ;
  6. System.out.println(str.length());
  7. }
  8. }
  9. Output: 
  10. true
  11. 0

3.equals();


  • To compare two strings

4.compareTo():

  • To Compare two string objects lexicographically, means after comparison method should return difference between string content

5.compareToIgnoreCase():

  • To Compare two string objects lexicographically, means after comparison method should return difference between string content ignores case.
  1. package com.instanceofjavaforus;
  2. public Class StringMethodsDemo{
  3. public static void main (String args[]) {
  4. String str1="abc";
  5. String str2= new String("abc")
  6. System.out.println(str1.equals(str2)) ;
  7. String str3="a";
  8. String str4="A";
  9. System.out.println(str3.compareTo(str4)) ;
  10. String str5="a";
  11. String str6="A";
  12. System.ot.println(str3.compareToIgnoreCase(str4)) ;

  13. }
  14. }
  15. Output: 
  16. true
  17. 32
  18. 0

6.7. startsWith(), endsWith():

  • To check whether the string starts with specified string or ends with specified string
  1. package com.instanceofjavaforus;
  2. public Class StringMethodsDemo{

  3. public static void main (String args[]) {

  4. String str1="Java programming language";
  5. System.out.println(str1.startsWith("Java"));
  6. System.out.println(str1.endsWith("java"));

  7. }
  8. }
  9. Output: 
  10. true
  11. false

8.charAt(int index);

  • To find character at given index
  1. package com.instanceofjavaforus;
  2. public Class StringMethodsDemo{

  3. public static void main (String args[]) {

  4. String str1="Java";
  5. System.out.println(str1.charAt(1));
  6. System.out.println(str1.charAt(3));

  7. }
  8. }
  9. Output: 
  10. a
  11. a

9.indexOf(char ch):

  • Returns first occurrence of  given character
  1. package com.instanceofjavaforus;
  2. public Class StringMethodsDemo{

  3. public static void main (String args[]) {

  4. String str1="Java";
  5. System.out.println(str1.indexOf("J"));
  6. System.out.println(str1.indexOf("B"));

  7. }
  8. }
  9. Output: 
  10. 0
  11. -1



Collections in Java

Collections:
  • Collections in java is a framework that provides an architecture to store and display the data.
  • Collections API provides interfaces and classes.
  • Using Collection we can perform operations like searching,sorting,insertion,deletion,manipulation.
  • Collections is nothing but group of different type of objects together as a single entity is also known as Collections.
  • Collections are growable Nature.
  • Collection Framework having Interfaces like Set,List,Map.Every Interface having classes.
Why Collection Came?
  • Arrays are fixed in size.we can't increase size of Arrays.that's y only collections came.collections having growable nature.we can increase size.
Set Interface:
  • A set is a collection that having only unique elements.Duplicate won't be there.
  • Set having no index.
  • Set allows only one null value.
  • Set having classes like :
  • HashSet
  • LinkedHashMap
  • TreeSet

HashSet:

HashSet having only unique elements.
HashSet having no Order.
HashSet allows only one null value.

Program for HashSet:

package.com.instanceofjava;
import.java.util.HashSet;

public class A{
public static void main(String args[]){

HashSet hashset=new HashSet();

hashset.add("Indhu");
hashset.add("Indhu");
hashset.add("Sindhu");
hashset.add("swathi");
hashset.add(null);
hashset.add(null);
hashset.add("Lavs");
Iterator it=hashset.iterator();
while(it.hasNext()){
System.out.println(it.next);
}
}
}
Output:

Indhu
null
Lavs
Sindhu
swathi

LinkedHashSet :
  • LinkedHashSet allows only unique elements.
  • LinkedHashSet allows Insertion order.
  • LinkedHashSet allows only one null value.

Program for LinkedHashSet;

package.com.instanceofjava;
import.java.util.LinkedHashSet;

public class testSet{
public static void main(String args[]){

LinkedHashSet linkedHashSet=new LinkedHashSet();

linkedHashSet.add("Indhu');
linkedHashSet.add("Indhu");
linkedHashSet.add("Sindhu");
linkedHashSet.add("Bindhu");
linkedHashSet.add(null);
linkedHashSet.add(null);

Iterator it=linkedHashSet.iterator();
while(it.hasNext()){
System.out.println(it.next);
}
}
}

Output:
Indhu
Sindhu
Bindhu
null


TreeSet:
  • TreeSet Allows only Unique elements.
  • Treeset having sorted order
  • TreeSet doesn't allow  any null value.
Program for TreeSet:

package.com.instanceofjava;
import.java.util.TreeSet;

Public class testSet2{

public static void main(String args[]){
TreeSet treeSet=new treeSet();
treeSet.add("Sindhu");
treeSet.add("Sindhu");
treeSet.add("Indhu");
treeSet.add("Bindhu');
Iterator it=treeSet.iterator();
while(it.hasNext()){
System.out.println(it.next);
}
}
}

Output:
Bindhu
Indhu
Sindhu
  • in Set interface if you want to add elements you can use add() method.
  • If you want to remove you can use remove() method.



















Synchronization

What is Synchronization?

  • The concept of avoiding multiple threads entering into a common functionality of common object  simultaneously is known as thread safe or synchronization.
  • we implement the concept of thread safe  using synchronized keyword. The functionality of Synchronized keyword is to avoid multiple threads entering into a common functionality of common functionality. 

Why do we need Synchronization? 

  • The "Synchronized" keywords prevents concurrent access to a block of code or object by multiple Threads.  
  • Synchronized keyword in Java provides locking, which ensures mutual exclusive access of shared resource and prevent data race.
  • To prevent consistency problem and thread interference .

Producer consumer problem:

Common   class:

package com.instanceofjavaforus;

public class Common {
    int x;
   
    boolean flag=true;
    //if flag is true producer thread has to produce
    // if flag is false consumer thread has to produce

    synchronized public void produce(int i){
       
        if(flag){
           
            x=i;
            System.out.println("producer thread has produced "+i);
            flag=false;
            notify();
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }      
        }
     }
   

    synchronized public int consume(){
        if(flag){
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
           
        }
        flag=true;
        notify();
        return x;
    }
   
}

package com.instanceofjavaforus;

public class ProducerThread extends Thread {
    Common c;
   
    ProducerThread(Common c){
        this.c=c;
    }
   
    public void run(){
        int i=0;
        while(true){
           
            i++;
            c.produce(i);
           
           
            try {
                Thread.sleep(600);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
        } 
    } 
}

ConsumerThread:

package com.instanceofjavaforus;

public class ConsumerThread extends Thread {
   
    Common c;
   
    ConsumerThread(Common c){
        this.c=c;
    }
   
    public void run(){
       
        while(true){
           
            int x=c.consume();
            System.out.println("Consumer consumes"+x);
            try {
                Thread.sleep(600);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
        } 
    }
}

ProducerConsumerTest:

package com.instanceofjavaforus;

public class ProducerConsumerTest {
   
    public static void main(String args[]){
        Common c= new Common();
        ProducerThread pt=new ProducerThread(c);
        ConsumerThread ct= new ConsumerThread(c);
        pt.start();
        ct.start();
    }
}

Output:

producer thread has produced 1
Consumer consumed 1
producer thread has produced 2
Consumer consumed 2
producer thread has produced 3
Consumer consumed 3
producer thread has produced 4
Consumer consumed 4
producer thread has produced 5
Consumer consumed 5
producer thread has produced 6
Consumer consumed 6


Serialization

  • Serializable means transferable
  • The concept of transferring object of a class from one location to another location is known as Serialization.
  • All the java classes can be devided into two. 
  • The classes whose objects can be transferable .  Objects of all classes  that are implementing serializable  interface can be transferable
  • The classes whose objects can't be transferable .  Objects of all classes  which are not implementing serializable  interface cant be transferable .
  • To transfer the object need to convert to byte stream :  serializing 
  • To receive Object need to convert from byte stream to Object : deserializing
  • Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object.
  •  

public class Student implements java.io.Serializable
{
   public String name;
   public int number ;
   
}
 
import java.io.*;

public class SerializeDemo
{
   public static void main(String [] args)
   {
      Employee e = new Employee();
      e.name = "harsha";
       
     e.number = 101;
      try
      {
         FileOutputStream fileOut =
         new FileOutputStream("/tmp/student.ser");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
         out.writeObject(e);
         out.close();
         fileOut.close();
         System.out.printf("Serialized data is saved in /tmp/employee.ser");
      }catch(IOException i)
      {
          i.printStackTrace();
      }
   }
} 
     Deserialization
     
import java.io.*;
public class DeserializeDemo
{
   public static void main(String [] args)
   {
      Student e = null;
      try
      {
         FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
         ObjectInputStream in = new ObjectInputStream(fileIn);
         e = (Student ) in.readObject();
         in.close();
         fileIn.close();
      }catch(IOException i)
      {
         i.printStackTrace();
         return;
      }catch(ClassNotFoundException c)
      {
         System.out.println("student class not found");
         c.printStackTrace();
         return;
      }
      System.out.println("Deserialized student...");
      System.out.println("Name: " + e.name);

      System.out.println("Number: " + e.number);
By default all the variables in the object is converted to persistent state. In some cases, you may want to avoid persisting some variables because you don’t have the necessity to transfer across the network. So, you can declare those variables as transient. - See more at: http://www.javabeat.net/what-is-transient-keyword-in-java/#sthash.TMBQ2f9K.dpuf

    }
} 
 

Transient Keyword: 

  • The keyword transient in Java used to indicate that the variable should not be serialized
  • By default all the variables in the object is converted to persistent state. In some cases, you may want to avoid persisting some variables because you don’t have the necessity to transfer across the network. So, you can declare those variables as transient.
  • If the variable is declared as transient, then it will not be persisted. It is the main purpose of the transient keyword.

Multithreading In Java

Thread:
  • Thread is nothing but functionality which could be executed simultaneously with the other part of the program based on the concept of one with another.
  • But where as method or a function which would be executed hierarchically with the other part of the program.
  • It is termed as a ‘lightweight process’, since it is similar to a real process but executes within the context of a process and shares the same resources allotted to the process by the kernel
What is a process? difference between process and thread? 
  • A program which is under execution can be called as process.
  • Some operating systems use the term ‘task‘ to refer to a program that is being executed.
  • Thread is part of the process.
  • Both processes and threads are independent sequences of execution. The typical difference is that threads (of the same process) run in a shared memory space, while processes run in separate memory spaces.
  • I'm not sure what "hardware" vs "software" threads might be referring to. Threads are an operating environment feature, rather than a CPU feature (though the CPU typically has operations that make threads efficient).
  • Threads share the address space of the process that created it; processes have their own address space.
  • Threads have direct access to the data segment of its process; processes have their own copy of the data segment of the parent process.
  • Threads can directly communicate with other threads of its process; processes must use interprocess communication to communicate with sibling processes.
  • Threads have almost no overhead; processes have considerable overhead.
  • A process is a collection of code, memory, data and other resources. A thread is a sequence of code that is executed within the scope of the process. You can (usually) have multiple threads executing concurrently within the same process.
How many ways to create thread in java: 
  • we can create threads in two ways.
  • 1. Extending Thread class.
    2. Implementing Runnable interface.

Extending Thread class:

package com.instanceofjavaforus;

public class ExtendsThread extends Thread {
 
    public void run(){
    System.out.println("thread is running...");
    }
    public static void main(String args[]){
    ExtendsThread t1=new ExtendsThread();
    t1.start();
     }
  
}

Implementing Runnable interface

package com.instanceofjavaforus;

public class RunnabelDemo  implements Runnable{
  
    public void run(){ 
    System.out.println("thread is running..."); 
    } 
    public static void main(String args[]){ 
    RunnabelDemo m1=new RunnabelDemo(); 
    Thread t1 =new Thread(m1); 
    t1.start(); 
     } 
   
}



Best Practices for Multithreading
  1. Avoid Deadlocks: Ensure that threads acquire locks in a consistent order.
  2. Use Thread Pools: Prefer ExecutorService over manually creating threads.
  3. Minimize Synchronization: Synchronize only the critical sections of your code.
  4. Use Volatile Variables: Use the volatile keyword for variables that are accessed by multiple threads.
  5. Handle Exceptions: Always handle exceptions in threads to avoid unexpected crashes.
  • java is a powerhouse application that allows programmers to make their applications be able to do multiple tasks at once in essence.Multithreading means that software to the server, is fast; but it also takes advantage of my computer and yours too for performance.It also means that Multithreading allows you to have parallelism between different programs on one machine: from where they run off more than one CPU core all the time--thus increasing efficiency even further than just using performance of one set plus productivity when running together concurrently.In this blog post, we’ll look at how to create threads and use the new C++ STD standard mutex with graphicsexamples. We will also discuss good programming practice; indeed it is essential for multithreading operations in today’s fast-paced development environment.

 What are Threads?

Multithreading allows the execution of multiple threads by a CPU (or the threading of a single core in multi-core processors), and it provides the possibility to interrupt any running thread at all times whether this one happens to be currently blocked for some reason on I/O operations or not at all A thread  is smallest unit that can be independently run within a process. In Java, multithreading allows you to run many threads at the same time--and indeed most of them might finish quickly so they won't need any additional waiting for message processing or other future work which is not needed now that so many jobs have been done.

 Why Multithreading?

Performance Improved: Because tasks are split into several threads you can take better advantage of the resources inside your CPU.
Responsiveness: Even if your program performs a lot of time-consuming tasks, it remains responsive.
Data Sharing: Threads share information and states--so this makes it easier to exchange data between them.
Background Tasks: Multithreading allows you to execute non-blocking operations in the main thread.


Exception Handling

Exception:

  • Exceptions are the objects representing the logical errors that occur at run time and makes JVM enters into the state of  "ambiguity".
  • The objects which are automatically created by the JVM for representing these run time errors are known as Exceptions.
  • An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.
  •  few of the subclasses of Error
  • AnnotationFormatError - Thrown when the annotation parser attempts to read an annotation from a class file and determines that the annotation is malformed.
  • AssertionError - Thrown to indicate that an assertion has failed.
  • LinkageError - Subclasses of LinkageError indicate that a class has some dependency on another class; however, the latter class has incompatibly changed after the compilation of the former class.
  • VirtualMachineError - Thrown to indicate that the Java Virtual Machine is broken or has run out of resources necessary for it to continue operating.
  •  There are really three important subcategories of Throwable:
  • Error - Something severe enough has gone wrong the most applications should crash rather than try to handle the problem,
  • Unchecked Exception (aka RuntimeException) - Very often a programming error such as a NullPointerException or an illegal argument. Applications can sometimes handle or recover from this Throwable category -- or at least catch it at the Thread's run() method, log the complaint, and continue running.
  • Checked Exception (aka Everything else) - Applications are expected to be able to catch and meaningfully do something with the rest, such as FileNotFoundException and TimeoutException.
 instanceofjavaforus.blogspot.com


try block:

  • The functionality of try keyword is to identify an exception object.
  • And catch that exception object and transfer the control along with the identified exception object to the catch block by suspending the execution of the try block.
  • All the statements which are proven to generate exceptions should be place in try block.

catch Block:

  •  The functionality of catch block is to receive the exception class object that has been send by the "try".
  • And catch that exception class object and assigns that exception class object to the reference of the corresponding exception class defined in the catch block.
  • And handle the exception that has been identified by "try".
  • "try"  block identifies an exception and catch block handles the identified exception.

finally block:

  • finally blocks are the blocks which are going to get executed compulsorily irrespective of exceptions.
  • finally blocks are optional blocks.

 throw keyword:

  • throw keyword used to throw user defined exceptions.(we can throw predefined exception too)
  • If we are having our own validations in our code we can use this throw keyword.
  • For Ex: BookNotFoundException, InvalidAgeException (user defined)

 throws keyword:

  •  The functionality of throws keyword is only to explicitly to mention that the method is proven transfer un handled exceptions to the calling place.
  1. package com.instanceofjavaforus;
  2. public class ExcpetionDemo {
  3.  public static void main(String agrs[]){
  4.   try{
  5. //statements
  6. }catch(Exception e){
  7.  System.out.println(e);
  8. }
  9. finally(){
  10. //compulsorily executable statements 
  11. }
  12.   }
  13. }

 

Unreachable Blocks:

  • The block of statements to which the control would never reach under any case can be called as unreachable blocks.
  • Unreachable blocks are not supported by java.
  • Thus catch block mentioned with the reference of  "Exception" class should and must be alwats last catch block. Because Exception is super class of all exceptions.

  1. package com.instanceofjavaforus;
  2. public class ExcpetionDemo {
  3. public static void main(String agrs[]){
  4. try{
  5. //statements
  6. }catch(Exception e){
  7. System.out.println(e);
  8. }
  9. catch(ArithmeticException e)//unreachable block.. not supported by java. leads to error
  10. System.out.println(e);
  11.  }
  12. }

This Keyword and Instanceof operator

  • The functionality of "this" keyword is only to explicitly point the object because of which the function is currently under execution.
  • The object because of which the function is currently under execution is known as current object.
  • Thus the functionality of this is to point current class object.
This used to call constructor from another constructor:

Class Tdemo{

Tdemo(){
this(6);
System.out.println("Default constructor")
}
Tdemo(int a ){
this(1,2);
System.out.println("One argument constructor")
}

Tdemo(int a, int b ){

System.out.println("Two argument constructor")
}

public static void main(String args[]){

Tdemo obj= new Tdemo();

}
}

Output:
Two argument constructor
One argument constructor
Default constructor

Program for without this keyword:

class Student{
int id;
String name;
String college;
Student(int id,String name,String college){
id=id;
name=name;
college=college;
}
void display(){
System.out.println(id+" "+name+" "+college);
}
public satic void main(String args[]){
Student s=new Student(1,"Indhu","TRML");
Student s1=new Student(2,"Sindhu","TRML");
s.display();
s1.sispaly();

}

Output:
0 null null
0 null null

in the above program parameters and instance variables are same.so we by using this keyword we can solve this problem.

solution of the above problem using This keyword:

class Student{
int id;
String name;
String college;
Student(int id,String name,String college){
this.id=id;
this.name=name;
this.college=college;
}
void display(){
System.out.println(id+" "+name+" "+college);
}
public satic void main(String args[]){
Student s=new Student(1,"Indhu","TRML");
Student s1=new Student(2,"Sindhu","TRML");
s.display();
s1.sispaly();

}

Output:
1 Indhu TRML
2 Sindhu TRML

Important points of this keyword:

  • This is final variable in java.so we can't assign values to the final.
  • this=new Emp(); //Can't assign values to this.it will return compilation error.

Limitation of this keyword:

  • "this" is applicable to only to the non static methods because static methods are not executed by any object

Instance of operator:

  • Instance of operator is used to test whether that object is belong to that class type or not.
  • If that object belongs to that class it returns true .otherwise it returns false.
  • Instance of operator is also known as comparison operator.because it compares with the instance of type.
Program to instance of operator:

public class Employee{
public static void main(String args[]){
Employee e =new Employee();
System.out.println(e instanceof Employee);//true
}
}

Output:true

public class A{
public void show(){
System.out.println("This is class A");
}

public class B extends A{
public void show(){
System.out.println("This is class B");
}
public static void main(String args[]){
A a=new A();
System.out.println(a instanceof A);
System.out.println(a instanceof B);
}
}

Output:
true
false

Abstract Class and Interfaces

Abstract Class:
  • Abstract class means hiding the implementation  and showing the function definition to the user is known as Abstract class
  • Abstract classes having Abstract methods and normal methods (non abstract methods) will be there.
  • Abstract classes having methods will be anything means public ,private,protected.
    In Abstract classes  variables will be anything( public, private, protected)
    For Abstract classes we not able to create object directly.But Indirectily we can create object using sub calss object.
  • A Java abstract class should be extended using keyword “extends”.
  • A Java abstract class can have instance methods that implements a default behavior.
    If you know requirement and partially implementation you can go for Abstract classes.
    abstract  class  can extend from a class or from an abstract class.
  • Abstract class can extend only one class or one abstract class at a time. soAbstract classes can't support multiple inheritance.
  • In comparison with java Interfaces, java Abstract classes are fast.
    If you add new method to abstract class, you can provide default implementation of it. So you don’t need to change your current code.
  • Abstract classes can have constructors .
    We can run an abstract class if it has main() method.

Example Program:


abstract class A{

abstract void display();
public void show(){
S.o.p("Indhu");
}

Public class B extends A{
void display();
}
Abstract class C Extends B{
//Escaping Here
}
public static void main(String args()){
A a= new B();
a.display();
a.show();

}

Interface :

  • Interface nothing but some set of rules.
  • Interfaces having only Abstract methods.it is purely Achive Abstraction.
  • In Interfaces by default the methods will be public abstract methods.
  • In Interfaces by default the variables will be static final .
  • For Interfaces we can't create object directly or Indirectly but we can give sub class object reference to interface .
  • Java interface should be implemented using keyword “implements”. 
  • methods of a Java interface are implicitly abstract and cannot have implementations.
  • If u don't know Any requirement and any implementation you can go for Interfaces.
  • Interface can extend only from an interface
  • Interface can extend any number of interfaces at a time. so interfaces can support multiple inheritance(syntactical not implementation of multiple inheritance).
  • In comparison with java abstract classes, java interfaces are slow as it requires extra indirection.
  • if  you add new method to interface, you have to change the classes which are implementing that interface
  • Interface having no constructor.
    we can’t run an interface because they can’t have main method implementation.
Example Program:

public interface Payment
{
    void makePayment();//by default it is a abstract method
}
public class PayPal implements Payment
{
    public void makePayment()
    {
        //some logic for paypal payment
        //like paypal uses username and password for payment
    }
}
public class CreditCard implements Payment
{
    public void makePayment()
    {
        //some logic for CreditCard payment
        //like CreditCard uses card number, date of expiry etc...
    }

Final Keyword

    Final variables:

    • Any variable declare along with final modifier then those variables treated as final variable.
    •  if we declare final variables along with static will became constants.
    • while declaring itself we need to assign these final variables.
    • final int a;
    Example program: 

       class finalvariabledemo{

       final int a=10;
        public static void main(String args[]){
        finalvariabledemo obj= new finalvariabledemo();
        //obj.a=24;  this will rise compile time error
    }
    }

    Output:

    Compile time Error.

    Final Method:

    • If you declare method as final that method also known as final methods.Final methods are not overridden.means we can't overridden that method in anyway.
    • public final void add(){
       }
       public class A{
       void add(){
       //Can't override
       }
       }

    Final Class:

    • If you declare class is final that class is also known as final classes.Final classes are not extended.means we can't extends that class in anyway.
    • public final class indhu{
       }
       public class classNotAllowed extends indhu {...} //not allowed

    Static Keyword

    Static Keyword
    • Static means class level. static can be applied to variable method and block.
    • static variables , static methods , static blocks.
    • makes your program memory efficient 
    Static variables 
    • 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.
    Example program:

    package com.instanceofjava.snippets.basics;


    public class StaticDemo {

        // static variable - the same on all instances of a class
        static int X = 10;

        // non static variable
        int Y = 5;
       
        public static void main(String[] args) {




      StaticDemo o1= new StaticDemo();

      StaticDemo o2= new StaticDemo();


      System.out.println("o1.X = " + o1.X + " o1.Y = " + o1.Y);

      System.out.println("o2.X = " + o2.X + " o2.Y = " + o2.Y);

     

      instance1.X = 15;

      instance1.Y = 10;

     

      System.out.println("After updating X value to 15 and Y value to 10 from o1:");

      System.out.println("o1.X = " + o1.X + " o1.Y = " + o1.Y);

      System.out.println("o2.X = " + o2.X + " o2.Y = " + o2.Y);

        }

    }

    Output:

    instance1.X = 10 o1.Y = 5
    instance2.X = 10 o2.Y = 5
    After updating X value to 15 and Y value to 10 from o1:
    instance1.X = 15 o1.Y = 10
    instance2.X = 15 o2.Y = 5 



    Static methods:
    • Static method belongs to the class rather than object of a class
    • Static methods can be called without creating an object of class
    • Static method can access static data member and can change the value of static data
    • You can define as many static methods. These methods are independent, except that they may refer to each other through calls
    • Any static method can call any other static method in the same file or any static method in a Java library like Math
    Example program:

    1. class Student{  
    2.      int rollno;  
    3.      String name;  
    4.      static String college = "SBIT";  
    5.        
    6.      static void change(){  
    7.      college = "SBCE";  
    8.      }  
    9.   
    10.      Student9(int r, String n){  
    11.      rollno = r;  
    12.      name = n;  
    13.      }  
    14.   
    15.      void show(){
    16.      System.out.println(rollno+" "+name+" "+college);
    17.    }  
    18.   
    19.     public static void main(String args[]){  
    20.     Student.change();  
    21.   
    22.     Student s1 = new Student (37,"indhu");  
    23.     Student s2 = new Student (38,"sindhu");  
    24.     Student s3 = new Student (39,"swathi");  
    25.   
    26.     s1.show();  
    27.     s2.show();  
    28.     s3.show();  
    29.     }  

    OutPut:

    indhu SBCE
    sindu SBCE
    swathi SBCE

    Static Blocks:
    • Whenever class loads these static blocks will be exeuted.
    • Static blocks are also called Static initialization blocks . A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword.
    • we can use static blocks to assign static variables.
    Example program:
    class staticBlockDemo{

        static int i;

        int j;

        

        // start of static block

        static {

            i = 20;

            System.out.println("static block called ");

        }

        // end of static block

    }

    class Main {

        public static void main(String args[]) {

            // Although we don't have an object of staticBlockDemo, static block is

            // called because i is being accessed in following statement.

            System.out.println(staticBlockDemo.i);

        }

    }



          Output:

    static block called

    20



     
    Select Menu