Friday, 7 October 2016

How does ConcurrentHashMap achieves its Scalability?

Question) How does ConcurrentHashMap achieve its Scalability?
Sometimes this multithreading + collection interview question is also asked as, the difference between ConcurrentHashMap and Hashtable in Java.

The problem with synchronized HashMap or Hashtable was that the whole Map is locked when a thread performs any operation with Map.


The java.util.ConcurrentHashMap class solves this problem by using the lock stripping technique, where the whole map is locked at different segments and only a particular segment is locked during the write operation, not the whole map.

The ConcurrentHashMap also achieves its scalability by allowing lock-free reads as read is a thread-safe operation.

Sunday, 24 January 2016

Java one year experience interview questions

1. Explain System.out.println()?
  • The system is a class That is present in java.lang package.
  • Out is a static final field (variable) of  Printstream class
    Println(): method of Printstream Class
  • Class System{
    public static final Printstream Out;
    }
  • Class Printstream{
    public void println(){}}

 2. What happens When System.out.println(null)?
  • Compilation Error -This is because you can pass an Object or a String or char[]. Since null can fit in both, the compiler doesn't know which method to use, leading to compile error.
  • Method Overloading:
        1.public void prinltln(String str) { }
        2.public void prinltln(char[] ch){ }
        3.public void prinltln(Object ch){ 
  • It seems the call System.out.print(null) is ambiguous to the compiler because print(null) here will find the two best specific matches i.e. print(String) and print(char[]). So the compiler is unable to determine which method to call here.
  • Compilation Error:
       System.out.println(null)
  • Compile Fine:
         System.out.println((String)null);//null
         System.out.println((char[])null);
         System.out.println((Object)null);//null
  • It's the compiler type-checking the parameters of the method call.
  • But here we need to know one more thing  System.out.println((char[])null); will compile fine but at run time will throw runtime exception.
 
3. What are the oops concepts in Java

Oops:
Oops, concepts are the rules which are supposed to be satisfied by a programing language in order to call that programing language as an Object Oriented Programing Language.


1. The 3 oops concepts are
    I. Encapsulation
    ii. Polymorphism
    iii. Inheritance

Encapsulation:

The process of binding the data with corresponding methods
  • The concept of binding the data along with its related and corresponding methods is known as Encapsulation.
  • The concept of restricting the availability of the data only to its related areas and related functions it is known as binding.
  • Because of binding, we can restrict the availability of data to the unrelated methods
  • So that unrelated functions cannot access the data 
  • Class is the base for encapsulation 

Polymorphism:

Defining multiple methods with the same name is known as Polymorphism.
  1. Static polymorphism (Compile time polymorphism ):
    The concept of defining multiple methods with the same name and with different parameters within the same class is known as static polymorphism.
  2. Dynamic polymorphism (Run time polymorphism ):
    The concept of defining multiple methods with the same name and with the same signature in super class and subclass is known as Dynamic polymorphism.

Inheritance:

Getting the properties from one class object to another class object is known as Inheritance.
  1. Multiple inheritance:
    Getting the properties from one class object to another class object level-wise with different priorities.
  2. Multilevel inheritance: Getting the properties from one class object to another class object with the same priority.

4. What are classes and Objects in Java?

Class
  • Class is a structure.
  • Binding the data with its related and corresponding functions.
  • Class is the base for encapsulation.
  • Class is a user-defined data type in Java.
  • The class will act as the base for encapsulation and implement the concept of encapsulation through objects.
  • Any Java application looks like a collection of classes but whereas a c- application looks like a collection of functions.
public class Example{

         //variable declaration
          int id;

      // methods
        public int getId() {
          return id;
         }

    public void setId(int id) {
        this.id = id;
    }

}

Object

  • An object is nothing but an instance (dynamic memory allocation) of a class.
  • The dynamic memory allocated at run time for the members [non-static variables] of the class is known as an object.

What is a Reference variable?

  • A reference variable is a variable that would be representing the address of the object.
  • Reference will act as a pointer and handler to the object.
  • Since the reference variable always points to an object.
  • In practice, we call the reference variable also an object.
  • We can create an object by using a new operator.
  • If we want to call any method inside the class we need an object
               Syntax: A obj= new A();

Example program:

      public class A {
         int a;
         public  void Print(){
            System.out.println("value of a="+a);
        }
        public static void main(String[] args) {
            A obj=new A();
           obj.print();
        }
}

Output: the value of a=0 
 
What Object Contains?
  • The object of any class contains only data.
  • Apart from the data object of a class would not contains anything else.
  • An object of a class would not contain any functionalities or logic.
  • Thus object of a class would be representing only data and not represent logic.

What is the state of the Object?

The data present inside the object of a class at that point in time is known as the state of the object.

What is the behavior of the object? 

  • The functionalities associated with the object => Behavior of the object.
     The state of the object changes from time to time depending on the functionalities that are executed on that object but whereas the behaviour of the object would not change.

Naming conventions for declaring a class:

  • The class name should be relevant.
  • Use UpperCamelCase for class names. //StudentDemoClass
  • For Methods names follow camelCase(); //getName();
  • Declare variables in the lowercase first letter. // int rollNumber
  • To declare final static variables means they will act like constants
    MIN_WIDTH=10;
    MAX_AGE=18;


5. Can you define an abstract class without any abstract methods?

  • Yes.
  • Declaring a class abstract without abstract methods means that you don't allow it to be instantiated on its own.
  • The abstract class used in Java signifies that you can't create an object of the class directly.
  • This will work:
    public abstract class abs {

    protected int s=0;

    public void display() {
        System.out.print("hello");
    }

    }

6. what are the differences between Final, finally Finalize ()?

Final:

  •  Any variable declare along with the final modifier then those variables treated as final variables
  • if we declare final variables along with static will become constants.
  • public final String name = "foo"; //never change this value
  • If you declare a method as final that method is also known as final methods. Final methods are not overridden. means we can't override that method in any way.
  • 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 a try or catch. finally, blocks are compulsory 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 a value from the finally block, calling System. exit from try block etc
  • finally, the block always executes, 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 that is present in Java.lang.Object class.
  •  Before an object is garbage collected, the garbage collector calls this finalize() of the object. Any unreferenced before destroying if that object has any connections with the database 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 for a long time the garbage collector will destroy that objects.
  • public void finalize() {
      //free resources (e.g. un allocate memory)
      super.finalize();
    }

7. What is Exception? difference between Exception and Error? and types of Exceptions?
  • Exceptions are the objects representing the logical errors that occur at run time and make 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
   
 8. Differences between method overloading and method overriding
  • Method overloading is nothing but defining multiple functionalities with the same name with
    different parameters are known as method overloading
  • while compile time itself we know which method is executed
  • Overloading gives better performance compared to overriding. The reason is that the
    binding of overridden methods is being done at runtime.
  • The argument list should be different while doing method overloading.
  • Polymorphism does not apply to overloading. The return type of overloaded methods should be the same.
    static binding is used for overloaded methods
public class A{
   public void show(int a){
      S.o.p("indhu");
   }
   public void show(int a,int b){
     S.o.p("sindhu");
   }

   public void show(float a){
     S.o.p("lavanya");
   }
   public static void main(String args[]){

       A a=new A();
       a.show(10);
      a.show(1,2);
     a.show(1.2);
   }
}
  • Method overriding is nothing but defining multiple functionalities with the same name with
    the same definition in superclass and subclass is known as Method overriding.
    While Run time only now which method is Executed.
  • Overriding gives slower performance compared to overloading. The reason is that the
    binding of overridden methods is being done at run time.
  • The argument list should be the same while doing method overriding.
    Polymorphism applies to overriding. 
  • In method overriding the return type of the overriding method can be different from overridden
    method.
  • Dynamic binding is used for method-overriding methods
public class A{
    public void display(){
      S.o.p("Indhu");
    }
}

Public class B extends A{
   public void display(){
     S.o.p("Sindhu");
   }
   public sttaic void main(String args[]){
      A a =new B();
      a.display();
   }
}


9. How to write custom Exceptions?
  • "MyException" is our exception class name. You can give any name of your choice.
    An important thing to be noted is our class extends the "Exception" class. This is all we need to do to make a custom-defined exception
    "Now we define a constructor of my class. This constructor takes a "String" argument. We call the super class' constructor(super class here is "Exception class") and pass this string to it. Not Java creates a new Exception with the message as in the string passed.

    •   public class MyException extends Exception

      {

          public MyException(String message)        

          { 

              super(message);       

          }     

      }
public class ExceptionDemo 
    {     
        public static void main(String args[]) throws Exception   
        {         
            ExceptionDemo exceptionDemo = new ExceptionDemo();        
            exceptionDemo.displayNumbers();   
        }     
        public void displayNumbers() throws MyException   
        {         
            for(int i=0;i<10;i++)      
            {     
               try{       
                System.out.print(i);          
                if(i==6)          
                {                 
                  throw new MyException("My ExceptionOccurred");             
                }
               catch(Exception e){
              System.out.println(e);
            }    
        }
    }


Output: 1 2 3 4 5 6  My exception occurred


10. What is serialization?

Serializable means transferable
  • The concept of transferring an object of a class from one location to another location is known as Serialization.
  • All the Java classes can be divided 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 it to byte stream:  serializing 
  • To receive an 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 is used to indicate that the variable should not be serialized
  • By default, all the variables in the object are converted to a 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.
 
11. What are abstract classes and interfaces?

Abstract Class:
  • An 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 that means public, private, or protected.
    In Abstract classes, variables will be anything( public, private, protected)
    For Abstract classes, we are not able to create objects directly. But Indirectly we can create objects using sub-class objects.
  • A Java abstract class should be extended using the keyword “extends”.
  • A Java abstract class can have instance methods that implement a default behaviour.
    If you know the requirements and partial implementation you can go for Abstract classes.
    an abstract class can extend from a class or from an abstract class.
  • An abstract class can extend only one class or one abstract class at a time. so Abstract classes can't support multiple inheritances.
  • In comparison with Java Interfaces, java Abstract classes are fast.
    If you add a new method to the abstract class, you can provide a 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 a main() method.

Interface :

  • The interface is nothing but some set of rules.
  • Interfaces have only Abstract methods.it is purely Achieve 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 objects directly or Indirectly but we can give sub-class object references to the interface.
  • Java interface should be implemented using the keyword “implements”. 
  • methods of a Java interface are implicitly abstract and cannot have implementations.
  • If u don't know any requirements and any implementation you can go for Interfaces.
  • The interface can extend only from an interface
  • The interface can extend any number of interfaces at a time. so interfaces can support multiple inheritance(syntactically not implementation of multiple inheritance).
  • In comparison with Java abstract classes, java interfaces are slow as it requires extra indirection.
  • if  you add a new method to the 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 the main method implementation.

 12. How to call garbage collectors explicitly?
  • When there are no more references to an object, the object is finalized and when the Garbage Collections starts these finalized objects get collected this will be done automatically by JVM.
  • But if we want to call  Garbage collection explicitly, There are methods
    1.System.gc();
    2.Runtime.gc(); 
How to prove it?
  • The java.lang.Runtime.freeMemory() method returns the amount of free memory in the Java Virtual Machine. Calling the gc method may result in increasing the value returned by free memory
Class GcDemo{

public static void main(String args[]){
System.out.println(Runtime.getRuntime().freeMemory());

    for (int i=0;i<= 100000;i++) {
    Double d = new Double(225);
    }
    System.out.println(Runtime.getRuntime().freeMemory());
    System.gc();
    System.out.println(Runtime.getRuntime().freeMemory());
}

13. Difference between ArrayList and vector?
  • Vector was introduced in the first version of Java. that's the reason only vector is a legacy class.
  • ArrayList was introduced in Java version1.2, as part of the Java collections framework.
  • Synchronization and Thread-Safe:
  • The vector is synchronized. Synchronization and thread-safe means at a time only one thread can access the code. In the Vector class, all the methods are synchronized. That's why the Vector object is already synchronized when it is created.
  • ArrayList is not synchronized.
How To Make ArrayList Synchronized:
  • We have a direct method in the collections class to make Arrraylist Synchronized.
  • List li=new ArrayList();
  • Collections.synchronized list(li);
Automatic Increase in Capacity:
  • A Vector defaults to doubling the size of its array.
  • ArrayList increases its size by 50%.
Performance:
  • Vector is slower than ArrayList.
  • ArrayList is faster than Vector.

14. Different ways to create objects in Java

   There are four different ways to create objects in Java:

  1.     Using new keyword
  2.     Using Class.forName():
  3.     Using clone():
  4.     Using Object Deserialization: 

Using new keyword:

This is the most common way to create an object in Java. Almost 99% of objects are created in this way.

MyObject object=new Object();

Using Class.forName():

  • If we know the name of the class & if it has a public default constructor we can create an object in this way.
  • Syntax:
  • Myobject obj=(MyObject) class.forName("object").newInstance();

Using clone():

  • The clone() can be used to create a copy of an existing object.
  • Syntax:
  • MyObject obj=new MyObject();
  • MyObject object=(MyObject )obj.clone();

Using Object Deserialization:

  • Object deserialization is nothing but creating an object from its serialized form.
  • Syntax:
  • objectInputStream istream=new objectInputStream(some data);
  • MyObject object=(MyObject) instream.readObject();

Java Program on creating an object using the new keyword:

    package com.instanceofjava;
    
    public class Employee
    {
    
          private int id;
          private String name;
    
          Employee(int id,String name){
          this.id=id;
          this.name=name;
    }
    
    public void display(){
          System.out.println(id+" "+name);
    }
    
    public static void  main (String args[]){

    Emploee e=new Employee(1,"Indhu");
    Employee e1=new Employee(2,"Sindhu");
    
    e.display();
    e1.display();
    
    }
    }

 Output:

    Indhu
    Sindhu

Java Program on creating objects using the clone() method:

    package com.instanceofjava;
    
    public class Empcloneable implements Cloneable {
    
      int a;
      String name;
    
    Empcloneable(int a,String name){
    
     this.a=a;
     this.name=name;
    
    }
    
     public Empcloneable clone() throws CloneNotSupportedException{
    
      return (Empcloneable) super.clone();
    
     }
    
    public static void main(String[] args) {

    Empcloneable e=new Empcloneable(2,"Indhu");
    System.out.println(e.name);
    
    try {

    Empcloneable b=e.clone();
    System.out.println(b.name);
    
    } catch (CloneNotSupportedException e1) {
    
     e1.printStackTrace();
    }
    
    }
    }

 Output:

    Indhu
    Indhu

Java Program on creating an object using Deserialization

    package com.instanceofjava;
    import java.io.*;
    public class Files
    {
    
    public static void main(String [] args)
    {
    
     Employee e = null;
    
    try
    {
    
    FileInputStream fileIn = new FileInputStream("/E/employee.txt");
    ObjectInputStream in = new ObjectInputStream(fileIn);
    
    e = (Employee) in.readObject();
    in.close();
    fileIn.close();
    
    }catch(IOException i)
    {
    i.printStackTrace();
    return;
    
    }catch(ClassNotFoundException c)
    {
    System.out.println("Employee class not found");
    c.printStackTrace();
    return;
    }
    
    System.out.println("Deserialized Employee...");
    System.out.println("Name: " + e.name);
    
    }
    
    }


 Output:

    Name: Indhu

Java Program on creating an object using class.forName();


    package com.instanceofjava;
    public class Sample{
    
    public static void main(String args[]){
    
    try {
    
     Class s= Class.forName("com.instanceofjava.Sample");
     Sample obj=(Sample) s.newInstance(); 
     System.out.println(obj.hashcode());
    
     } catch (Exception e) {
    
      e.printStackTrace();
    
    }
    
    }
    
    }

 Output:

    2007759836

15. Why Java does not support multiple inheritance?

Inheritance:

  • The concept of getting properties of one class object to another class object is known as inheritance.
  • Here properties mean variable and methods.

Types of Inheritance:

  1. Multiple inheritance.
  2. Multilevel inheritance.

 Multiple inheritance:

  • The concept of Getting the properties from multiple class objects to sub-class objects with the same priorities is known as multiple inheritances.
  • Java Doesn't Support multiple Inheritance.

Diamond problem:

  • In multiple inheritances there is every chance of multiple properties of multiple objects with the same name available to the sub-class object with the same priorities leads to ambiguity. 
  1. //Multiple inheritance program
  2. Class A{
  3. }
  4. Class B extends A{
  5. public void show(){
  6. }
  7. }
  8. Class C extends A{
  9. public void show(){
  10. }
  11. }
  12. Class D extends B, C{  // not supported by Java leads to a syntax error.
  13. }
  •  We have two classes B and c which are inheriting A class properties.
  • Here Class D inherits B class and C class So properties present in those classes will be available in Java.
  • But both classes are at the same level with the same priority.
  • If we want to use the show() method that leads to ambiguity
  • This is called the diamond problem.
  • Because of multiple inheritances, there is a chance of the root object getting created more than once.
  • Always the root object i.e. object of the object class has to be created only once.
  • Because of above mentioned reasons multiple inheritance would not be supported by Java.
  • Thus in Java, a class can not extend more than one class simultaneously. At most, a class can extend to only one class.
So these are the reasons that Java does not support multiple inheritances. Even though having this many reasons some people say that we also get some doubts when we are using interfaces. lets me clear this one also. our immediate question should be.

Is Java supports multiple inheritances using interfaces?

  • Before that, we need to know about interfaces.
  • Interfaces having fully abstract functionality.
  • This means methods in interfaces by default public abstract methods so we need to implement these methods in classes that are extending this interface.
   
  1. /Multiple inheritance program
  2. interface A{
  3. public void  show();
  4. }
  5. interface B{
  6. public void  display();
  7. }
  8. Class C Implements A,B{
  9. }

  • Here it seems we are achieving multiple inheritances by using interfaces. but we are not.
  • Syntactically it seems to be multiple inheritance but the actual implementation of multiple inheritance is not there. how can I say that? let me clear

Difference between interfaces and inheritance: in multiple inheritances

  • Inheritance means getting the properties from one class object to another class object.
  • This means if any class extends another class then the superclass methods can be used in sub-classes happily.
  • But in interfaces the methods in interfaces are fully abstract so we need to provide functionality in our extended class and use it .seems both are opposites right? yes.
  • That is the reason we can say interfaces only supports syntactical multiple inheritance which is not the implementation of multiple inheritance.
So finally java supports only the syntax of multiple inheritance and does not supports the implementation of multiple inheritance.
Inheritance is like debit and interface is like credit but the interface has its own importance in other concepts like server-side programming

16. Difference between throw and throws in Java

Throw: 

  • 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) 
  1. //Custom exception
  2. package com.instanceofjavaforus;
  3. public class InvalidAgeException extends Exception {
  4.  InvaidAgeException(String msg){
  5.  super(msg);
  6.  }
  7. }
     

  1. package com.instanceofjavaforus;
  2. public class ThrowDemo {
  3. public boolean isValidForVote(int age){
  4.  try{
  5.    if(age<18){
  6.   throw new InvalidAgeException ("Invalid age for voting");
  7. }
  8.  }catch(Exception e){
  9.  System.out.println(e);
  10.  }
  11.   return false;
  12.  }
  13.   public static void main(String agrs[]){
  14.  ThrowDemo obj= new ThrowDemo();
  15.    obj.isValidForVote(17);
  16.   }
  17. }
We can throw predefined exceptions also

  1. package com.instanceofjavaforus;
  2. public class ThrowDemo {
  3. public void method(){
  4.  try{
  5.   
  6.   throw new NullPointerException("Invalid age for voting");
  7. }
  8.  }catch(Exception e){
  9.  System.out.println(e);
  10.  }
  11.  }
  12.   public static void main(String agrs[]){
  13.  ThrowDemo obj= new ThrowDemo();
  14.    obj.method();
  15.   }
  16. }
Like this, we can throw checked exceptions and unchecked exceptions also. But the throw keyword is mainly used to throw used defined exceptions/custom exceptions.

Throws:

  • The functionality of the throws keyword is only to explicitly mention that the method is proven to transfer un handled exceptions to the calling place.
  1. package com.instanceofjavaforus;
  2. public class ThrowSDemo {
  3. public void method(int a,int b) Throws ArithmeticException{
  4.  
  5. inc c= a/b;
  6.  }
  7.   public static void main(String agrs[]){
  8.  ThrowDemo obj= new ThrowDemo();
  9.    try{
  10. obj.method(1,0);
  11. }catch(Exception e){
  12.  System.out.println(e);
  13. }
  14.   }
  15. }

 Uses of throws keyword:

  • Using the throws keyword we can explicitly provide the information about unhand-led exceptions of the method to the end user, Java compiler, or JVM.
  • Using the throws keyword we can avoid try-catch with respect to the statements which are proven to generate checked exceptions.
  • It is highly recommended not to avoid try-catch with respect to the statements which are proven to generate exceptions in the main method using the throws keyword to the main() method.

17. What is the difference between equals() method and == operator

== operator:

  •  == operator used to compare objects references.
  • used to compare data of primitive data types
  • if we are comparing two objects using the "==" operator if the reference of both is the same then it will return true otherwise returns false.
  • obj1==obj2;
  • If we are comparing primitive data type variables then it compares data of those two variables
  • Ex: int a=12; int b=12; if(a==b) returns true

Comparing primitive values: 

  1. package com.instanceofjava;
  2.  
  3. Class Demo{ 
  4.  
  5. public static void main (String args[]) {

  6. int a=12;
  7. int b=13;
  8. int c=12;
  9.  
  10. if(a==b){
  11. System.out.println("a and b are equal");
  12.  
  13. if(b==c){
  14. System.out.println("a and b are equal");
  15.  
  16. }
  17. }

Comparing Objects:

  1. package com.instanceofjavaforus;
  2.  
  3. Class Demo{ 
  4.  
  5. public static void main (String args[]) {
  6.  
  7.  Demo obj1= new Demo();
  8. Demo obj2=new Demo();
  9.  
  10. if(obj1==obj2){ // here both are two different objects(memory allocation wise);
  11.  
  12. System.out.println("obj1 and obj2 are referring to same address");
  13.  
  14. }else{
  15.  
  16.  System.out.println("obj1 and obj2 are referring to different address");
  17.  
  18. }
  19. }
  20. }

Comparing String Objects:

  1. package com.instanceofjava;
  2.  
  3. Class ComapreStringDemo{ 
  4.  
  5. public static void main (String args[]) {
  6.  
  7.  String s1=new String("abc");
  8. String s2=new String("abc");
  9.  
  10. if(s1==s2){ // here it returns false
  11. System.out.println("obj1 and obj2 are referring to same address");
  12. }else{
  13.  System.out.println("obj1 and obj2 are referring to different address");
  14.  
  15. }
  16. }

Comparing String Literals:

  •  If we declared two string literals with the same data then those will refer to the same reference.
  • means if we create any object using a string literal then it will be created in the string pool 
  • then if we are created another literal with the same data then it won't create another object but rather refers to the same object in the pool.
  • so if compare two string literals with the same data using the "==" operator then it returns true.
  1. package com.instanceofjava;
  2.  
  3. Class ComapreStringLiteralDemo{ 
  4.  
  5. public static void main (String args[]) {
  6.  
  7.  String s1="abc";
  8. String s2="abc";
  9.  
  10. if(s1==s2){ // here it returns true
  11.  
  12. System.out.println("obj1 and obj2 are referring to same address");
  13.  
  14. }else{
  15.  
  16.  System.out.println("obj1 and obj2 are referring to different address");
  17.  
  18. }
  19. }
  20. }

equals() method:

  • equals() method defined in the "object" class.
  • By default equals methods behave like the "==" operator when comparing objects.
  • By default equals() method compares references of objects.
  • But All wrapper classes and String classes override this equals method and comparing data.
  • This means in the String class and in All wrapper classes this equals() method is overridden to compare data of those class objects. 

Comparing String Objects:

  1. package com.instanceofjava;
  2.  
  3. Class ComapreStringDemo{ 
  4.  
  5. public static void main (String args[]) {
  6.  
  7.       String s1=new String("ABC");
  8.       String s2=new String("ABC");
  9.  
  10.       if(s1.equals(s2)){ // here it returns true
  11.  
  12.                System.out.println(" data present in obj1 and obj2 is same");
  13.  
  14.      }else{
  15.  
  16.                System.out.println(" data present in obj1 and obj2 is different");
  17.  
  18.      }
  19. }
  20. }

 Comparing custom objects:

  • If we want to compare custom objects means our own objects' data.
  • Then we need to override the equals method and in that, we need to compare data.

  1. package com.instanceofjavaforus;

    public class Patient {
       String name;
       Patient(String name){
           this.name=name;
       }
          public boolean equals(Patient obj){
          
           if(this.name.equals(obj)){
               return true;
           }else{
               return false;
           }
       }
           public static void main(){
            Patient obj1= new Patient("sam");
           
            Patient obj2= new Patient("sam");
           
            System.out.println(obj1.equals(obj2)); //returns true
        }
           
    }

Important points to note about equals() and "==":

  • "==" used to compare data for primitive data type variables .
  • "==" operator compares objects references
  • By default equals() method behaves like the "==" operator for objects means comparing objects references.
  • All wrapper classes and String class override this equals() method and compares data of two objects. if the same returns true.(whenever we override the equals() method we need to override the hashcode() method too and if two objects on an equal method same then both should have the same hashcode).
  • And in the equals() method in string class logic includes the "==" operator too.

  1. package com.instanceofjava;
  2.  
  3. public boolean equals(Object anObject) {
  4.    if (this == anObject) {
  5.       return true;
  6.      }
  7.  if (anObject instanceof String) {
  8.      String anotherString = (String) anObject;
  9.      int n = value.length;
  10.     if (n == anotherString.value.length) {
  11.     char v1[] = value;
  12.      char v2[] = anotherString.value;
  13.   int i = 0;
  14. while (n-- != 0) {
  15.    if (v1[i] != v2[i])
  16.            return false;
  17.            i++;
  18.        }
  19.          return true;
  20.         }
  21.     }
  22.        return false;
  23.   }

18. Differences between HashMap and Hash-table

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 to Hashtable and provides better scalability than Hashtable in Java. Synchronized means only one thread can modify a hash table at one point in 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 the 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 throws 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 with the 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:

import java.util.HashMap;

import java.util.Hashtable;

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

 

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



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

 }
}