Frequently asked Question in java


Is Servlet Threadsafe
Servlets are not thread safe. If you want to make it Servlet as Thread safe, you can implement SingleThreadInterface which is a blank Interface there is no methods  (this is not recommend method, because it could slow the performance of your page) the SingleThreadModel interface Deprecated from Servlets 2.4 or you can synchronize methods by using synchronized keyword. Don’t synchronize service or doget or dopost.

Is Struts Thread Safe?

Struts are not thread-safe but thread-dependent. The response to a request is handled by light weight Action object, rather than an individual servlet. Struts instantiates each Action class once and allows other request to thread through the original object. This core strategy conserves resources and provides the best possible throughput. A properly-designed application will exploit this further by routing related operations through a single action.

Difference between java & javax

There’s no difference at all between "import java..." and "import javax..." it's just that some of the Java API packages are named java.something, and others are named javax.something. Originally, the "javax" names were supposed to represent "extensions" to the Java core, but in a controversial decision, Swing was released in a javax package, and since then the conceptual difference has been minimal.

If you’re overriding the method equals () of an object, which other method you might also consider?
hashCode().

What is actually the difference between a Nested Class, a Member Class, an Inner Class, a Local Class, and an Anonymous Class?
* nested (top-level) class:
A class defined as static inside another class. Instances can live
independent of instances of the enclosing class. It's a normal class,
just with a longer name.
* member (inner) class:
A class defined as non-static inside another class. Instances are
dependent on an instance of the enclosing class.
* inner class:
A member, local or anonymous class
* local (inner) class:
Defined inside a code block, only visible inside that code block
* anonymous (inner) class:
A local class without a name.

Why oracle Type 4 driver is named as oracle thin driver?
Oracle provides a Type 4 JDBC driver, referred to as the Oracle “thin” driver. This driver includes its own implementation of a TCP/IP version of Oracle’s Net8 written entirely in Java, so it is platform independent, can be downloaded to a browser at runtime, and does not require any Oracle software on the client side. This driver requires a TCP/IP listener on the server side, and the client connection string uses the TCP/IP port address, not the TNSNAMES entry for the database name.

What are Locale and resourcebundle classes ?
They are from java.util
Locale loc = (Locale)ses1.getAttribute("lang");
AA =ResourceBundle.getBundle("ArcLabels",loc).getString("AA");

How to convert String to Number in java program?
String numString = “1000″;
int id=Integer.valueOf(numString).intValue();

In System.out.println(), what is System, out and println?
System is a predefined final class, out is a PrintStream object and println is a built-in overloaded method in the out object.

How does Java handle integer overflows and underflows?
 It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.

Why cant static methods be overridden?
Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object.  A static method in a super class can be shadowed by another static method in a subclass, as long as the original method was not declared final However, you can’t override a static method with a non-static method. In other words, you can’t change a static method into an instance method in a subclass. Non-static variables take on unique values with each object instance.

What is the difference between the boolean & operator and the && operator?
If an expression involving the boolean & operator is evaluated, both operands are evaluated, whereas the && operator is a short cut operator. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. If the first operand evaluates to false, the evaluation of the second operand is skipped.

What do you understand by numeric promotion?
The Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integral and floating-point operations may take place. In the numerical promotion process the byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required.

When is static variable loaded? Is it at compile time or runtime? When exactly a static block is loaded in Java?
Static variable are loaded when classloader brings the class to the JVM. It is not necessary that an object has to be created. Static variables will be allocated memory space when they have been loaded. The code in a static block is loaded/executed only once i.e. when the class is first initialized. A class can have any number of static blocks. Static block is not member of a class, they do not have a return statement and they cannot be called directly. Cannot contain this or super. They are primarily used to initialize static fields.

Explain working of Java Virtual Machine (JVM)?
JVM is an abstract computing machine like any other real computing machine which first converts .java file into .class file by using Compiler (.class is nothing but byte code file.) and Interpreter reads byte codes.

How can I get the serialVersionUID of a class?
By running the serialver tool with the name of the class as the command line argumet, as shown in the example that follows:  serialver java.lang.String.

Why is UTFDataFormatException thrown by DataOutputStream.writeUTF() when serializing a String?
DataOutputStream.writeUTF() does not support writing out strings larger than 64K. The first two bytes of a UTF string in the stream are the length of the string. If a java.lang.String is larger than 64K, it needs to be stored in the stream by an alternative method rather than depending on the default method of storing a String in the stream, writeUTF.

Does JVM maintain a cache by itself? Does the JVM allocate objects in heap? Is this the OS heap or the heap maintained by the JVM? Why
Yes, the JVM maintains a cache by itself. It creates the Objects on the HEAP, but references to those objects are on the STACK.

Can a method be static and synchronized?
 A static method can be synchronized. If you do so, the JVM will obtain a lock on the java.lang.
Class instance associated with the object. It is similar to saying:
     synchronized(XYZ.class) {
     }

How Observer and Observable are used?
public class ObservDemo extends Object {
  MyView view;
 MyModel model;
  public ObservDemo() {
    view = new MyView();
    model = new MyModel();
    model.addObserver(view);
  }
  public static void main(String[] av) {
    ObservDemo me = new ObservDemo();
    me.demo();
  }
  public void demo() {
    model.changeSomething();
  }
  /** The Observer normally maintains a view on the data */
  class MyView implements Observer {
    /** For now, we just print the fact that we got notified. */
    public void update(Observable obs, Object x) {
      System.out.println("update(" + obs + "," + x + ");");
    }
  }
  /** The Observable normally maintains the data */
  class MyModel extends Observable {
    public void changeSomething() {
      // Notify observers of change
      setChanged();
      notifyObservers();
    }
  }
}

What are the differences between boolean & operator and  & operator.
When an expression containing the  & operator is evaluated, both operands are evaluated. And the & operator is applied to the operand. When an expression containing && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then only the second operand is evaluated otherwise the second part will not get executed.  && is also called short cut and

Can we declare an anonymous class as both extending a class and implementing an interface?
No. An anonymous class can extend a class or implement an interface, but it cannot be declared to do both.

what is a the difference between System.err and System.out
We can redirect System.out to another file but we cannot redirect System.err stream.

Can we catch an error in our java program ?
Yes. We can . We can catch anything that is derived from Throwable. Since Error is a sub class of Throwable we can catch an error also.

How many times may an object's finalize() method be invoked by the garbage collector?
Only once.

What is the difference between notify and notifyAll method ?
Notify wakes up a single thread that is waiting for object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. notifyAll Wakes up all threads that are waiting on this object's monitor. A thread waits on an object's monitor by calling one of the wait methods.

What does wait method do ?
It causes current thread to wait until either another thread invokes notify or notifyAll method of the current object, or a specified amount of time has elapsed.

What are the different states of a thread ?
The different thread states are ready, running, waiting and dead

What is the difference between String and StringBuffer class ?
Strings are immutable (constant), their values cannot be changed after they are created. StringBuffer support mutable objects,their values can be changed.

Why we cannot override static methods?
Static means they are associated with a class. In static methods , the binding mechanism is static binding. So it must be available at the compile time.


How is the difference between thread and process?
A process runs in its own address space. No two processes share their address space. Threads will run in the same address space of the process that owns them.

What is the difference between Iterator and Enumeration?
Iterator differ from enumeration in two ways Iterator allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics. And , method names have been improved.

What is a marker interface or tag interface?
An interface that contains no methods. Eg: Serializable, Cloneable, SingleThreadModel etc. It is used to just mark java classes that support certain capability.

Why Java is not fully objective oriented ?
Due to the use of primitives in java, which are not objects.

What is immutable?
Here a new object is created each time.

What is daemon thread?
Threads which are running on the background are called deamon threads. daemon thread is a thread which doesn't give any chance to run other threads once it enters into the run state it doesn't give any chance to run other threads. Normally it will run forever, but when all other non-daemon threads are dead, daemon thread will be killed by JVM.

What is volatile variable?
      A volatile variable is not allowed to have a local copy of a variable that is different from the value currently held in "main" memory. Volatile modifier requests the JVM to always access the shared copy of the variable so the it’s most current value is always read.

What is the difference between Comparable and Comparator ?
The Comparable is for natural ordering and Comparator is for custom ordering. But we can override the compareTo method of comparable interface to give a custom ordering.

What is a class, member and local variable?
Variables declared within a method are local variables. Variables declared within the class are member variables. Variables declared within the class with static modifier are class variables.

A subclass has complete access to super class member variables.


float j = Float.valueOf(args[0]).floatValue();
or          Float.parseFloat(“  ”);

String cs,bs,str;
     char[] chars = {'a','b','c','d'}; // CHAR ARRAY ASSIGNMENT TO STRING
     cs = new String(chars,0,chars.length);
     byte[] bytes = {65,66,67,68}; // BYTE ARRAY ASSIGNMENT TO STRING
     bs = new String(bytes,0,bytes.length)

class comparee implements Comparator{
    @Override
    public int compare(Object o1, Object o2) {
       // throw new UnsupportedOperationException("Not supported yet.");
        String a = (String) o1;
        String b = (String) o2;
        return a.compareTo(b);
    }
}
public class tree {
   static  TreeMap tm = new TreeMap(new comparee());
    public static void main(String agrs[]){
     tm.put("Kannan","Chennai");
     tm.put("Sachin","Bombay");
     tm.put("Elangovan","Bangalore");
     tm.put("Ram","Vellore");
     tm.put("Pathan","Delhi");
     tm.put("Ganguly","Kolkata");
        Set entrySet = tm.entrySet();
        Iterator iterator = entrySet.iterator();
        for (Iterator it = entrySet.iterator(); it.hasNext();) {
           Map.Entry b =(Map.Entry) it.next();
           System.out.println(b.getValue());
        }
    }
}

maruti
maruti