Thursday, 20 June 2013

Generics

Q1. Explain Type interface
Ans. This feature, known as type inference, allows you to invoke a generic method as you would an ordinary method, without specifying a type between angle brackets.
The complete syntax for invoking this method is:
         Box.<Crayon>fillBoxes(red, crayonBoxes);

Here we've explicitly provided the type to be used as U, but more often than not, this can be left out and the compiler will infer the type that's needed:

       Box.fillBoxes(red, crayonBoxes); // compiler infers that U is Crayon

Q2. Explain subtyping.
Ans. It is explained by generics. Now consider the following method:

public void boxTest(Box<Number> n) {
      // method body omitted
}


Looking at its signature, we can see that it accepts a single argument whose type is Box<Number>. So, we think that it should accept Box<Integer> or Box<Double>. Surprisingly, the answer is "no", because Box <Integer> and Box<Double> are not subtypes of Box<Number>, but Integer and Double are subtypes of Number.


Q3. Can you limit the generic type <T> to few types or Explain bounded types.

Ans. Yes. It can be done using extends keyword.
Ex. using <T extends Number> expects the parameter to be passed of type Number or its sub-class. It can’t accept a String.

To specify additional interfaces to implement, use & character, as shown below:
      <U extends Number & MyInterface>
Bounded type parameters limit the kinds of types that can be passed into a type parameter; they can specify an upper bound only.


Q4. Explain use of wildcards in generics

Ans. In contrast to bounded parameters, Wildcards represent unknown types, and they can specify an upper or lower bound.

Keyword extends gives upper bound, saying “an unknown type that is a subtype of Number or Number itself" and keyword super gives a lower bound, saying “an unknown type that is super-type of Number or is Number itself”.


Ex. <Box<? extends Number>

Box<Integer> and Box<Double> are not subtypes of Box<Number>, they are in fact subtypes of “<Box<? extends Number>”. Here ? is a wildcard character.

Ex. <? super Number> -> Class must be a super class of Number or Number itself. Thus, it can be Number or Object.


Q5. Explain type erasure.

Ans. During compilation, type erasure removes all generic information from a generic class or interface, leaving behind only its raw type. It is possible for generic code and legacy code to interact, but in many cases the compiler will emit a warning telling you to recompile with special flags for more details.
java.sun.com/docs/books/tutorial/java/generics/erasure.html

Random Java Ques

Q1. Does importing a package imports the subpackages as well? e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*?
Ans. No, you will have to import the subpackages explicitly. Importing com.MyTest.* will import classes in the package MyTest only. It will not import any class in any of its subpackage.

Q2. Dictionary is an interface or class?
Ans. class.

Q3. Which one throws arithmetic exception:
a. int i = 100/0;b. float f = 100.00/0.0
Ans. b, float f = 100.00/0.0.
Float division by zero returns NAN (not a number) instead of exception.

Q4. Which one is not correct
a. x = = Float.NaNb. Float.isNan(x);
c. Myobject .equals(float.NaN);

Ans. a

Q5. Is below statement valid?
float f = 3.4;

Ans. No, a decimal number is a double by default. Assigning it to float requires a cast.


Q6. Java supports both multi dimension and nested arrays. True/False
Ans . False

Q7. What is the immediate super class of Container?
Ans. Component

Q8. What is the difference between the >> and >>> operators?
Ans. The >> operator carries the sign bit when shifting right. The >>> zero fills bits that have been shifted out.

Q9. Why would you prefer a short circuit “&&, ||” operators over logical “& , |” operators?
Ans: Firstly NullPointerException is by far the most common RuntimeException. If you use the logical operator you can get a NullPointerException. This can be avoided easily by using a short circuit “&&” operator as shown below.

if((obj != null) & obj.equals(newObj)) {

      //can cause a NullPointerException if obj == null because obj.equals(newObj) is always executed.
      ...
}

Short-circuiting means that an operator only evaluates as far as it has to, not as far as it can. If the variable 'obj' equals null, it won't even try to evaluate the 'obj.equals(newObj)’ clause as shown in the following example. This protects the potential NullPointerException.


if((obj != null) && obj.equals(newObj)) {

      //cannot get a NullPointerException because obj.equals(newObj) is executed only if obj != null
      ...
}

Q10. What happens if you put semicolon after if statement?
Ans. If you put a semicolon directly after the condition in if statement, Java thinks it's finished with the body of "if" statement (ONLY if statement).

NOTE: You can still continue with else statement.

if ( 1 == 2);
else System.out.println("false.");

Above code snippet prints "false", as else is considered continuation of "if" statement (since there is no other statement before else). However, if you put any other statement after "if" statement finished by semicolon, and then try to put else (as below), it will give a compilation error.


if ( 1 == 2); System.out.println("true.");

else System.out.println("false.");


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

Q12. What is the difference b/w procedure and function?

Ans. A procedure has a return type of void, whereas a function must return something.

Q13. Explain re-entrant, recursive and idempotent methods.
Ans. All Java methods are automatically re-entrant. It means that several threads can be executing the same method at once, each with its own copy of the local variables.

A Java method may call itself without needing any special declarations. This is known as a recursive method call. Given enough stack space, recursive method calls are perfectly valid in Java though it is tough to debug. Recursive methods are useful in removing iterations from many sorts of algorithms. All recursive functions are re-entrant but not all re-entrant functions are recursive.


Idempotent methods are methods, which are written in such a way that repeated calls to the same method with the same arguments yield same results. Ex: clustered EJBs, which are written with idempotent methods, can automatically recover from a server failure as long as it can reach another server (i.e. scalable).


Q14. Explain autoboxing and auto-unboxing?
Ans. It happens when converting primitive types to relevant object or vice-versa.

Ex:

Integer i;
int x = 5;
i = 5; // Auto-boxing happens since primitive int is converted to integer object.
float y = i ; //Auto un-boxing happens as value of Integer obj is converted to float.

Q15. What do you understand by downcasting?

Ans. The process of downcasting refers to the casting from a general to a more specific type, i.e. casting down the hierarchy

Q16. Give a scenario where explicit casting is not allowed, but implicit casting happens.

Ans. Incidentally, there is one situation in Java when only implicit casting is allowed, and that is string concatenation. Any time a string is concatenated with any object or base type, that object or base type is automatically converted to a string. Explicit casting of an object or base type to a string is not allowed, however.

Ex:String s = (String) 4.5; // this is wrong!

String s = “” + 4.5; // this is correct.

Q17. What is design by contract?
Ans. Design by contract specifies the obligations of a calling-method and called-method to each other. The strength of this programming methodology is that it gets the programmer to think clearly about what a function does, what pre and post conditions it must adhere to and also it provides documentation for the caller.

Java uses the assert statement to implement pre and post-conditions. Java’s exceptions handling also support design by contract especially in checked exceptions. In design by contract in addition to specifying programming code to carrying out intended operations of a method the programme also specifies:

1. Preconditions – This is the part of the contract the calling-method must agree to. Preconditions specify the conditions that must be true before a called method can execute. Preconditions involve the system state and the arguments passed into the method at the time of its invocation. If a precondition fails then there is a bug in the calling-method or calling software component.
2. Post-conditions – This is the part of the contract the called-method agrees to. What must be true after a method completes successfully. Post-conditions can be used with assertions in both public and non-public methods. The post-conditions involve the old system state, the new system state, the method arguments and the method’s return value. If a post-condition fails then there is a bug in the called-method or called software component.
3. Class invariants - what must be true about each instance of a class? A class invariant as an internal invariant that can specify the relationships among multiple attributes, and should be true before and after any method completes. If an invariant fails then there could be a bug in either calling-method or called-method. There is no particular mechanism for checking invariants but it is convenient to combine all the expressions required for checking invariants into a single internal method that can be called by assertions.
Ex: if you have a class, which deals with negative integers then you define the isNegative() convenient internal method.

Q18. Can we print address of a variable in java? If not, why?

Ans. In Java, say one object has been created at some particular address in Heap. At this point of time, we may feel that there should be some API which can return the address back. But, that is not possible because of another feature in Java - Garbage Collection. GC in Java not only collects the objects which are not live, it also does something called heap de-fragmentation. New objects gets created and old object gets deleted from the heap. As a result of this, free memory may lie non-utilized in between live objects. The GC moves all the live objects from one part of the memory to another part, so that contiguous free space remains available in the heap. Each time the object gets moved, its address gets changed. Depending on object's life span, this may happen many times. Hence the address also gets changed accordingly.

However, in java, it is possible to make JNI calls, which means I will be able to pass variables to JNI or I can access java variables in my JNI c++ code. And through my c++ code, I can print the address of the variable. But in that case, variable is not placed in jvm, instead it is stored in system memory. 


Q19. Why Java doesn't support sizeof operator?
Ans. Because all data types are the same size on all machines.

Q20. Why there are no global variables in Java?
Ans. Global variables are globally accessible. Java does not support globally accessible variables due to following reasons:
  • The global variables break the referential transparency.
  • Global variables create collisions in namespace.
Java doesn't support global variables, by design. Java was designed with object oriented principles in mind and as such, every variable in Java is either local or a member of a class. Static class members, whilst accessible via the class name and therefore across multiple scopes, are still class members; and therefore not global variables as such. Java's lack of support for global variables is a good thing, as using global variables is a design anti-pattern.

Q21. Difference btw getName(), getCanonicalName() and getSimpleName()

Ans. getName() and getCanonicalName() are same. Both includes package information, whereas getSimpleName() produces the class name alone.

Q22. Can you instantiate the Math class?
Ans. You can’t instantiate the Math class. All the methods in this class are static. And the constructor is not public.

Q23. Math.random and java.util.Random
Ans. Using Math.random works well when you need to generate a single random number. If you need to generate a series of random numbers, you should create an instance of java.util.Random and invoke methods on that object to generate numbers

Math.random() method returns a pseudo-randomly selected number between 0.0 and 1.0. The range includes 0.0 but not 1.0. In other words: 0.0 <= Math.random() < 1.0.


NOTE:  Default seed to java.util.Random is based on the current time.  However, same can be passed as an argument while initializing Random object.


Q24. Explain valueOf, toString and parseXXX in Number class?

Ans.
valueOf: The valueOf method converts a string to a number, and returns an object of given type.
Ex. Float.valueof(“5”) converts a string containing 5 into a float object with value 5.
parseXXXX: Similar to valueOf, except that it returns a primitive type.
Ex. Float.parseFloat(“5”) converts a string containing 5 into a primitive float with value 5.
toString: This method converts a number to a string.
Ex. toString(5) returns a string object containing 5 in it.


Q25. How can you get environment variables?

Ans. An application uses System.getEnv to retrieve environment variable values. Without an argument, getEnv returns a read-only instance of java.util.Map, where the map keys are the environment variable names, and the map values are the environment variable values.

Q26. How will you get the platform dependent values like line separator, path separator, etc.?
Ans. Using Sytem.getProperty(…) (line.separator, path.separator, …)

Q27. Can we pass a new-line ('\n') character or any other escape sequence via command line in Java?
Ans. No. The question arises, if you pass the same escape sequence programmatically, it works fine, so why doesn't it work well when passed via command line.

Ex: System.setProperty("line.separator", " Bye!\nBBye!"); will work fine, but if try to do the same via command line as (java -Dline.separator=" Bye!\nBBye!" ClassName) then '\n' will be treated as two distinct ASCII characters ('\' and 'n') and not as a single escape sequence new-line Unicode character.

This behaviour was logged as a bug on Sun's Bug Database. But, it was closed saying 'not a bug'. The reason given is that interpretation of text passed on command line is a shell specific stuff and it is not reasonable to expect that to work in lines with the handling of escape sequences by any particular programming language.

It's not something to do with Java as even if you pass a command line argument having '\n' to a C program, it will be treated as two distinct ASCII characters only and not as a escape sequence.

Q28. How to define it a pattern and match it against a string.
Ans. The java.util.regex package primarily consists of three classes:
           PatternMatcher, and PatternSyntaxException.
- A Pattern object is a compiled representation of a regular expression. The Pattern class provides no public constructors. To create a pattern, you must first invoke one of its public static compile methods, which will then return a Pattern object. These methods accept a regular expression as the first argument.

- A Matcher object is the engine that interprets the pattern and performs match operations against an input string. Like the Pattern class, Matcher defines no public constructors. You obtain a Matcher object by invoking the static matcher method on a Pattern object.


- A PatternSyntaxException object is an unchecked exception that indicates a syntax error in a regular expression pattern.


Q29. How can you specify union, intersection & subtraction in regular expressions.

Ans:
Union: To create a union, simply nest one class inside the other, such as [0-4[6-8]]. This particular union creates a single character class that matches the numbers 0, 1, 2, 3, 4, 6, 7, and 8.

Intersection: To create a single character class matching only the characters common to all of its nested classes, use &&, as in [0-9&&[345]]. This particular intersection creates a single character class matching only the numbers common to both character classes: 3, 4, and 5


Subtraction: Finally, you can use subtraction to negate one or more nested character classes, such as [0-9&&[^345]]. This example creates a single character class that matches everything from 0 to 9, except the numbers 3, 4, and 5.


Q30. Explain assertions.

Ans. An assertion is a statement in the Java programming language that enables you to test your assumptions about your program. Ex: If you write a method that calculates the speed of a particle, you might assert that the calculated speed is less than the speed of light.

Each assertion contains a boolean expression that you believe will be true when the assertion executes. If it is not true, the system will throw an error. By verifying that the boolean expression is indeed true, the assertion confirms your assumptions about the behavior of your program, increasing your confidence that the program is free of errors.


Simpler form of assertion is assert Expression1; where Expression1 is a boolean expression. When the system runs the assertion, it evaluates Expression1 and if it is false throws an AssertionError with no detail message.


Q31: Explain some of the new features in J2SE 5.0, which improves ease of development?

Ans : The J2SE 5.0 release is focused along the key areas of ease of development, scalability, performance, quality, etc. The new features include
1. Generics
2. Metadata (aka annotations)
3. Autoboxing and auto-unboxing of primitive types
4. Enhanced “for” loop
5. Enums i.e. enumerated type
6. static import
7. C style formatted output and formatted input
8. varargs
9. New I/O which is non blocking: Scanner API provide a more robust mechanism for reading in data types rather than simply parsing strings from buffered System.in calls. Prior to Scanner feature was introduced, to read from standard input it would be necessary to write exception handling code and wrap an InputStreamReader and a BufferedReader around System.in. Scanner class throws an unchecked exception InputMismatchException, which you could optionally catch. Scanner API simplifies your code as follows:

//read from keyboard using the java.util.ScannerScanner

keyboard = new Scanner(System.in);
System.out.println("Enter your first number?");
int i1 = keyboard.nextInt();

Q32. What is phantom memory?

Ans. Phantom memory is false memory, one that does not exist in reality.

Q33. What is the GregorianCalendar class?

Ans. The GregorianCalendar provides support for traditional Western calendars.

Q34. What is the ResourceBundle class?

Ans. ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program’s appearance to the particular locale in which it is being run.

Q35. What is reflection in Java?

Ans. Java Reflection is a technology that looks inside a Java object at runtime and sees what variables it contains, what methods it supports, what interfaces it implements, what classes it extends - basically everything about the object that you would know at compile time.

Q36. What is the difference between instanceof and isInstance?

Ans.
instanceof - Used to check to see if an object can be cast into a specified type without throwing a cast class exception.
isInstance() - Determines if specified object is assignment-compatible with the object represented by this Class.

Instanceof() is a reserved word of Java, but isInstance() is a method of java.lang.Class. isInstance() method is dynamic equivalent of instanceof operator. The method returns true if the specified Object argument is non-null and can be cast to the reference type represented by this Class object without raising a ClassCastException and false otherwise. If argument is null, method returns false.


In instanceof operator, you can compare it to a named type only, and not to a Class object. Like, there is no way to cleverly automate objects by creating a Vector of Class objects and comparing it to those. isInstance() remove this problem and call instanceof() operator dynamically.


You could use instanceof() on types (which are known on compile time), and isInstance() could only be called on an instance of java.lang.Class.

if (obj instanceof MyType) {
     ...
}

if (MyType.class.isInstance(obj)) {

      ...
}

So you can have dynamism using isInstance() as given below. You could check the type of an object with an unknown class during compile time! 



Class x = Integer.class;
if (x.isInstance(obj)) {
    ...
}

x = String.class;
if (x.isInstance(obj)) {
    ...
}

Q37. Explain type.getConstructor(int.class).newInstance()?
Ans. type -> A class whose constructor is to be retrieved
        int.class -> Constructor accepting an integer argument
        newInstance() -> Create a object of type “type”, with constructor obtained.

The newlnstance() method of Class is a way to implement a "virtual constructor," which allows you to say, "I don’t know exactly what type you are, but create yourself properly anyway." And when you create a new instance, you get back an Object reference. In addition, the class that’s being created with newlnstance() must have a default constructor.


Q38. What is a native method?
Ans. A native method is a method that is implemented in a language other than Java.

Q39. Explain annotations.
Ans. It’s a way to introduce meta-data with the program.3 annotations are:
1. @Deprecated – @deprecated used to serve the same purpose before introduction of annotations.
2. @Override
3. @SuppressWarnings (type)
2 and 3 are new annotations introduced.


One can define its own annotations. Annotation type declarations are similar to normal interface declarations. An at-sign (@) precedes the interface keyword. Each method declaration defines an element of the annotation type. Method declarations must not have any parameters or a throws clause. Return types are restricted to primitives, String, Class, 

enums, annotations, and arrays of the preceding types. Methods can have default values.

Here is an example annotation type declaration:

/* Describes the RequestForEnhancement(RFE) that led to the presence of the annotated API element.
*/
public @interface RequestForEnhancement {
      int id();

      String synopsis();
      String engineer() default "[unassigned]";
      String date(); default "[unimplemented]";
}

@RequestForEnhancement(

      id = 2868724,
      synopsis = "Enable time-travel",
      engineer = "Mr. Peabody",
)


Once an annotation type is defined, you can use it to annotate declarations. An annotation is a special kind of modifier, and can be used anywhere that other modifiers (such as public, static, or final) can be used. By convention, annotations precede other modifiers. Annotations consist of an at-sign (@) followed by an annotation type and a parenthesized list of element-value pairs. The values must be compile-time constants. Here is a method declaration with an annotation corresponding to the annotation type declared above.


Q40. Hot deployment & dynamic reloading

Ans. Hot deployment is the process of adding new components (such as WAR files, EJB Jar files, enterprise Java beans, servlets, and JSP files) to a running server without having to stop the application server process and start it again.

Dynamic reloading is the ability to change an existing component without needing to restart the server in order for the change to take effect. Dynamic reloading involves:

a. Changes to the implementation of a component of an application, such as changing the implementation of a servlet.
b. Changes to the settings of the application, such as changing the deployment descriptor for a Web module

Although hot deploy seems a good feature, it's not natively supported by the Java Virtual Machine (JVM) because. Once a given class is defined by a ClassLoader it cannot be redefined. That's where a custom class loader enters. The idea is simple, exploit the JVM behaviour.


Classes are not only identified by its package name and class name, but also by the class loader instance that defined the class. Hence, using a new instance when needed will allow the developer to load the new class version into the JVM. It might sound simple, but the process itself has implications regarding how to deal the new class casting. Other problems related with the use of class loaders are:

a. Memory usage: Various definitions of classes will be loaded into memory, since new class loaders instances keep defining new versions of classes.
b. The possible scenario of old instances and new instances co-existing, this is especially problematic if object serialization is being used.

Hot Deployment

Web containers commonly have a special directory (e.g. “webapps” in Tomcat, “deploy” in JBoss) that is periodically scanned for new web applications or changes to the existing ones. When the scanner detects that a deployed .WAR is updated, the scanner causes a redeploy to happen (in Tomcat it calls the StandardContext.reload() method). Since this happens without any additional action on the user’s side it is commonly referred to “Hot Deployment”.

Hot Deployment is supported by all wide-spread application servers under different names: autodeployment, rapid deployment, autopublishing, hot reload, and so on. In some containers, instead of moving the archive to a predefined directory you can configure the server to monitor the archive at a specific path. Often the redeployment can be triggered from the IDE (e.g. when the user saves a file) thus reloading the application without any additional user involvement. Although the application is reloaded transparently to the user, it still takes the same amount of time as when hitting the “Reload” button in the admin console, so code changes are not immediately visible in the browser.


Q41. What major patterns do the Java APIs utilize?

Ans. Design patterns are used and supported extensively throughout the Java APIs. Here are some examples:
1. MVC pattern: Used extensively throughout the Swing API.
2. Factory Method Design Pattern: Used in getInstance() method in java.util.Calendar
3. Singleton Pattern: Classes java.lang.System and java.sql.DriverManager, though they are not implemented using the approach recommended in the GoF book but with static methods.
4. Prototype Pattern: Supported in Java through the clone() method defined in class Object and the use of java.lang.Cloneable interface to grant permission for cloning.
5. Command Pattern: The Java Swing classes support the Command pattern by providing an Action interface and an AbstractAction class.
6. Observer Pattern: The Java 1.1 event model is based on the observer pattern. In addition, the interface java.util.Observable and the class java.util.Observer provide support for this pattern.
7. Adapter Pattern: Used extensively by the adapter classes in java.awt.event.
8. Proxy Pattern: Used extensively in the implementation of Java's Remote Method Invocation (RMI) and Interface Definition Language (IDL) features.
9. Composite Pattern: The structure of Component and Container classes in java.awt provide a good example of the Composite pattern.
10. Bridge Pattern: The Bridge pattern can be found in the separation of the components in java.awt (e.g., Button and List), and their counterparts in java.awt.peer.

Q42. Which patterns were used by Sun in designing the Enterprise JavaBeans model

Ans. Many design patterns were used in EJB, and some of them are clearly identifiable by their naming convention. Here are several:
1. Factory Method: Define a interface for creating classes, let a subclass (or a helper class) decide which class to instantiate.
This is used in EJB creation model. EJBHome defines an interface for creating the EJBObject implementations. They are actually created by a generated container class. See InitialContextFactory interface that returns an InitialContext based on a properties hashtable.

2. Singleton: Ensure a class has only one instance, and provide a global point of access to it. There are many such classes. One example is javax.naming.NamingManager


3. Abstract Factory: Provide an interface for creating families of relegated or dependent objects without specifying their concrete classes.We have interfaces called InitialContext, InitialContextFactory. InitialContextFactory has methods to get InitialContext.


4. Builder: Separate the construction of a complex factory from its representation so that the same construction process can create different representations. InitialContextFactoryBuilder can create a InitialContextFactory.


5. Adapter: Convert the interface of a class into another interface clients expect.In the EJB implementation model, we implement an EJB in a class that extends SessionBean or a EntityBean. We don't directly implement the EJBObject/home interfaces. EJB container generates a class that adapts the EJBObject interface by forwarding the calls to the enterprise bean class and provides declarative transaction, persistence support.


6. Proxy: Provide a surrogate for other object to control access to it. We have remote RMI-CORBA proxies for the EJB's.


7. Memento: Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later.


Q43. Which design pattern does I/O classes use?

Ans. I/O classes use Decorator design pattern. The decorator design pattern attaches responsibilities to objects at runtime. Decorators are more flexible than inheritance because inheritance attaches responsibility to classes at compile time. The java.io.* classes use the decorator pattern to construct different combinations of behaviour at runtime based on some basic classes.

Q44. Explain the Java I/O streaming concept and the use of the decorator design pattern in Java I/O?
Ans: Java input and output is defined in terms of an abstract concept called a “stream”, which is a sequence of data. There are 2 kinds of streams.
1. Byte streams (8 bit bytes) -> Abstract classes are: InputStream and OutputStream
2. Character streams (16 bit UNICODE) -> Abstract classes are: Reader and Writer

Design pattern: java.io.* classes use the decorator design pattern. The decorator design pattern attaches responsibilities to objects at run time. Decorators are more flexible than inheritance because the inheritance attaches responsibility to classes at compile time. The java.io.* classes use the decorator pattern to construct different combinations of behavior at run time based on some basic classes.

Q45. Loading, Linking and Initialization
Ans. 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:
1. Loading: finding and importing the binary data for a type

2. Linking: performing verification, preparation, and (optionally) resolution
   a. Verification: ensuring the correctness of the imported type
   b. Preparation: allocating memory for class variables and initializing the memory to default values
   c. Resolution: transforming symbolic references from the type into direct references.


3. Initialization: Invoking Java code that initializes class variables to their proper starting values.


Q46. What happens when you call Class.forName() method?
Ans. Creating a reference to a Class object using ".class" doesn’t automatically initialize the Class object. However, Class.forName() initializes the class immediately in order to produce the Class reference There are actually three steps in preparing a class for use:
1. Loading: It is performed by the class loader. This finds the bytecodes and creates a Class object from those bytecodes.
2. Linking: The link phase verifies the bytecodes in the class, allocates storage for static fields, and if necessary, resolves all references to other classes made by this class.
3. Initialization: If there’s a superclass, initialize that. Execute static initializers and static initialization blocks.

If a static final value is a "compile-time constant" that value can be read without causing the class to be initialized. Making a field static and final, however, does not guarantee this behaviour. However, if static final variable value is calculated at run time, it forces class initialization because it cannot be a compile-time constant.

If a static field is NOT final, accessing it always requires linking (to allocate storage for the field) and initialization (to initialize that storage) before it can be read.

Q47. Explain Java class loaders? If you have a class in a package, what do you need to do to run it? Explain dynamic class loading?
Ans: Class loaders are hierarchical. Classes are introduced into the JVM as they are referenced by name in a class that is already running in the JVM. So, how is the very first class loaded? The very first class is especially loaded with the help of static main() method declared in your class. All the subsequently loaded classes are loaded by the classes, which are already loaded and running. A class loader creates a namespace. All JVMs include at least one class loader that is embedded within the JVM called the primordial (or bootstrap) class loader. Now let’s look at non-primordial class loaders. The JVM has hooks in it to allow user defined class loaders to be used in place of primordial class loader. Let us look at the class loaders created by the JVM.                        CLASS LOADERS                                                                       RELOADABLE                                                                                     EXPLAINATION

BootStrap(Primordial)
No
Loads JDK internal classes, java.* packages. (as defined in the sun.boot.class.path system property, typically loads rt.jar and i18n.jar)
Extensions
No
Loads jar files from JDK extensions directory (as defined in the java.ext.dirs system property – usually lib/ext directory of the JRE)
System
No
Loads classes from system classpath (as defined by the java.class.path property, which is set by the CLASSPATH environment variable or –classpath or –cp command line
options)

Bootstrap
(primordial)
(rt.jar, i18.jar)
           /|\
            |
Extensions
(lib/ext)
           /|\
            |
System
(-classpath)
           /|\
            |
[Sibling1 classloader]              [Sibling1 classloader]

Class loaders are hierarchical and use a delegation model when loading a class. Class loaders request their parent to load the class first before attempting to load it themselves. When a class loader loads a class, the child class loaders in the hierarchy will never reload the class again. Hence uniqueness is maintained. Classes loaded by a child class loader have visibility into classes loaded by its parents up the hierarchy but the reverse is not true as explained in the above diagram.

Hence,

1.) Classes loaded by Bootstrap class loader have NO visibility into classes loaded by its descendants (ie Extensions and Systems class loaders).
2.) The classes loaded by system class loader have visibility into classes loaded by its parents (ie Extensions and Bootstrap class loaders).
3.) If there were any sibling class loaders they cannot see classes loaded by each other. They can seen only by classes loaded by their parent class loader.

For example Sibling1 class loader cannot see classes loaded by Sibling2 class loader Both Sibling1 and Sibling2 class loaders have visibilty into classes loaded by their parent class loaders (eg: System, Extensions, and Bootstrap).

In the general case, when a thread runs the code of class A and comes across a reference for class B, it attempts to load the code for class B from the same classloader that loaded class A (or one of that classloader's ancestors in the classloading hierarchy). This approach is taken irrespective of which threads or classloaders were originally involved in loading class A. A classloader knows only about its ancestors, not its descendants.


Q48. Can two objects loaded by different class loaders be same?
Ans. Two objects loaded by different class loaders are never equal even if they carry the same values, which mean a class is uniquely identified in the context of the associated class loader. This applies to singletons too, where each class loader will have its own singleton.

Q49. Explain about context Class loaders.
Ans. Threads interact with the classloader in one particular case. Each thread is assigned a specific classloader known as the context classloader. This classloader is retrieved with the getContextClassLoader() method and set with the setContextClassLoader() method.

The context classloader only comes into play with certain internal classes in the virtual machine. 

Q50. Explain static vs. dynamic class loading?
Ans.
Static class loading
 Dynamic class loading
Classes are statically loaded with Java’s “new” operator.
class MyClass {
          public static void main(String args[]) {
                   Car c = new Car();
          }
}
Dynamic loading is a technique for programmatically invoking the functions of a class loader at run time. Let us look at how to load classes dynamically.

Class.forName (String className); //static method which returns a Class

The above static method returns the class object associated with the class
name. The string className can be supplied dynamically at run time. Unlike the static loading, the dynamic loading will decide whether to load the class Car or the class Jeep at runtime based on a properties file and/or other runtime conditions. Once the class is dynamically loaded the following method returns an instance of the loaded class. It’s just like creating a class object with no arguments.
class.newInstance (); //A non-static method, which creates an instance of a
//class (i.e. creates an object).

Jeep myJeep = null ;
//myClassName should be read from a .properties file or a Constants class.
// stay away from hard coding values in your program. CO
String myClassName = "au.com.Jeep" ;
Class vehicleClass = Class.forName(myClassName) ;
myJeep = (Jeep) vehicleClass.newInstance();
myJeep.setFuelCapacity(50);
A NoClassDefFoundException is thrown if a class is referenced with Java’s “new” operator (i.e. static loading) but the runtime system cannot find the referenced class.
A ClassNotFoundException is thrown when an application tries to load in a
class through its string name using the following methods but no definition for the class with the specified name could be found:
      The forName(..) method in class - Class.
      The findSystemClass(..) method in class - ClassLoader.
      The loadClass(..) method in class - ClassLoader.

Q51. Towers of Hanoi Problem Solution

Stable sorts
count sort, merge sort, bubble sort, radix sort, insertion sort, binary tree sort

Non stable sorts
quick sort, heap sort, selection sort, shell sort

Burstsort and its variants are cache-efficient algorithms for sorting strings and are faster than quicksort and radix sort for large data sets. Burstsort algorithms use tries to store prefixes of strings, with growable arrays of pointers as end nodes containing sorted, unique, suffixes (referred to as buckets). Some variants copy the string tails into the buckets. As the buckets grow beyond a predetermined threshold, the buckets are "burst", giving the sort its name. A more recent variant uses a bucket index with smaller sub-buckets to reduce memory usage. Most implementations delegate to multi key quicksort, an extension of three-way radix quicksort, to sort the contents of the buckets. By dividing the input into buckets with common prefixes, the sorting can be done in a cache-efficient manner.

Max subarray problem
1-d ->  http://en.wikipedia.org/wiki/Maximum_subarray_problem

Big Endian: MSB’s at beginning