Final ,finally and finalize()?

Final:

  • 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.
  • public final String name = "foo"; //never change this value
  • 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
     }

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

Finally:

  • Finally blocks are followed by try or catch.finally blocks are complasary executable blocks.But finally is useful for more than just exception handling.
  •  it allows the programmer to avoid having cleanup code accidentally bypassed by a return,
     continue, or break,Closing streams, network connection, database connection. Putting cleanup  code in a finally block is always a good practice even when no exceptions are anticipated
  •  where finally doesn't execute e.g. returning value from finally block, calling System.exit from try block etc
  • finally block always execute, except in case of JVM dies i.e. calling System.exit() .

     lock.lock();
    try {
      //do stuff
    } catch (SomeException se) {
      //handle se
    } finally {
      lock.unlock(); //always executed, even if Exception or Error or se
      //here close the database connection and any return statements like that we have to write
    }

Finalize():

  • finalize() is a method which is present in Java.lang.Object class.
  •  Before an object is garbage collected, the garbage collector calls this finalize() of object.Any unreferncebefore destorying if that object having any connections with databse or anything..It will remove  the connections and it will call finalize() of object.It will destroy the object.
  • If you want to Explicitly call this garbage collector you can use System.gc() or Runtime.gc() objects are there from a long time the garbage collector will destroy that objects.
  • public void finalize() {
      //free resources (e.g. unallocate memory)
      super.finalize();
    }

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.

Select Menu