Core Java FAQ

About volatile keyword?

volatile is used to indicate that a variable's value will be modified by different threads.

Declaring a volatile Java variable means:



  • The value of this variable will never be cached thread-locally: all reads and writes will go straight to "main memory";
  • Access to the variable acts as though it is enclosed in a synchronized block, synchronized on itself.

—————

What is Singleton ? and Double-checked locking ?

Need to follow : 
* private constructor , can't create object from outside of the class 
* Synchronized methods are used to ensure that the class is thread-safe. 
* This class cannot be subclassed because the constructor is private. This may or may 
not be a good thing depending on the resource being protected. 



//Single-checked locking 
//Thread 1 enters the synchronized block, and, before it can assign the singleton member variable, the thread is preempted. Subsequently, another thread can enter the if block. The second thread will wait for the first thread to finish, but we will still wind up with two distinct singleton instances 


public static Sequence getInstance() { 
if(singleton == null) { 
synchronized(Sequence.class) { 
singleton = new Sequence(); 


return singleton; 



//final and best solution is 

public class Sequence { 
private static Sequence singleton; 
private Sequence() 



//Double-checked locking 
//Imagine Thread 1 enters the synchronized block and is preempted.Subsequently, a second thread enters the if block.When Thread 1 exits the synchronized block, Thread 2 makes a second check to see if the singleton instance is still null.Since Thread 1 set the singleton member variable, Thread 2's second check will fail, and a second singleton will not be created. 


public static Sequence getInstance() { 
if(singleton == null) { 
synchronized(Sequence.class) { 
if(singleton == null) { 
singleton = new Sequence(); 



return singleton; 


—————

Sort an ArrayList?

 

*
  Sort elements of Java ArrayList Example
  This Java Example shows how to sort the elements of java ArrayList object using
  Collections.sort method.
*/
 
import java.util.ArrayList;
import java.util.Collections;
 
public class SortJavaArrayListExample {
 
  public static void main(String[] args) {
 
    //create an ArrayList object
    ArrayList arrayList = new ArrayList();
 
    //Add elements to Arraylist
    arrayList.add("1");
    arrayList.add("3");
    arrayList.add("5");
    arrayList.add("2");
    arrayList.add("4");
 
    /*
      To sort an ArrayList object, use Collection.sort method. This is a
      static method. It sorts an ArrayList object's elements into ascending order.
    */
    Collections.sort(arrayList);
 
    //display elements of ArrayList
    System.out.println("ArrayList elements after sorting in ascending order : ");
    for(int i=0; i<arrayList.size(); i++)
      System.out.println(arrayList.get(i));
 
  }
}
 
/*
Output would be
ArrayList elements after sorting in ascending order :
1
2
3
4
5
*/

—————

what is class loader in java ? explain the types of class loaders?

The Java Classloader is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine.Usually classes are only loaded on demand. The Java run time system does not need to know about files and file systems because of class loaders. Delegation is an important concept to understand when learning about class loaders.

 

the Java virtual machine contains two kinds of class loaders: a bootstrap class loaderand user-defined class loaders. The bootstrap class loader is a part of the virtual machine implementation, and user-defined class loaders are part of the running Java application. Classes loaded by different class loaders are placed into separate name spaces inside the Java virtual machine.
 
The class loader subsystem involves many other parts of the Java virtual machine and several classes from thejava.lang library. For example, user-defined class loaders are regular Java objects whose class descends from java.lang.ClassLoader. The methods of class ClassLoader allow Java applications to access the virtual machine's class loading machinery. Also, for every type a Java virtual machine loads, it creates an instance of class java.lang.Class to represent that type. Like all objects, user-defined class loaders and instances of class Class reside on the heap. Data for loaded types resides in the method area.
 
Detailed Opertion About Class Loaders -(Ref : Inside JVM Book)
 
Loading, Linking and Initialization
 
The class loader subsystem is responsible for more than just locating and importing the binary data for classes. It must also verify the correctness of imported classes, allocate and initialize memory for class variables, and assist in the resolution of symbolic references. These activities are performed in a strict order:
 
Loading: finding and importing the binary data for a type
Linking: performing verification, preparation, and (optionally) resolution
Verification: ensuring the correctness of the imported type
Preparation: allocating memory for class variables and initializing the memory to default values
Resolution: transforming symbolic references from the type into direct references.
Initialization: invoking Java code that initializes class variables to their proper starting values.
 
The Bootstrap Class Loader
 
Java virtual machine implementations must be able to recognize and load classes and interfaces stored in binary files that conform to the Java class file format. An implementation is free to recognize other binary forms besides class files, but it must recognize class files.
 
Every Java virtual machine implementation has a bootstrap class loader, which knows how to load trusted classes, including the classes of the Java API. The Java virtual machine specification doesn't define how the bootstrap loader should locate classes. That is another decision the specification leaves to implementation designers.
 
Given a fully qualified type name, the bootstrap class loader must in some way attempt to produce the data that defines the type. One common approach is demonstrated by the Java virtual machine implementation in Sun's 1.1 JDK on Windows98. This implementation searches a user-defined directory path stored in an environment variable named CLASSPATH. The bootstrap loader looks in each directory, in the order the directories appear in the CLASSPATH, until it finds a file with the appropriate name: the type's simple name plus ".class". Unless the type is part of the unnamed package, the bootstrap loader expects the file to be in a subdirectory of one the directories in the CLASSPATH. The path name of the subdirectory is built from the package name of the type. For example, if the bootstrap class loader is searching for class java.lang.Object, it will look for Object.class in the java\lang subdirectory of each CLASSPATH directory.
 
In 1.2, the bootstrap class loader of Sun's Java 2 SDK only looks in the directory in which the system classes (the class files of the Java API) were installed. The bootstrap class loader of the implementation of the Java virtual machine from Sun's Java 2 SDK does not look on the CLASSPATH. In Sun's Java 2 SDK virtual machine, searching the class path is the job of the system class loader, a user-defined class loader that is created automatically when the virtual machine starts up. 
 
User-Defined Class Loaders
 
Although user-defined class loaders themselves are part of the Java application, four of the methods in class ClassLoader are gateways into the Java virtual machine:
 
// Four of the methods declared in class java.lang.ClassLoader:
protected final Class defineClass(String name, byte data[],
    int offset, int length);
protected final Class defineClass(String name, byte data[],
    int offset, int length, ProtectionDomain protectionDomain);
protected final Class findSystemClass(String name);
protected final void resolveClass(Class c);
Any Java virtual machine implementation must take care to connect these methods of class ClassLoader to the internal class loader subsystem.
 
The two overloaded defineClass() methods accept a byte array, data[], as input. Starting at position offset in the array and continuing for length bytes, class ClassLoader expects binary data conforming to the Java class file format--binary data that represents a new type for the running application -- with the fully qualified name specified in name. The type is assigned to either a default protection domain, if the first version of defineClass() is used, or to the protection domain object referenced by the protectionDomain parameter. Every Java virtual machine implementation must make sure the defineClass() method of class ClassLoader can cause a new type to be imported into the method area.
 
The findSystemClass() method accepts a String representing a fully qualified name of a type. When a user-defined class loader invokes this method in version 1.0 and 1.1, it is requesting that the virtual machine attempt to load the named type via its bootstrap class loader. If the bootstrap class loader has already loaded or successfully loads the type, it returns a reference to the Class object representing the type. If it can't locate the binary data for the type, it throws ClassNotFoundException. In version 1.2, the findSystemClass() method attempts to load the requested type from the system class loader. Every Java virtual machine implementation must make sure the findSystemClass() method can invoke the bootstrap (if version 1.0 or 1.1) or system (if version 1.2 or later) class loader in this way.
 
The resolveClass() method accepts a reference to a Class instance. This method causes the type represented by the Class instance to be linked (if it hasn't already been linked). The defineClass() method, described previous, only takes care of loading. (See the previous section, "Loading, Linking, and Initialization" for definitions of these terms.) When defineClass() returns a Class instance, the binary file for the type has definitely been located and imported into the method area, but not necessarily linked and initialized. Java virtual machine implementations make sure the resolveClass() method of class ClassLoader can cause the class loader subsystem to perform linking.
 
The details of how a Java virtual machine performs class loading, linking, and initialization, with user- defined class loaders is given in Chapter 8, "The Linking Model."

 

 

 

 

—————

How many times "hello" will print in the following program ?

 

Question :
 
for(int i=0;i<5;++i)
{
    for(int j=0;j<5;++j)
     {  
        for(int k=i;k<5;k++)
        {
          System.out.println("Hello");
       }
    }
}

 

Answer:

Totally 75 times. ++i and i++, are both same in the for loop. The for loop operation i intialization,coditionchecking then exceute the block code, then increment or decrement. so inthis case if you put ++i or i++ means the value will be ramin same.

—————

What is the Output for the following program?

Question :

class Animal
{
     public void eat()
     {
       System.out.println("eat function from super class");
     }
 
     public void run()
    {
       System.out.println("run function from super class");
    }
    public void hunting()
    {
       System.out.println("hunting function from sub class");
    }
}//class animal ends here
 
class Lion extends Animal
{
  public void eat()
   {
     System.out.println("eat function from sub class");
   }
   public void hunting()
   {
    System.out.println("hunt function from sub class"); 
   }
}//class lion ends here
 
public class test
{
  public static void main(String[] args)
   {
     Animal obj=new Lion();
     obj.eat();
     obj.hunting();
  }
 
}
 
Answer :
 
eat function from sub class
hunt function from sub class
 
Both sub class method will print.

—————

What is the Output of the following program? (looks like previous one but not please check the code)

 

Question :
 
class Animal
{
    
     public void run()
    {
       System.out.println("run function from super class");
    }
    public void hunting()
    {
       System.out.println("hunting function from sub class");
    }
}//class animal ends here
 
class Lion extends Animal
{
  public void eat()
   {
     System.out.println("eat function from sub class");
   }
   public void hunting()
   {
    System.out.println("hunt function from sub class"); 
   }
}//class lion ends here
 
public class test
{
  public static void main(String[] args)
   {
     Animal obj=new Lion();
     obj.hunting();
     obj.eat();
  }
 
}
 
Answer :
The above program will through the following error :
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
The method eat() is undefined for the type Animal
 
in the above program Lion extends Animal and we are creating the object for Lion class And Assigning the object to Animal class. Any way Lion is subclass of Animal so it will accept.(you cant create like this Lion obj=new Animal();) and the eat method is not defined in Superclass so it will through an error in this case.
 

 

—————

Explain different way of using thread?

 The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help.

—————

What is the difference between sleep(), wait() and suspend()?

 

Thread.sleep() sends the current thread into the "Not Runnable" state for some amount of time. The thread keeps the monitors it has aquired -- i.e. if the thread is currently in a synchronized block or method no other thread can enter this block or method. If another thread calls t.interrupt() it will wake up the sleeping thread.
Note that sleep is a static method, which means that it always affects the current thread (the one that is executing the sleep method). A common mistake is to call t.sleep() where t is a different thread; even then, it is the current thread that will sleep, not the t thread.
 
t.suspend() is deprecated. Using it is possible to halt a thread other than the current thread. A suspended thread keeps all its monitors and since this state is not interruptable it is deadlock prone.
 
object.wait() sends the current thread into the "Not Runnable" state, like sleep(), but with a twist. Wait is called on a object, not a thread; we call this object the "lock object." Before lock.wait() is called, the current thread must synchronize on the lock object; wait() then releases this lock, and adds the thread to the "wait list" associated with the lock. Later, another thread can synchronize on the same lock object and call lock.notify(). This wakes up the original, waiting thread. Basically, wait()/notify() is like sleep()/interrupt(), only the active thread does not need a direct pointer to the sleeping thread, but only to the shared lock object.

—————

I want to create only one object for the class. What technique or design pattern you will use?

Make the class as single-ton class 

(Single ton is a one of the java design pattern)

singleton class steps to remember 

1.create private static global variable  and intialize as null (this variable is going to have the instance of the class)

2.make the constructor private 

3.create a static method (if thread based access means make this method as synchronized)

4. inside the static method check the global variable is null ,if null means  create a new instance nd assign to global variable and return the object.

5.if the global vriable not null means the object already reated so return the object

6. Override the clone method and throw the exception inside on it.

 

Example:

 

 

public class Singleton
{
   private static Singleton instance = null;
   private Singleton() {}
 
public static synchronized Singleton getInstance()
{
   if(instance!=null)
    {
       instance=new Singleton();
    }
    return instance;
}
 
@Override
 
protected Object clone() throws CloneNotSupportedException
{
   throw new CloneNotSupportedException("Clone is not allowed.");
}
 
Note :- There is two technque is availble in  single-ton class inrespect to thread
 
Single checked  Locking
Double checked Locking 
 
Search in the portal for single checked locking.
 
 
 
 
 

—————


Topic: Core Java FAQ

Date: 23/12/2023

By: 1

Subject: Mr.

1

—————

Date: 23/12/2023

By: 1

Subject: Mr.

1

—————

Date: 23/12/2023

By: 1

Subject: Mr.

1

—————

Date: 23/12/2023

By: 1

Subject: Mr.

1

—————

Date: 23/12/2023

By: 1

Subject: Mr.

1

—————

Date: 23/12/2023

By: 1

Subject: Mr.

1

—————

Date: 23/12/2023

By: 1

Subject: Mr.

1

—————

Date: 23/12/2023

By: 1

Subject: Mr.

1

—————

Date: 23/12/2023

By: 1

Subject: Mr.

1

—————

Date: 23/12/2023

By: 1

Subject: Mr.

1

—————