Friday, 1 August 2014

Array Vs ArrayList

  1. ArrayList is internally backed by Array in Java. So the performance for getting and replacing the elements based on index is similar for both the Arrays and ArrayLists. But, If ArrayList filled completely, then it performs resizing, this automatic resizing slow down the performance. But this performance issue is minimal.
  2. Array is a fixed length data structure, where as ArrayList is variable length collection.
  3. It is possible to store both primitive and objects in array. But ArrayList not support primitive types.



                                                             Home

Check whether thread holds lock on object ?

Thread class provides a 'holdsLock' method which returns true if the current thread holds the monitor lock on the specified object, else false.

public static boolean holdsLock(Object obj)

Returns true if the current thread holds the monitor lock on the specified object else false.

public class Employee{

}

public class HoldLockEx implements Runnable{
    Employee emp;
    
    HoldLockEx(Employee emp){
        this.emp = emp;
    }
    
    public void unHoldLock(){
        System.out.println("Is thread holds the lock " + Thread.holdsLock(emp));
    }
    
    public void holdLock(){
        synchronized(emp){
            System.out.println("Is thread holds the lock " + Thread.holdsLock(emp));
        }
    }
    
    @Override
    public void run(){
        unHoldLock();
        holdLock();
    }
    
    public static void main(String args[]){
        HoldLockEx task = new HoldLockEx(new Employee());
        Thread t1 = new Thread(task);
        t1.start();
    }
}

Output
Is thread holds the lock false
Is thread holds the lock true





                                                             Home

Is overriding of static methods possible in Java ?

No, static methods can not be overridden, but they can hide the parent static methods. Because static methods are class level methods, so access to static methods resolved at compile time, where as instance methods are object level, so access to them resolved at run time.

Example
public class SuperClass {
    static void print(){
       System.out.println("In static super class print method");
    }
    
    void show(){
        System.out.println("In super class show method");
    }
}

public class SubClass extends SuperClass{
     static void print(){
       System.out.println("In static sub class print method");
    }
    
     @Override
    void show(){
        System.out.println("In sub class show method");
    }
    
    public static void main(String args[]){
        SuperClass obj = new SubClass();
        
        obj.show();
        obj.print();
    }
}


Output
In sub class show method
In static super class print method

Observe output, 'obj.show' calls subclass show method, where as 'obj.print' calls super class print method.



                                                             Home

NoClassDefFoundError Vs ClassNotFoundException

1. ClassNotFoundException is a checked exception, where as NoClassDefFoundError is of type Error.

2. NoClassDefFoundError is a linkage error, thrown when a class 'A' has dependency on other class 'B', latter compilation of class A, class B changed or removed.

ClassNotFoundException may thrown while application tries to use the below methods.

     Class.forName(java.lang.String),
     ClassLoader.findSystemClass(java.lang.String),  
     ClassLoader.loadClass(java.lang.String, boolean)

Related Links


                                                             Home

NoClassDefFoundError

NoClassDefFoundError is a linkage error, thrown when a class 'A' has dependency on other class 'B', latter compilation of class A, class B changed or removed.

Lets take an example

public class B {
    
}

public class A {
    public static void main(String args[]){
        B b = new B();
    }
}

Compile both the files, before running class 'A' remove 'B.class'.

While running the class A, below error thrown.

Exception in thread "main" java.lang.NoClassDefFoundError: B
        at A.main(A.java:3)
Caused by: java.lang.ClassNotFoundException: B
        at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        ... 1 more




                                                             Home

ClassNotFoundException

ClassNotFoundException is a checked exception, thrown when an Application tries to load the class using name, but the class doesn't exist.

public class LoadClass {
    public static void main(String args[]) throws ClassNotFoundException{
        Class.forName("NoClass");
    }
}

Since there is no class named 'NoClass', so ClassNotFoundException thrown.

Exception in thread "main" java.lang.ClassNotFoundException: NoClass
 at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
 at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
 at java.security.AccessController.doPrivileged(Native Method)
 at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
 at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
 at java.lang.Class.forName0(Native Method)
 at java.lang.Class.forName(Class.java:259)
 at LoadClass.main(LoadClass.java:3)
Java Result: 1

ClassNotFoundException may thrown while application tries to use the below methods.
      Class.forName(java.lang.String),
      ClassLoader.findSystemClass(java.lang.String), 
      ClassLoader.loadClass(java.lang.String, boolean)




                                                             Home

convert List to Integer array in Java

By using toArray method, List<Integer> is converted to integer array.

public <T> T[] toArray(T[] a)
Returns an array containing all of the elements in this list in proper sequence, the run time type of the returned array is that of the specified array.

Example
import java.util.*;

class LinkedListSpecificArray{
 public static void main(String args[]){
  LinkedList<Integer> myList;
  myList = new LinkedList<> ();
  
  Integer myArray[];
  Integer retArray[];
  
  /* Add Elements to myList */
  myList.add(10);
  myList.add(123);
  myList.add(321);
  myList.add(456);
  
  int size = myList.size();
  
  myArray = new Integer[size];
  retArray = new Integer[size];
  
  retArray = myList.toArray(myArray);
  
  System.out.println("Elements in the list are");
  System.out.println(myList);
  
  System.out.println("Elements in myArray are");
  for(int i: myArray)
   System.out.print(i +" ");
   
  System.out.println("\nElements in the retArray are");
  for(int i: retArray)
   System.out.print(i +" "); 
 }
}

Output
Elements in the list are
[10, 123, 321, 456]
Elements in myArray are
10 123 321 456
Elements in the retArray are
10 123 321 456





                                                             Home