Sunday, April 10, 2011

Core Java Q&A


                                                                        Core Java

Q) New in Java 1.5?
Generics: Provides compile-time type safety for collections and eliminates the need for casting every time you get an object out of Collections
For/in loop: Instead of using iterators we can use this.
Varargs: Converts the arguments into an array of strings when you use the “...” syntax, it automatically treats that parameter as an array.
Ex:-
public class VarArgs {
  public static void main(String[] args) {
    vaMethod("a", "b", "c");
  }

  public void vaMethod(String... args) {
     for(String s : args)
        System.out.println(s);
  } }
Autoboxing/Unboxing à Eliminates need of manual conversion between primitive types (such as double) and wrapper types (such as Double).
Integer wrapper_integer = 5;  // primitive 5 autoboxed into an Integer
int primitive_int = wrapper_integer;  // automatic unboxing Integer into int
Enums: enums provide default implementation for toString(), equals(), hashCode() methods, enums are Comparable and Serializable by default,  enums are allowed to implement interfaces, switch, Adding new enum constants, does not require re-compilation of the client code
Static Import: Eliminates the need for using class names prior to using the static member variables of other classes. This will make the code a bit neater.
Using this now you can import the static members of the interface import static
Anotations: Annotations are generally a way to add meta-data information to an element (an element can be a class, method, field, or anything) and these meta-data are processed by the tools (compilers, javadoc, etc.). Annotations are differentiated from other elements like class, interface etc., by preceding an '@' symbol before it. Annotations can be applied to class (a class-level annotation), or a method (method-level annotation) or a field (field-level annotation) is specified in the declaration of the annotation itself.

Q) Opps concepts?
Polymorphism: Ability to take more than one form, in java we achieve this using Method Overloading (compile time polymorphism), Method overriding (runtime polymorphism)
1. Compile-time polymorphism: what object will be assigned to the present variable this will be evaluated at compile time.
2. Run-time polymorphism: what object will be assigned to the present variable this will be evaluated at runtime  depending on condition.
Inheritance: Is the process by which one object acquires the properties of another object.

Benefits of Inheritance: To minimise the amount of duplicate code by sharing common code amongst several subclasses. If equivalent code exists in two related classes, the hierarchy can usually be refactored to move the common code up to a mutual superclass.

Encapsulation: Wrapping of data and methods into a single unit called encapsulation. Ex: - all java programs (Or) Encapsulation is the mechanism that binds together code & data it manipulates and keeps both safe from outside interference and misuse.

Abstraction: Representing the essential futures without including background details.

DynamicbindingCode associated with a given procedural call is not known until the time of the call at runtime. Dynamic binding is nothing but late binding.
  
Q) How will u implement 1) multiple inheritance 2) multilevel inheritance in java?
    Multiple Inheritances – interfaces.
    Multilevel Inheritance – extending class.

Q) Why java doesn't support Cyclic Inheritance?
class a extends b { } class b extends a { }

In the first block “a” is subclass of class “b”. Again class “b” is extending class “a” which is a sub class of “b”. A sub class never becomes a super class from which it is extended. So in java it throws an exception like cyclic inheritance not possible.

Q) How an object becomes eligible for G.C?
An object is eligible for G.C when no object refers to it, an object also becomes eligible when its reference is set to null. The objects referred by method variables or local variables are eligible for garbage collection when they go out of scope.
Integer i = new Integer(7);
i = null;

Q) is a’ & a ‘has a’ relationship (or) explain Inheritance & Composition? Diff between Composition & Aggregation?
The is arelationship is expressed with inheritance and has arelationship is expressed with composition. Both allow you to place sub-objects inside your new class. Two of them used for code reuse are class inheritance and object composition.

Q) Garbage collection
G.C is also called automatic memory management as JVM automatically removes the unused variables/objects from the memory. G.C to automatically free the objects that are no longer referenced by a program. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use. When calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected. Garbage collection is a low-priority thread and it is a daemon thread.
G.C cannot be forced explicitly the call System.gc() does not force the garbage collection but only suggests that the JVM may make an effort to do garbage collection.

Q) Overloading & Overriding?
Overloading (Compile time polymorphism)
Defining two or more methods within the same class (or) subclass that share the same name and number of parameters, but order of parameter & return type are different then the methods are said to be overloaded.
· Overloaded methods do not have any restrictions on exceptions can be thrown. That is something to worry about with overriding.
· Overloading is used while implementing several methods that implement similar behavior but for different data types.

Overriding (Runtime polymorphism)
When a method in a subclass has the same name, return type & number of parameters as the method in the super class then the method in the subclass is override the method in the super class.

* Access modifier for the overriding method may not be more restrictive than the access modifier of the superclass method.
· If the superclass method is public, the overriding method must be public.
· If the superclass method is protected, the overriding method may be protected or public.
· If the superclass method is package, the overriding method may be packagage, protected or public.
· If the superclass methods is private, it is not inherited and overriding is not an issue.
· Methods declared as final cannot be overridden.

* Overriding method may only include exceptions that can be thrown by the superclass method, including its subclasses.

Q) Final, Finally, Finalized
Final: - Final to prevent Inheritance & Method Overriding. Once to declare a variable as final it cannot occupy memory per instance basis. Final class cannot have static methods / abstract methods (Because of final class never allows any class to inherit it), Final class can have a final method.

Finally: - Finally create a block of code that will be executed after try catch block has completed. Finally will execute whether are not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement match the exception.

* You can have try in finally and you can have finally in finally as well.
                       
* Using System.exit() in try block will not allow finally code to execute, because the try block does not complete execution at all. The System.exit method halts the execution of the current thread and all others dead in their tracks.
* Even if I write “return” at the end of the try block and no exception occurs also the finally block will execute.

Finalized: - An object need to perform some actions when it is going to garbage collected. JVM give the user a chance to clean up some resources before it got garbage collected. if an object holding some non-java resource such as closing the open file, closing a opened database Connection these resources are freed before the object is going to destroy.
* protected void finalize()throws throwable

Q) Constructor
The automatic initialization is performed through the constructor, constructor has same name has class name. Constructor has no return type not even void. We can pass the parameters to the constructor. this() is used to invoke a constructor of the same class. Super() is used to invoke a super class constructor. Constructor is called immediately after the object is created before the new operator completes.

* Constructor can use the access levels public, protected, private or have no access modifier
* Constructor can not use the modifiers abstract, static, final, native, synchronized or strictfp
* Constructor can be overloaded and we cannot override.
* You cannot use this() and Super() in the same constructor.

Q) Diff Constructor & Method?
Constructor
Method
Use to instance of a class
Grouping java statement
No return type
Void (or) valid return type
Same name as class name
The class method name, begin with lower case.
“This” refer to another constructor in the same class
Refers to instance of class.
“Super” to invoke the super class constructor
Execute an overridden method in the super class.
Inheritance” cannot be inherited
Can be inherited
We can overload but we cannot overridden
Can be inherited
Will automatically invoke when an object is created
Method has called explicitly

Q) What is static in java?
Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object.

Q) Static methods cannot access instance variables why?
There is no need to create an object of Static methods, Static methods can be invoked before the object is created, Instance variables are created only when the new object is created. Since there is no possibility to the static method to access the instance variables.

Q) Diff Static block & Static variable?
Static variable
Static block
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.
S.B which executed exactly once when the class is first loaded into JVM. Before going to the main method the S.B will execute. 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.

Q) Static variable & Static method
Static variables & methods are instantiated only once per class. In other words they are class variables, not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class.
* Static variable are loaded when classloader brings the class to the JVM, Static variables will be allocated memory space when they have been loaded.
* Instance variables declared as static are essentially global variables.
* If you do not specify an initial value to an instance & Static variable a default value will be assigned automatically.
* Static variable stores in a memory static (heap, stack, static are three memories in JVM).

Static methods can be called with the name of the class. It may not access the instance variables / instance methods.
* Static members can be accessed before any objects of its class are created.
* Methods declared as static have some how they cannot refer this or super.
* If a non-static method overrides a static method (or) static method overrides a non-static method then compile time error occurs.
* We can overload a static method & we canot override a static method.
* Static method in a super class can be overridden by another static method in a subclass.
* Static methods is called by the static methods only, an ordinary method can call the static methods, but static methods cannot call ordinary methods.
* Static methods are implicitly "final", because overriding is only done based on the type of the objects

Q) 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) {
           }

Q) Class variable & Instance variable & Instance methods & Class methods
Instance variable à variables defined inside a class are called instance variables with multiple instance of class; each instance has a variable stored in separate memory location.Class is loaded in to memory, then only memory is allocated for all class variables.

Class variables à you want a variable to be common to all classes then we create class variables. To create a class variable put the “static” keyword before the variable name.

Class methods à Class methods allow us to call a method without creating instance of the class, to declare a class method use the “static” key word.

Instance methods à define a method in a class, in order to use the methods we need to first create objects of the class.

Q) Diff String & StringBuffer & StringBuilder
String
StringBuffer
StringBuilder
String is a final class; it is a fixed length of sequence of characters.
SgtringBuffer represent growable and writeable character sequence.
If you aren’t going to use threading then use the StringBuilder as it’ll be more efficient than StringBuffer due to the absence of synchronization

Strig is immutable object (means the value stored in the String object cannot be changed).
StringBuffer is mutable which means that its value can be changed.
StringBuilder is mutable.
All of the java.lang package wrapper classes are immutable

StringBuffer is synchronized.


StringBuilder is not synchronized.


String: Here your not changing the contents of the object and it’s not the same String object that reflects the changes you do. Internally a new String object is created to do the changes.

String myString = myString +” Guest”;
* concat(), trim(), substring(), and replace() in String classes that generate new string instances.

String literals (String str=”hello”) are also string objects. String literals are created on special area on heap called a literal pool whereas the string objects are created on memory heap.

In case of string objects, always a new string object is created when you use new keyword. In case of literals if there is already a literal in the literal pool then new string literal is not created.

Performance improvement in String & StringBuffer concatenation:

String concatination
StringBuffer concatenation
String str = "abc";
long stTime = System.currentTimeMillis();
for ( int i = 0; i < 100; i++) {
         str += "xyz";
}
long endTime = System.currentTimeMillis();
double time = (endTime - stTime)/1000.0;
System.out.println("String concatenation:"+ time);
StringBuffer sb = new StringBuffer();
long sbTime = System.currentTimeMillis();
for ( int i = 0; i < 100; i++) {
         sb.append(i);
}
long endTime = System.currentTimeMillis();
double time = (endTime - sbTime)/1000.0;
System.out.println("StringBuffer concatenation:"+ time);
The above code would build 99 new objects, of which 98 would be thrown away immediatey.
The above code would build only one new objects.

Optimization techniques when Concatenating Strings :
“+” operator is faster than “StringBuffer.append()” method, compiler does a good job of optimization it simply concatenates at compile time. It does compile time resolution instead of runtime resolution and StringBuffer object is resolved at runtime.

How JVM works with Strings
JVM loads String literal from class file and executes, it checks whether that String exists in the internal list or not. If it already exists in the list, then it does not create a new String and it uses reference to the existing String Object. JVM does this type of checking internally for String literal but not for String object which it creates through 'new' keyword      .

Q) Diff “= =” & “.equals()”?
equals() à Compare the characters in the string object.
==         à Compares two objects to determine if they are the same object in memory i.e. present in the same memory location. It is possible for two String objects to have the same value, but located in different areas of memory.

   StringBuffer sb1 = new StringBuffer("Amit"); 
   StringBuffer sb2 = new StringBuffer("Amit");
   String s1 = "Amit";  
   String s2 = "Amit";
   String s3 = new String("Amit ");
   String s4 = new String("Amit ");
           
(sb1==sb2)         à F
(s1.equals(s2)) à T
(s3.equals(s4)) à T
(sb1.equals(s1)) à F
(sb1.equals(sb2)) à F
((s1==s2))        à T
((s3==s4))        à F


    s1 == s3 à F
    s1.equals(s3)) à T

String.equals() only compares the characters as a last effort: it first compares the length of the strings, which is stored in a separate field, and only if the lengths are the same it starts comparing the characters, but it halts as soon as it finds the first non matching character.

Q) Why does not “Final” prevent my object from changing?
final StringBuffer s =  new StringBuffer(“Harsha”);
  s.append(“how are u”);
Reason is the “final” modifier makes the reference variable (here, s) final, not the object that “s” points to.

Q) How to make a Immutable Class?
An immutable class has all private data fields and none of the methods change the data field values

final class MyImmutable {
private final int count; // to restrict the access
private final double value;
public MyImmutable(int pCount,double pValue) {
   count = pCount;    value = pValue;
}
public int getCount() {
   return count;
} }
public class TestImmutable {
  public static void main(String[] args) {
     MyImmutable obj1 = new MyImmutable(3,5);
      System.out.println(obj1.getCount());
  // there is no way to change the values of count
  // no method to call besides getXX, no subclassing, no public access to var -> Immutable
}
}

Q) How to make a “immutable object”?
Override the equals() & hashCode() method.

Q) Why can't an Abstract method be declared private?
The private abstract method modifiers do not make sense in combination and the compiler will fail. An abstract method must be overridden by any subclass, but subclasses do not have access to their superclass' private fields, so a private abstract method could never be fulfilled.

Q) Why can't we create object for an Abstract Class?
An Abstract class doesnt have an implementation for one or more methods. After calling the abstract methods then the jvm doesnt have any direction of what to do and hence it may be crashed. So to avoid this situation we are restricted to instantiate an abstract class if you need an object for abstract class create a concrete subclass and create an object for it and use it.

Q) Abstract Class
It is an incomplete class containing default implementation for its sub classes. It contains both abstract and concrete methods. Any class that contain one are more abstract methods must also be declared as an abstract, there can be no object of an A.C. We cannot directly instantiate the abstract classes. Any sub class of an A.C must either implement all the abstract methods in the super class or be declared itself as Abstract.
* Compile time error occur if an attempt to create an instance of an Abstract class.
* You cannot declare “abstract constructor”
* You cannot declare “abstract static method” the compiler will reject the class with the error "illegal combination of modifiers"
* An “abstract method” also declared public, protected.
* Abstract class can have static method, static variables.
* A.C can have public, protected variable declaration as well.
* A class can be declared abstract even if it does not have any abstract methods. Declaring such a class abstract indicates that the implementation is somehow incomplete and is meant to serve as a super class for one or more subclasses that will complete the implementation.
abstract class AA {
protected Abstract void callmeprotected();
public Abstract void callmePublic();
            Void callmetoo() {………  }
            Public static void foo() {……… }
            Public/Protected static int si = 123;
}
class BB extends AA (
            protected void callmeprotected () {…….  }
public callmePublic() {…… }
}

class AbstractDemo {
public static void main(string args[]) {
            BB b = new BB();
            b. callmeprotected ();
} }

Q) Interface
Interface is similar to class but they lack instance variable, their methods are declared with out any body. Interfaces are designed to support dynamic method resolution at run time.
* All methods of an interface are implicitly Public Abstract even if the public modifier is omitted.
* Interface methods cannot be declared protected, private, strictfp, native or synchronized.
* All Variables are implicitly public static final fields. In the implementation class you cannot change this variables because these are final.
* An interface body may contain constant declarations, abstract method declarations, inner classes and inner interfaces.
* A Compile time error occurs if an interface has a simple name the same as any of it's enclosing classes or interfaces.
* top-level interfaces may only be declared public, inner interfaces may be declared private and protected but only if they are defined in a class.
* Interface can be extended & implemented.
* A class can only extend one other class and a class may implements more than one interface.
* Interface can extend more than one interface and cannot extend abstract class, class.

Why Interfaces?
“one interface multiple methods“ signifies the polymorphism concept.
public Interface A {
            public final static float pi = 3.14f;
}
class B implements A {
            public float compute(float x, float y) {…….. }
}

   class test{
   public static void main(String args[]){
            A a = new B();
            a.compute();
    }  }

Q) When we use Abstract class & Interface? Useful of Abstract Class & Interface?
- Adding new methods in abstract class in middle of development canno't break existing sub classes. Method can be simply implemented in the abstract class and the same can be called by its subclass. If there is frequent addition of new methods then use abstract class.

- Adding new methods to the interface will force users to go through each and every sub class that implemented that interface and call these methods. So it is always preferred to use abstract over interface because of this limitation.

- If you plan on updating the base class throughout the life of your program, it is best to allow that base class to be an abstract class. Because you can make a change to it and all of the inheriting classes will now have this new functionality.

- If the base class will be changing often and an interface was used instead of an abstract class, we are going to run into problems. Once an interface is changed, any class that implements that will be broken.

- An interface is also used in situations when a class needs to extend another class apart from the abstract class. In such situations its not possible to have multiple inheritance of classes. An interface on the other hand can be used when it is required to implement one or more interfaces. Abstract class does not support Multiple Inheritance whereas an Interface supports multiple Inheritance.

If you want to inherit from class that can provide reusable code then use abstract class. For instance connecting to the database.

Abstract classes are useful in a situation when some general methods should be implemented and specialization behavior should be implemented by subclasses. Interfaces are useful in a situation when all its properties need to be implemented by subclasses

Q) Diff Interface & Abstract Class?
Interface
Abstract Class
Interface contains no implementation code
A.C may have some executable methods & methods left unimplemented which has to be implemented by sub classes
An Interface cannot have instance variables
A.C can have instance variables
Interface can't have subclasses
An A.C must have subclasses
Interface cannot have constructor.
A.C can define constructor
An Interface visibility must be public.
A.C can have any visibility: public, private, protected
An Interface can only declare constants and instance methods, but cannot implement default behavior.
A.C can have instance methods that implement a default behavior

Q) Can two interfaces have the same methods & same variable?
Concrete class can only provide one implementation of a given method signature, so there is no ambiguity about how the Java compiler deals with this case, only a potentially difficult design decision.

Yes, we can declare two variables with the same name and we need to call them with their corresponding interface names.

Q) Diff Interface & Class?
 A class can have instance variable and an Interface has no instance variables.
 Objects can be created for classes where as objects cannot be created for interfaces.
 All methods defined inside class are concrete. Methods declared inside interface are without any body.

Q) Diff Abstract class & Class?
 Classes are fully defined. Abstract classes are not fully defined (incomplete class)
 Objects can be created for classes; there can be no objects of an abstract class.

Q) When I use Object as a key in HashTable , what in the Object class must override and why?
hashCode() & equals()?
This is used to compare two objects based upon the equals() method. If any one wants to use your object as key in any coolection then we need to implement this. hashCode() is used to get a "unique" identifier for each object. The hash code is used to speed up the search process. First it checks if two hash codes to be the same then it will check the equals method ito verify for an exact match.

The hashCode() method returns an integer that is a "hashcode" for the object. Hashcodes are used in the process of storing objects in collection. Hashcode helps the collections to optimize its storage of objects by serving as an identifier for distributing them into storage evenly, and locating them quickly. The default  implementation of hashCode() in Object assigns each object instance a unique number.

If you don't override this method each instance of your class will have a unique hashcode. However, if you classes have a equivalent objects (if you have overriden equals()) and you want equal objects to serve as equivalent keys in a Hashtable, then you should override hashCode() so that your equivalent objects generate the same hashcode value.

Q) Object creation?

Object is constructed either on a memory heap (or) on a stack.
Generally the objects are created using the new keyword. Some heap memory is allocated to this newly created object. This memory remains allocated throughout the life cycle of the object. When the object is no more referred the memory allocated to the object is eligible to be back on the heap.
Stack
The primitive variables like int and double are allocated in the stack. In a multi-threaded application each thread will have its own stack but will share the same heap. The stack is threadsafe (each thread will have its own stack) but the heap is not threadsafe unless guarded with synchronisation through your code.

Q) Ways of Object Creation?
1. Using new operator. 2. First get class reference using “class.forName()” or class loader. On this class, create object using 'newInstance()' method. 3. Clone 4. Deserialization

Q) System.out.println()
 “println()” is a methd of  “java.io.printWriter”, “out” is an instance variable of  “java.lang.System” class.

Q) Byte code & JIT compiler & JVM & JRE & JDK & lib & bin
* Byte code is a highly optimized set of instructions. Translating a java program into byte code helps makes it much easier to run a program in a wide variety of environment.
* JVM is an interpreter for byte code, which converts source code to byte code. This byte code varies from one platform to Platform.
* JRE is an implementation of the JVM, which actually executes Java programs.
* JIT (Just In Time) is a part of JVM, JIT will is used when the application is run and that time the bytecode is converted to the machine code (native code). In real time JIT will increase the performance of the interpretations.

How it will increase the performanace?           
The job of the JIT compiler is to convert this bytecode to the machine code (native code). JIT compiler uses a V-table which is a pointer to the methods in the class. This internal table is used to compile the methods to native code.
Only during the first call to a method it is compiled and for the subsequent calls the native code for that particular method is called. The V-table maintains the addresses of the native code for all the methods that are compiled. V-table also maintains another table which has the addresses of the bytecode itself in case there is a need to compile it for the first time.
* JDK is also includes the JVM, standard class libraries and several other tools. Tools provided by JDK are….
(i) Javac – compiler                   (ii) java – interpretor                               (iii) jdb – debugger        
(iv) javap - Disassembles          (v) Appletviewer – Applets         (VI) javadoc - documentation generator  
(vii) javah - 'C' header file generator
* “Lib” contains API and all the packages.
* bin” contains all tools such as javac, appletviewer & awt tool.




Q) Public static void main (String [] args)
 We can overLoad the main() method.

Valid main declarations
InValid (Runtime Error not compile time error)
public static void main(String [] args){}
public void main(String [] args){} 
// static modifier missing
public static void main(String [] XXX){}
 // in the place of XXX any thing can be placed
static void main(String [] args){}
// public modifier missing
static public void main(String [] args){}
public static int main(String [] args){return 1;}
// return type must be void
public static final void main(String [] args){}
private static void main(String [] args){} 
// At runtime will give "Main method not public"
public static synchronized void main(String [] args){}
protected static void main(String [] args){} 
// access modifier is protected
public static strictfp void main(String [] args){}
public static void main(String args){} 
// argument to main method is a String and not ‘String[]’

public static void main(){} 
// argument is missing a runtime error "NoSuchMethodError"

Q) Can an application have multiple classes having main() method?
Yes it is possible. While starting the application mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is not conflict among the multiple classes having main method.

Q) Can I have multiple main methods in the same class?
No the program fails to compile. The compiler says that the main method is already defined in the class.

Q) Can we compile a java program without main?
Yes, we can. In order to compile a java program, we don't require any main method. But to execute a java program we must have a main in it (unless it is an applet or servlet). Because main is the starting point of a java program

Q) Can we write another main method in the main, which is entry point in java?
Yes, the reason is java just looks the main as an entry point to start running the java file and what ever inside it be in a main method JVM treats it as an other overloaded method.

Q) Why do I have to put an “f” after a floating point constant?  
The f (or F) suffix directs the compiler to create a float value from a sequence of characters representing a floating point number, otherwise the compiler would by default create either a double value.
Ex: - Float f = 12.34; //invalid
The literal 12.34 is of double type, it cannot be directly assigned to a variable of type float because float (32 bits) is narrower datatype than double (64 bits). You can redundantly apply the suffix “d” to the floating-point literals.

Q) Why Runnable interface is preferable than extending the Thread class?
Java not supporting multiple inheritance, If we extend thread class you can't extend any class which you required 
other than thread class.if u are implementing runnable interface u can extend any class which you required other 
than thread class.

Q Count the number of instances of an object?
Create a static int variable to store the number of instances and include an increment statement in all constructors. Implement a final finalize() method that is called upon garbage collection to decrement the count. And since multiple instances may increment and decrement the static value in separate threads, these statements should be enclosed in a synchronized block

Q)  Can you instantiate the Math class? Can I write sin(x) instead of Math.sin(x)?
You can’t instantiate the math class. All the methods in this class are static. And the constructor is not public

Before Java 1.5, it is not possible. From Java 1.5 it is possible by using static imports; you can now write “import static java.lang.Math.*” and then use sin(x).

Q) Approaches that you will follow for making a program very efficient?
1) By avoiding too much of static methods 2) Unnecessary use of synchronized methods 3) Use synchronized classes for multiuser and non-synchronized classes for single user 4) Usage of appropriate design patterns 5) Using cache methodologies for remote invocations 6) Avoid creation of variables within a loop. 7) for string concat operations use append method.

Q) Synchronization
Is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time (Or) When 2 are more threads need to access the shared resources they need to some way ensure that the resources will be used by only one thread at a time. Ex: - Railway booking, ATM

Block level Synchronizing
Method Level Synchronizing
If you go for synchronized block it will lock a specific object.

class A {
     public void method1() {...}
}
class B {
public static void main(String s[]) {
    A object1=new A();
    A object2=new A();
    synchronized(object1) {
          object1.method();
    }
          object2.method1(); //not synchronized
} }
class A {
      public synchronized void method1() { ...}
}
class B {
public static void main(String s[]) {
  A objecta=new A();
  A objectb =new A();
  objecta.method1();
  objectb.method2();
} }


Class level lock? Can a lock be acquired on a class?
Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object.

Object's lock? Which object's have locks?
This is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock.

Q) Diff Static Synchronization & Non-Static Synchronization?
When Synchronization is applied on a static Member or a static block, the lock is performed on the Class and not on the Object, while in the case of a Non-static block/member, lock is applied on the Object and not on class. When ever you call a "static synchronized" block, JVM locks access to this Class object and not any of your objects.

Q) Runtime class         
Runtime class is to provide access to the Java runtime system. You cannot instantiate a Runtime object. You can get a reference to the current Runtime object by calling the static method Runtime.getRuntime()

Q) How will you invoke external process in java?
You can use java to execute other heavy weight process on your multi tasking operating system, several form of exec() method allow you to name the programme you want to run.
            Runtime r = Runtime.getRuntime();
            Process p = r.exce(notepad);
            p.waiFor()

Q)  Size of the Java Memory Heap?
// Get current size of heap in bytes
long heapSize = Runtime.getRuntime().totalMemory();

// Get max size of heap in bytes and heap cannot grow beyond this size. Any attempt will result in an OutOfMemoryException.
long heapMaxSize = Runtime.getRuntime().maxMemory();

// Get amount of free memory within the heap in bytes. Size will increase after garbage collection and decrease as new objects are created.
long heapFreeSize = Runtime.getRuntime().freeMemory();

Q) System class          
The purpose of this class is to provide access to system resources. System class hold a collection of static methods & variables. The standard input, output, error output of the java runtime are stored in the in, out, err variables.
           
Q) How to get the path of main class of application?
String S = system.getProperty(“user.dir”);

Q) Set & Get the Value of a System Property from the Command Line?
java -Dmy.prop="my value" MyApp
String prop = System.getProperty("my.prop");

Q) Class
Class encapsulate the run-time state of an object or interface. Methods in this class are

Method[] methods = Vardhan.class.getMethods();
Class[] intfs = Vardhan.class.getInterfaces();

forName(String name)
getClass()
getInterface()
 getDeclearedMethods()
getMethods()
getClassLoader()
getConstructor()
getSuperClass()
getDeclaredFields()
getField()

Q) java.lang.Reflect (package)
Reflection allows programmatic access to information about the fields, methods and constructors of loaded classes, and the use reflected fields, methods and constructors to operate on their underlying counterparts on objects, within security restrictions.

Q) Static & Dynamic Class loading?
Static Loading
Dynamic Laoding
Classes are statically loaded with Java’s “new” operator.

Car c = new Car();

Programmatically invoking the functions of a class loader at run time.

Class.forName(className); //returns the class object associated with the class name.
class.newInstance (); //creates an instance of a class (i.e an object).

Class vehicleClass = Class.forName(myClassName) ;
myJeep = (Jeep) vehicleClass.newInstance();

Q) Transient & Volatile
Transient à A transient variable is a variable that may not be serialized i.e. the value of the variable can’t be written to the stream in a Serializable class. If you don't want some field to be serialized, you can mark that field transient (or) static. In such a case when the class is retrieved from the ObjectStream the value of the variable is “null”.

If you want to send the transient variable also throw network then you need to explicitly mentione that.
private void writeObject(ObjectOutputStream stream) throws IOException {
    stream.defaultWriteObject();
    stream.writeObject(b);
  }

  private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
    stream.defaultReadObject();
    b = (String) stream.readObject();
  }

Volatile: Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.

In a multi-threaded programming, the volatile keyword will be more useful. When multiple threads using the same variable and each thread will have its own copy of the local cache for that variable. So, when it's updating the value, it is actually updated in the local cache not in the main variable memory. The other thread which is using the same variable doesn't know anything about the values changed by another thread. To avoid this problem, if you declare a variable as volatile, then it will not be stored in the local cache. Whenever a thread updating the values, it is updated to the main memory. So, other threads can access the updated value.

Q) Serialization? What are the uses of serialization? Can one have a control over the serialization process?
Serialization is the process of writing the state of the object to a byte stream; this is useful when ever you want to save the state of your programme to a persistence storage area. If any of the objects is not serializable then it throws a “NotSerializableException”. Serialization ignores static fields, because they are not part of ay particular state.

Yes we can control, the class should implement Externalizable interface and it contains two methods readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process.

Q) Diff Serializable & Externalizable
Serializable
Externalizable
Is an interface that extends serializable interface and sends data into streams in compressed format. It has 2 methods

writeObject(objectOutputStream out)  
readObject (objectInputStrem in)
Is an Interface that extends Serializable Interface. It sends data into Streams in Compressed Format. It has 2 methods and these methods give you a control over the serialization mechanism. Thus if your class implements this interface, you can customize the serialization process by implementing these methods.

writeExternal(ObjectOuput out)
readExternal(ObjectInput in)

Q) Marker Interfaces (or) Tagged Interfaces:-
An Interface with no methods is called marker Interfaces, eg. Serializable, SingleThread Model, Cloneable.

Q) Why do we need wrapper classes?
Wrapper class is called for converting primitive data types into objects. It is sometimes easier to deal with objects, moreover most of the collection classes store objects and not primitive data types. And also the wrapper classes provide many utility methods also. Because of these resons we need wrapper classes.

Q) Internalisation & Localization
Internalisation à Making a programme to flexible to run in any locale called internalisation.
Localization    à Making a programme to flexible to run in a specific locale called Localization.

Q) Can I use the same variable name in two methods?
Yes, It is possible. Methods have their own variable scope, so the Java compiler and interpreter can maintain a distinction between the variables they contain. Generally it is preferable for variables that represent different properties to have different names to avoid confusion.

Q) InstanceOf
Instanceof means by which your program can obtain run time type information about an object.
Ex:- A a = new A();
       a.instanceOf A;

Q) Cloneable Interface
Any class that implements the cloneable interface can be cloned, this interface defines no methods. It is used to indicate that a class allow a bit wise copy of an object to be made.

Q) Comparable Interface
Classes that implements comparable contain objects that can be compared in some meaningful manner. This interface having one method compare the invoking object with the object. For sorting comparable interface will be used.
Ex :- int compareTo(Object obj)

Q) Boxing and Unboxing?
Boxing refers to the conversion of a primitive to a corresponding wrapper instance, such as from an int to a java.lang.Integer.
Unboxing is the conversion of a wrapper instance to a primitive type, such as from Byte to byte.

Q) Can we create a .Exe for a Java file?
Micro soft provided sdk for java, which includes jexegentool. This converts class file into a .Exec  form. Only disadvantage is user needs a M.S java V.M installed.

Q) How do I convert a numeric IP address like 192.18.97.39 into a hostname like java.sun.com?
A) String hostname = InetAddress.getByName("192.18.97.39").getHostName()

Q) What are different types of inner classes?
 Nested top-level classes- If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other top-level class. Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. e.g., outer.inner. Top-level inner classes implicitly have access only to static variables. There can also be inner interfaces. All of these are of the nested top-level variety.

Member classes - Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested top-level class. The primary difference between member classes and nested top-level classes is that member classes have access to the specific instance of the enclosing class.

Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement a more publicly available interface. Because local classes are not members the modifiers public,  protected, private and static are not usable.

Anonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor.
à Inner class inside method cannot have static members or blocks

Q) Java Keywords?
package
import
class
extends
interface
Instanceof
new
switch
for
void
implements
public
private
protected
final
Const
else
if
default
return
abstract
strictfp
super
this
byte
Goto
while
catch
native
case
short
int
long
char
boolean
Assert
do
finally
synchronized
continue
float
double
static
transient
volatile
Value
break
throw
try
throws

Q) URL Encoding & URL Decoding
 URL Encoding is the method of replacing all the spaces and other extra characters into their corresponding Hex  
 Characters and URL Decoding is the reverse process converting all Hex Characters back their normal form.

Q) URL & URLConnection
URL is to identify a resource in a network, is only used to read something from the network.
URL url = new URL(protocol name, host name, port, url specifier)

URLConnection can establish communication between two programs in the network.
URL hp = new URL(www.yahoo.com);
URLConnection con = hp.openConnection();

Q) Access Specifiers & Access modifiers?
Access Specifiers gives access privileges to outside of application (or) others, they are Public, Protected, Private, Defaults.
Access Modifiers which gives additional meaning to data, methods and classes, final can’t be modified at any point of time.


Private
Public
Protected
No modifier
Same class
No
Yes
Yes
Yes
Same package Subclass
No
Yes
Yes
Yes
Same package non-subclass
No
Yes
Yes
Yes
Different package subclass
No
Yes
Yes
No
Different package non-subclass
No
Yes
No
No

Q) Primitive Data Types & Default Values
long (I)
-2^63 to 2^63 –1 à 0L
Double (F)
0.0d
Int (I)
-2^31 to 2^31 –1 à 0
Float (F)
0.0f
Short (I)
-2^15 to 2^15 –1 à 0
Boolean
False
Byte (I)
-2^7 to 2^7 –1     à 0
char
0 to 2^7 –1 à null character (or) ‘\u 0000’

Q) How can I swap two variables without using a third variable?
int a=5,b=10;a=a+b; b=a-b; a=a-b;

Q) How can you improve java I/O performance?
The basic rules for speeding up I/O performance are
  • Minimise accessing the hard disk.
  • Minimise accessing the underlying operating system.
  • Minimise processing bytes and characters individually.

Without buffering : inefficient code
Try {
File f = new File("myFile.txt");
FileInputStream fis = new
                                   FileInputStream(f);
int count = 0;  int b = ;
while((b = fis.read()) != -1) {
if(b== '\n') {
count++;
} }
fis.close() ;
}

With Buffering: yields better performance
Try {
File f = new File("myFile.txt");
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new
                                 BufferedInputStream(fis);
int count = 0;  int b = ;
while((b = bis.read()) != -1) {
if(b== '\n') {
count++;
} }
bis.close() ;
}
Reading one line: Instead of reading a character or a byte at a time, by reading one line at a time:

File f = new File("myFile.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
While (br.readLine() != null) count++;
           
Q) Default value of the local variables?
The local variables are not initialized to any default value, neither primitives nor object references. If you try to use these variables without initializing them explicitly, the java compiler will not compile the code. It will complain abt the local varaible not being initialized