Diff Between JDK 1.4 and 1.5Interview Question

Embed Size (px)

Citation preview

  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    1/38

    1. What is the latest version of JDK available in the market?

    2. What is the difference between the JDK 1.4 and 1.5?

    3. What is the feature of the JDK 1.5?

    Generics

    This long-awaited enhancement to the type system allows a type or method

    to operate on objects of various types while providing compile-time typesafety. It adds compile-time type safety to the Collections Framework and

    eliminates the drudgery of casting.

    When you take an element out of a Collection, you must cast it to the type ofelement that is stored in the collection. Besides being inconvenient, this is

    unsafe. The compiler does not check that your cast is the same as thecollection's type, so the cast can fail at run time.

    Generics provides a way for you to communicate the type of a collection tothe compiler, so that it can be checked. Once the compiler knows the element

    type of the collection, the compiler can check that you have used thecollection consistently and can insert the correct casts on values being taken

    out of the collection.

    Enhanced for Loop ;

    This new language construct eliminates the drudgery and error-proneness of

    iterators and index variables when iterating over collections and arrays.

    Iterating over a collection is uglier than it needs to be. Consider the followingmethod, which takes a collection of timer tasks and cancels them:

    void cancelAll(Collection c) {

    for (Iterator i = c.iterator(); i.hasNext();)i.next().cancel();

    }

    The iterator is just clutter. Furthermore, it is an opportunity for error. Theiterator variable occurs three times in each loop: that is two chances to get it

    wrong. The for-each construct gets rid of the clutter and the opportunity forerror. Here is how the example looks with the

    for-each construct:void cancelAll(Collection c) {

    for (TimerTask t : c)

    t.cancel();}

    When you see the colon (:) read it as in. The loop above reads as for each

    TimerTask t in c. As you can see, the for-each construct combines beautifullywith generics. It preserves all of the type safety, while removing the

    http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.htmlhttp://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.htmlhttp://java.sun.com/j2se/1.5.0/docs/guide/language/generics.htmlhttp://java.sun.com/j2se/1.5.0/docs/guide/language/generics.htmlhttp://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.htmlhttp://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html
  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    2/38

    remaining clutter. Because you don't have to declare the iterator, you don'thave to provide a generic declaration for it. (The compiler does this for you

    behind your back, but you need not concern yourself with it.)

    Autoboxing/Unboxing

    This facility eliminates the drudgery of manual conversion between primitive

    types (such as int) and wrapper types (such as Integer).

    As any Java programmer knows, you cant put an int (or other primitivevalue) into a collection. Collections can only hold object references, so you

    have to boxprimitive values into the appropriate wrapper class (which isInteger in the case of int). When you take the object out of the collection, you

    get the Integer that you put in; if you need an int, you must unboxtheInteger using the intValue method. All of this boxing and unboxing is a pain,

    and clutters up your code. The autoboxing and unboxing feature automatesthe process, eliminating the pain and the clutter.

    The following example illustrates autoboxing and unboxing, along withgenerics and the for-each loop. In a mere ten lines of code, it computes and

    prints an alphabetized frequency table of the words appearing on thecommand line.

    import java.util.*;

    // Prints a frequency table of the words on the command line

    public class Frequency {public static void main(String[] args) {

    Map m = new TreeMap();

    for (String word : args) {Integer freq = m.get(word);

    m.put(word, (freq == null ? 1 : freq + 1));}System.out.println(m);

    }}

    java Frequency if it is to be it is up to me to do the watusi

    {be=1, do=1, if=1, is=2, it=2, me=1, the=1, to=3, up=1, watusi=1}

    The program first declares a map from String to Integer, associating thenumber of times a word occurs on the command line with the word. Then it

    iterates over each word on the command line. For each word, it looks up theword in the map. Then it puts a revised entry for the word into the map. The

    line that does this (highlighted in green) contains both autoboxing andunboxing. To compute the new value to associate with the word, first it looks

    at the current value (freq). If it is null, this is the first occurrence of the word,so it puts 1 into the map. Otherwise, it adds 1 to the number of prior

    occurrences and puts that value into the map. But of course you cannot putan int into a map, nor can you add one to an Integer. What is really

    happening is this: In order to add 1 to freq, it is automatically unboxed,resulting in an expression of type int. Since both of the alternative

    expressions in the conditional expression are of type int, so too is the

    http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/lang/Integer.htmlhttp://java.sun.com/j2se/1.5.0/docs/guide/language/generics.htmlhttp://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.htmlhttp://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/lang/Integer.htmlhttp://java.sun.com/j2se/1.5.0/docs/guide/language/generics.htmlhttp://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html
  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    3/38

    conditional expression itself. In order to put this int value into the map, it isautomatically boxed into an Integer.

    Typesafe Enums

    This flexible object-oriented enumerated type facility allows you to create

    enumerated types with arbitrary methods and fields. It provides all thebenefits of the Typesafe Enum pattern ("Effective Java," Item 21) without the

    verbosity and the error-proneness.

    In prior releases, the standard way to represent an enumerated type was theint Enum pattern:

    // int Enum Pattern - has severe problems!public static final int SEASON_WINTER = 0;

    public static final int SEASON_SPRING = 1;public static final int SEASON_SUMMER = 2;

    public static final int SEASON_FALL = 3;This pattern has many problems, such as:

    Not typesafe - Since a season is just an int you can pass in any other intvalue where a season is required, or add two seasons together (which

    makes no sense).

    No namespace - You must prefix constants of an int enum with a string

    (in this case SEASON_) to avoid collisions with other int enum types.

    Brittleness - Because int enums are compile-time constants, they arecompiled into clients that use them. If a new constant is added between

    two existing constants or the order is changed, clients must berecompiled. If they are not, they will still run, but their behavior will be

    undefined.

    Printed values are uninformative - Because they are just ints, if youprint one out all you get is a number, which tells you nothing about what

    it represents, or even what type it is.

    It is possible to get around these problems by using the Typesafe Enumpattern (see Effective Java Item 21), but this pattern has its own problems: It

    is quite verbose, hence error prone, and its enum constants cannot be used inswitch statements.

    In 5.0, the Java programming language gets linguistic support forenumerated types. In their simplest form, these enums look just like their C,

    C++, and C# counterparts:enum Season { WINTER, SPRING, SUMMER, FALL }

    But appearances can be deceiving. Java programming language enums arefar more powerful than their counterparts in other languages, which are little

    more than glorified integers. The new enum declaration defines a full-fledgedclass (dubbed an enum type). In addition to solving all the problems

    mentioned above, it allows you to add arbitrary methods and fields to an

    enum type, to implement arbitrary interfaces, and more. Enum types providehigh-quality implementations of all the Object methods. They are Comparable

    and Serializable, and the serial form is designed to withstand arbitrarychanges in the enum type.

    http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.htmlhttp://java.sun.com/docs/books/effective/http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.htmlhttp://java.sun.com/docs/books/effective/
  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    4/38

    Varargs

    This facility eliminates the need for manually boxing up argument lists into an

    array when invoking methods that accept variable-length argument lists.

    In past releases, a method that took an arbitrary number of values required

    you to create an array and put the values into the array prior to invoking themethod. For example, here is how one used the MessageFormat class to

    format a message:

    Object[] arguments = {

    new Integer(7),new Date(),

    "a disturbance in the Force"};

    String result = MessageFormat.format(

    "At {1,time} on {1,date}, there was {2} on planet "+ "{0,number,integer}.", arguments);

    It is still true that multiple arguments must be passed in an array, but the

    varargs feature automates and hides the process. Furthermore, it is upwardcompatible with preexisting APIs. So, for example, the MessageFormat.format

    method now has this declaration:

    public static String format(String pattern,Object... arguments);

    The three periods after the final parameter's type indicate that the final

    argument may be passed as an array oras a sequence of arguments. Varargscan be used onlyin the final argument position. Given the new varargs

    declaration for MessageFormat.format, the above invocation may be replacedby the following shorter and sweeter invocation:

    String result = MessageFormat.format(

    "At {1,time} on {1,date}, there was {2} on planet "+ "{0,number,integer}.",

    7, new Date(), "a disturbance in the Force");

    Static Import

    This facility lets you avoid qualifying static members with class names without

    the shortcomings of the "Constant Interface antipattern."

    In order to access static members, it is necessary to qualify references withthe class they came from. For example, one must say:

    double r = Math.cos(Math.PI * theta);In order to get around this, people sometimes put static members into an

    interface and inherit from that interface. This is a bad idea. In fact, it's such abad idea that there's a name for it: the Constant Interface Antipattern (see

    Effective Java Item 17). The problem is that a class's use of the static

    http://java.sun.com/j2se/1.5.0/docs/guide/language/varargs.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/text/MessageFormat.htmlhttp://java.sun.com/j2se/1.5.0/docs/guide/language/static-import.htmlhttp://java.sun.com/docs/books/effective/http://java.sun.com/j2se/1.5.0/docs/guide/language/varargs.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/text/MessageFormat.htmlhttp://java.sun.com/j2se/1.5.0/docs/guide/language/static-import.htmlhttp://java.sun.com/docs/books/effective/
  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    5/38

    members of another class is a mere implementation detail. When a classimplements an interface, it becomes part of the class's public API.

    Implementation details should not leak into public APIs.

    The static import construct allows unqualified access to static memberswithoutinheriting from the type containing the static members. Instead, the

    program imports the members, either individually:

    import static java.lang.Math.PI;or en masse:

    import static java.lang.Math.*;Once the static members have been imported, they may be used without

    qualification:double r = cos(PI * theta);

    The static import declaration is analogous to the normal import declaration.Where the normal import declaration imports classes from packages, allowing

    them to be used without package qualification, the static import declarationimports static members from classes, allowing them to be used without class

    qualification.

    So when should you use static import? Very sparingly! Only use it when

    you'd otherwise be tempted to declare local copies of constants, or to abuseinheritance (the Constant Interface Antipattern). In other words, use it when

    you require frequent access to static members from one or two classes. If you

    overuse the static import feature, it can make your program unreadable andunmaintainable, polluting its namespace with all the static members you

    import. Readers of your code (including you, a few months after you wrote it)will not know which class a static member comes from. Importing allof the

    static members from a class can be particularly harmful to readability; if you

    need only one or two members, import them individually. Used appropriately,static import can make your program more readable, by removing the

    boilerplate of repetition of class names.

    Metadata (Annotations)

    This language feature lets you avoid writing boilerplate code under

    many circumstances by enabling tools to generate it from annotations in thesource code. This leads to a "declarative" programming style where the

    programmer says what should be done and tools emit the code to do it. Also

    it eliminates the need for maintaining "side files" that must be kept up to datewith changes in source files. Instead the information can be maintained in the

    source file.

    Many APIs require a fair amount of boilerplate code. For example, in order to

    write a JAX-RPC web service, you must provide a paired interface andimplementation. This boilerplate could be generated automatically by a tool if

    the program were decorated with annotations indicating which methodswere remotely accessible.

    Other APIs require side files to be maintained in parallel with programs. Forexample JavaBeans requires a BeanInfo class to be maintained in parallel with

    http://java.sun.com/j2se/1.5.0/docs/guide/language/annotations.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/beans/BeanInfo.htmlhttp://java.sun.com/j2se/1.5.0/docs/guide/language/annotations.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/beans/BeanInfo.html
  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    6/38

    a bean, and Enterprise JavaBeans (EJB) requires a deployment descriptor. Itwould be more convenient and less error-prone if the information in these

    side files were maintained as annotations in the program itself.The Java platform has always had various ad hoc annotation mechanisms. For

    example the transient modifier is an ad hoc annotation indicating that a fieldshould be ignored by the serialization subsystem, and the @deprecated

    javadoc tag is an ad hoc annotation indicating that the method should nolonger be used. As of release 5.0, the platform has a general purpose

    annotation (also known as metadata) facility that permits you to define and

    use your own annotation types. The facility consists of a syntax for declaringannotation types, a syntax for annotating declarations, APIs for reading

    annotations, a class file representation for annotations, and an annotation

    processing tool.Annotations do not directly affect program semantics, but they do affect the

    way programs are treated by tools and libraries, which can in turn affect thesemantics of the running program. Annotations can be read from source files,

    class files, or reflectively at run time.Annotations complement javadoc tags. In general, if the markup is intended

    to affect or produce documentation, it should probably be a javadoc tag;

    otherwise, it should be an annotation.

    4. How Generics and Enhanced loop works? (in JDK 1.5)

    Generics:

    Generics are a facility ofgeneric programming that was added to the

    Java programming language in 2004 as part ofJ2SE 5.0. They allow "a

    type or method to operate on objects of various types while providingcompile-time type safety.

    A type variable is an unqualified identifier. Type variables areintroduced by generic class declarations, generic interface

    declarations, generic method declarations, and by generic constructordeclarations.

    A class is generic if it declares one or more type variables.

    These type variables are known as the type parameters of the class. Itdefines one or more type variables that act as parameters. A generic

    class declaration defines a set of parameterized types, one for eachpossible invocation of the type parameter section. All of these

    parameterized types share the same class at runtime.

    An interface is generic if it declares one or more type variables.

    These type variables are known as the type parameters of theinterface. It defines one or more type variables that act as parameters.A generic interface declaration defines a set of types, one for each

    possible invocation of the type parameter section. All parameterizedtypes share the same interface at runtime.

    A method is generic if it declares one or more type variables.

    These type variables are known as the formal type parameters of themethod. The form of the formal type parameter list is identical to a

    type parameter list of a class or interface.

    http://java.sun.com/j2se/1.5.0/docs/guide/apt/index.htmlhttp://java.sun.com/j2se/1.5.0/docs/guide/apt/index.htmlhttp://en.wikipedia.org/wiki/Generic_programminghttp://en.wikipedia.org/wiki/Java_(programming_language)http://en.wikipedia.org/wiki/Java_Platform,_Standard_Editionhttp://java.sun.com/j2se/1.5.0/docs/guide/apt/index.htmlhttp://java.sun.com/j2se/1.5.0/docs/guide/apt/index.htmlhttp://en.wikipedia.org/wiki/Generic_programminghttp://en.wikipedia.org/wiki/Java_(programming_language)http://en.wikipedia.org/wiki/Java_Platform,_Standard_Edition
  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    7/38

    A constructor can be declared as generic, independently ofwhether the class the constructor is declared in is itself generic. A

    constructor is generic if it declares one or more type variables. These

    type variables are known as the formal type parameters of theconstructor. The form of the formal type parameter list is identical to a

    type parameter list of a generic class or interface.

    [edit] Motivation for generics

    The following block of Java code illustrates a problem that exists whennot using generics. First, it declares an ArrayList of type Object. Then,

    it adds a String to the ArrayList. Finally, it attempts to retrieve theadded String and cast it to an Integer.

    List v = new ArrayList();

    v.add("test");Integer i = (Integer)v.get(0);

    Although the code compiles without error, it throws a runtimeexception (java.lang.ClassCastException) when executing the third lineof code. This type of problem can be avoided by using generics and is

    the primary motivation for using generics.

    Using generics, the above code fragment can be rewritten as follows:

    List v = new ArrayList();v.add("test");

    Integer i = v.get(0); // (type error)

    The type parameter String within the angle brackets declares the

    ArrayList to be constituted of Strings (a descendant of the ArrayList'sgeneric Object constituents). With generics, it is no longer necessary

    to cast the third line to any particular type, because the result ofv.get(0) is defined as String by the code generated by the compiler.

    Compiling the third line of this fragment with J2SE 5.0 (or later) willyield a compile-time error because the compiler will detect that

    v.get(0) returns String instead of Integer. For a more elaborateexample, see [3].

    [edit] Wildcards

    Generic type parameters in Java are not limited to specific classes.Java allows the use ofwildcards to specify bounds on the type of

    parameters a given generic object may have. Wildcards are typeparameters of the form "?", possibly annotated with a bound. Given

    that the exact element type of an object with a wildcard is unknown,restrictions are placed on the type of methods that may be called on

    the object.

    http://en.wikipedia.org/w/index.php?title=Generics_in_Java&action=edit&section=2http://en.wikipedia.org/wiki/Generics_in_Java#cite_note-2%23cite_note-2http://en.wikipedia.org/w/index.php?title=Generics_in_Java&action=edit&section=3http://en.wikipedia.org/w/index.php?title=Generics_in_Java&action=edit&section=2http://en.wikipedia.org/wiki/Generics_in_Java#cite_note-2%23cite_note-2http://en.wikipedia.org/w/index.php?title=Generics_in_Java&action=edit&section=3
  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    8/38

    As an example of an unbounded wildcard, List indicates a listwhich has an unknown object type. Methods which take such a list as

    an argument can take any type of list, regardless of parameter type.Reading from the list will return objects of type Object, and writing

    non-null elements to the list is not allowed, since the parameter typeis not known.

    To specify the upper bound of a generic element, the extends keyword

    is used, which indicates that the generic type is a subtype of the

    bounding class. Thus it must either extend the class, or implement theinterface of the bounding class. So List

  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    9/38

    So what does an enhanced for loop look like? Suppose you have acollection of TechTip objects called RecentTips. You could use an

    enhanced for loop with the collection as follows:

    for (TechTip tip: RecentTips)

    You read this as "for each TechTip in RecentTips". Here the variable tipis used to point to the current instance of TechTip in the collection.

    Because of the "for each" wording, the enhanced-for construct is alsoreferred to as the for-each construct.

    If you compare the enhanced for loop to the typical way of iteratingover a collection, it's clear that the for each loop is simpler and can

    make your code more readable.

    Also note that the enhanced for loop is designed to simplify your work

    with generics. Although this tip does include two examples of using theenhanced for loop with generics, it's not the focus of the tip. Instead

    the objective of this tip is to introduces you to the more basic changesyou can make to your code to use the for each loop.

    5. What is the Inner class?

    An inner class is a class that is defined within the definition of another classbut outside any member definition. Inner classes should not be marked

    static.An Inner class cannot be instantiated directly, i.e. one can only instantiate

    an inner class by first instantiating the outer class. The Inner class hasaccess to all the static as well as non-static public/protected/private fields of

    its enclosing outer class.Inner classes are used to provide implementation that are intimately

    connected with the enclosing outer class.

    An instance of a normal or top-level class can exist on its own. By contrast,

    an instance of an inner class cannot be instantiated without being bound toa top-level class.

    Let us take the abstract notion of a Car with four wheels. Our wheels have a

    specific feature that relies on being part of our Car. This notion does not

    represent the wheels as wheels in a more general form that could be part ofvehicle. Instead it represents them as specific to this one. We can model

    this notion using inner classes as follows:

    We have the top-level class Car. Instances of Class Car are composed of

    four instances of the class Wheel. This particular implementation of Wheel isspecific to the car, so the code does not model the general notion of a

    Wheel which would be better represented as a top-level class. Therefore, itis semantically connected to the class Car and the code of Wheel is in some

    way coupled to its outer class.

  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    10/38

    Inner classes provide us with a mechanism to accurately model thisconnection. We say that our wheel class is Car.Wheel, Car being the top-

    level class and Wheel being the inner class.

    Inner classes therefore allow for the object orientation of certain parts ofthe program that would otherwise not be encapsulated into a class.

    Larger segments of code within a class might be better modeled or

    refactored as a separate top-level class, rather than an inner class. Thiswould make the code more general in its application and therefore more re-

    usable but potentially might be premature generalization. This may provemore effective if code has many inner classes with the shared functionality.

    [edit] Types of inner class

    In Java there are four types ofnested class:

    Static member class, also simply called nested class - They are

    declared static. Like other things in static scope, they do not have anenclosing instance, and cannot access instance variables and

    methods of the enclosing class. They are almost identical to non-nested classes except for scope details (they can refer to static

    variables and methods of the enclosing class without qualifying thename; other classes that are not one of its enclosing classes have to

    qualify its name with its enclosing class's name). Nested interfacesare implicitly static.

    Inner class - The following categories are called inner classes.Each instance of these classes has a reference to an enclosing

    instance (i.e. an instance of the enclosing class), except for local and

    anonymous classes declared in static context. Hence, they canimplicitly refer to instance variables and methods of the enclosing

    class. The enclosing instance reference can be explicitly obtained viaEnclosingClassName.this. Inner classes may not have static variables

    or methods, except for compile-time constant variables. When theyare created, they must have a reference to an instance of the

    enclosing class; which means they must either be created within aninstance method or constructor of the enclosing class, or (for

    member and anonymous classes) be created using the syntaxenclosingInstance.new InnerClass().

    o Member class - They are declared outside a function

    (hence a "member") and not declared "static".

    o Local class - These are classes which are declared in the

    body of a function. They can only be referred to in the rest of

    the function. They can use local variables and parameters ofthe function, but only ones which are declared "final". (This is

    because the local class instance must maintain a separate

    copy of the variable, as it may out-live the function; so as notto have the confusion of two modifiable variables with the

    same name in the same scope, the variable is forced to be

    non-modifiable.)o Anonymous class - These are local classes which are

    automatically declared and instantiated in the middle of an

    http://en.wikipedia.org/w/index.php?title=Inner_class&action=edit&section=2http://en.wikipedia.org/wiki/Java_(programming_language)http://en.wikipedia.org/wiki/Anonymous_classhttp://en.wikipedia.org/w/index.php?title=Inner_class&action=edit&section=2http://en.wikipedia.org/wiki/Java_(programming_language)http://en.wikipedia.org/wiki/Anonymous_class
  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    11/38

    expression. They can only directly extend one class orimplement one interface. They can specify arguments to the

    constructor of the superclass, but cannot otherwise have aconstructor

    4. What is the static keyword?

    There will be times when you will want to define a class member that

    will be used independently of any object of that class. Normally a

    class member must be accessed only in conjunction with an object of

    its class. However, it is possible to create a member that can be

    used by itself, without reference to a specific instance. To create

    such a member, precede its declaration with the keyword static.

    When a member is declared static, it can be accessed before any

    objects of its class are created, and without reference to any object.

    You can declare both methods and variables to be static. The most

    common example of a static member is main( ). main( ) is

    declared as static

    because it must be called before any objects exist.

    Instance variables declared as static are, essentially, global

    variables. When objects of its class are declared, no copy of a

    static variable is made. Instead, all instances of the class share

    the same static variable.

    Methods declared as static have several restrictions:

    They can only call other static methods.

    They must only access static data.

    They cannot refer to this or super in any way. (The

    keyword super relates to

    inheritance.)

    If you need to do computation in order to initialize your static

    variables, you can declare a static block which gets executed

    exactly once, when the class is first loaded.

  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    12/38

    5. When to use Static Method, Static Class and Static Member?

    Static method: Main(), Static class: Math, Static member: Any staticvariable.

    6. How to use the static Method and how it works?

    Static Methods:

    a. In a file context, it means that the function can be called only within thefile scope.b. In a class context, it means that you can invoke a method of a class

    without having to instantiate an object. However note that in staticmethods, you can only manipulate variables that are declared as static, and

    not other variables

    7. What is Thread?

    A threadis a thread of execution in a program. The Java Virtual Machineallows an application to have multiple threads of execution running

    concurrently.

    Every thread has a priority. Threads with higher priority are executed in

    preference to threads with lower priority. Each thread may or may not also bemarked as a daemon. When code running in some thread creates a new

    Thread object, the new thread has its priority initially set equal to the priority

    of the creating thread, and is a daemon thread if and only if the creatingthread is a daemon.

    When a Java Virtual Machine starts up, there is usually a single non-daemonthread (which typically calls the method named main of some designated

    class). The Java Virtual Machine continues to execute threads until either ofthe following occurs:

    The exit method of class Runtime has been called and the

    security manager has permitted the exit operation to take place.

    All threads that are not daemon threads have died, either byreturning from the call to the run method or by throwing an exception

    that propagates beyond the run method.

    There are two ways to create a new thread of execution. One is to declare a

    class to be a subclass of Thread. This subclass should override the runmethod of class Thread. An instance of the subclass can then be allocated and

    started. For example, a thread that computes primes larger than a statedvalue could be written as follows:

  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    13/38

    class PrimeThread extends Thread {

    long minPrime;PrimeThread(long minPrime) {

    this.minPrime = minPrime;}

    public void run() {// compute primes larger than minPrime. . .

    }

    }

    The following code would then create a thread and start it running:

    PrimeThread p = new PrimeThread(143);

    p.start();

    The other way to create a thread is to declare a class that implements theRunnable interface. That class then implements the run method. An instance

    of the class can then be allocated, passed as an argument when creatingThread, and started. The same example in this other style looks like the

    following:

    class PrimeRun implements Runnable {long minPrime;

    PrimeRun(long minPrime) {

    this.minPrime = minPrime;}

    public void run() {// compute primes larger than minPrime

    . . .}

    }

    The following code would then create a thread and start it running:

    PrimeRun p = new PrimeRun(143);new Thread(p).start();

    Every thread has a name for identification purposes. More than one thread

    may have the same name. If a name is not specified when a thread is

    created, a new name is generated for it.

    8. How to create the Thread class?

  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    14/38

    Execution in Java always take form of a thread. In simple programs only one threadoccurs, often referred to as the 'main thread'.

    In some programs though concurrent threads is necessary or if you are building a

    Swing application with for example a progress bar you don't want the main thread tohandle the updates of the UI.

    Then you create an additional thread to take care of that. There are two main ways ofcreating a thread. The first is to extend the Thread class and the second is to

    implement the Runnable interface.

    Extending Thread:

    publicclass MyThread extends Thread {

    /**

    * This method is executed when the start() method is called on the thread* so here you will put the 'thread code'.*/

    publicvoid run() {System.out.println("Thread executed!");

    }

    /*** @param args the command line arguments

    */ publicstaticvoid main(String[] args) {

    Thread thread = new MyThread();thread.start();

    }

    }

    Implementing the Runnable interface:

    publicclass MyRunnable implements Runnable {

    /*** As in the previous example this method is executed

    * when the start() method is called on the thread

    * so here you will put the 'thread code'.*/

    publicvoid run() {

    System.out.println("Thread executed!");}

  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    15/38

    /*** @param args the command line arguments

    */ publicstaticvoid main(String[] args) {

    //create a Thread object and pass it an object of type RunnableThread thread = new Thread(new MyRunnable());thread.start();

    }}

    9. Why implementing the Runnable interface is good to create a Thread class?

    Creating a thread using implementing Runnable interface is more advisable.Suppose we are creating a thread by extending a thread class, we cannot

    extend any other class. If we create a thread by implementing Runnableinterface, we can extend another class.

    10. How to stop a Thread?

    The Thread.stop() method is unsafe and thus deprecated. If the thread being

    stopped was modifying common data that common data remains in an

    inconsistent state.

    A better way would be to have a variable indicating if the thread should be

    stopped. Other threads may set the variable to make the thread stop. Then,the thread itself may clean up and stop.

    Consider the basic example shown below. The thread MyThread will not leavecommon data in an inconsistent state. If another thread calls the done()

    method for MyThread while MyThread is modifying data, MyThread will finishmodifying the data cleanly before exiting.

    public class MyThread extends Thread {

    private boolean threadDone = false;

    public void done() {

    threadDone = true;}

    public void run() {

    while (!threadDone) {// work here

    // modify common data

  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    16/38

    }}

    }

    Note that this method does not eliminate concern about synchronization.

    JDBC-ODBC Bridge driver

    The Type 1 driver translates all JDBC calls into ODBC calls and sends them tothe ODBC driver. ODBC is a generic API. The JDBC-ODBC Bridge driver is

    recommended only for experimental use or when no other alternative is

    available.

    Advantage

    The JDBC-ODBC Bridge allows access to almost any database, since thedatabase's ODBC drivers are already available.

    Disadvantages

    1. Since the Bridge driver is not written fully in Java, Type 1 drivers are notportable.

    2. A performance issue is seen as a JDBC call goes through the bridge to theODBC driver, then to the database, and this applies even in the reverse

    process. They are the slowest of all driver types.3. The client system requires the ODBC Installation to use the driver.

    4. Not good for the Web.

    Native-API/partly Java driver

    The distinctive characteristic of type 2 jdbc drivers are that Type 2 driversconvert JDBC calls into database-specific calls i.e. this driver is specific to a

    particular database. Some distinctive characteristic of type 2 jdbc drivers areshown below. Example: Oracle will have oracle native api.

    Advantage

    The distinctive characteristic of type 2 jdbc drivers are that they are typically

    offer better performance than the JDBC-ODBC Bridge as the layers ofcommunication (tiers) are less than that of Type

    1 and also it uses Native api which is Database specific.

    Disadvantage

    1. Native API must be installed in the Client System and hence type 2 drivers

    cannot be used for the Internet.

  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    17/38

    2. Like Type 1 drivers, its not written in Java Language which forms aportability issue.

    3. If we change the Database we have to change the native api as it isspecific to a database

    4. Mostly obsolete now5. Usually not thread safe.

    All Java/Net-protocol driver

    Type 3 database requests are passed through the network to the middle-tier

    server. The middle-tier then translates the request to the database. If themiddle-tier server can in turn use Type1, Type 2 or Type 4 drivers.

    Advantage

    1. This driver is server-based, so there is no need for any vendor database

    library to be present on client machines.2. This driver is fully written in Java and hence Portable. It is suitable for the

    web.3. There are many opportunities to optimize portability, performance, and

    scalability.

    4. The net protocol can be designed to make the client JDBC driver very smalland fast to load.

    5. The type 3 driver typically provides support for features such as caching

    (connections, query results, and so on), load balancing, and advancedsystem administration such as logging and auditing.

    6. This driver is very flexible allows access to multiple databases using onedriver.

    7. They are the most efficient amongst all driver types.

    Disadvantage

    It requires another server application to install and maintain. Traversing therecordset may take longer, since the data comes through the backend server.

    Native-protocol/all-Java driver

    The Type 4 uses java networking libraries to communicate directly with the

    database server.

    Advantage

    1. The major benefit of using a type 4 jdbc drivers are that they arecompletely written in Java to achieve platform independence and eliminate

    deployment administration issues. It is most suitable for the web.2. Number of translation layers is very less i.e. type 4 JDBC drivers don't

    have to translate database requests to ODBC or a native connectivityinterface or to pass the request on to another server, performance is typically

    quite good.

  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    18/38

    3. You dont need to install special software on the client or server. Further,these drivers can be downloaded dynamically.

    Disadvantage

    With type 4 drivers, the user needs a different driver for each database.

    11. What are the String and the StringBuffer?

    The String class represents character strings. All string literals in Javaprograms, such as "abc", are implemented as instances of this class.

    Strings are constant; their values cannot be changed after they are created.String buffers support mutable strings. Because String objects are immutable

    they can be shared.

    A string buffer implements a mutable sequence of characters. A string buffer

    is like a String, but can be modified. At any point in time it contains someparticular sequence of characters, but the length and content of the sequence

    can be changed through certain method calls.

    String buffers are safe for use by multiple threads. The methods are

    synchronized where necessary so that all the operations on any particular

    instance behave as if they occur in some serial order that is consistent withthe order of the method calls made by each of the individual threads involved.

    String buffers are used by the compiler to implement the binary string

    concatenation operator +.

    string is immutable, that is it can not be extended.whereasStringBuffer is mutable and can be extended.Fro example :

    Consider 2 statement : "Welcome " and "to Java World".now assign first statement to string and string buffer.

    String str = "Welcome" & StringBuffer strBuff = newStringBuffer("Welcome");

    Now if we add 2nd statement to both then :str= str + "to Java World" -> In this case, it would dump

    all the memory allocated with "welcome" and allocate a newmemory space to the entire string "Welcome to Java World" .

    On the other hand, in strBuff :-

    strBuff.append("to Java World") -> if simply allocate anew memory space to only 2nd statement and add to link to

    previous name.

    12. Difference between List and ArrayList?

    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.htmlhttp://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html
  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    19/38

    List: List is an interface in collection framework. several classes like ArrayList,LinkedList implement this interface. List is an ordered collection , so the

    position of an object does matter.ArrayList: An ArrayList is a class which can grow at runtime. you can store

    java objects in an ArrayList and also add new objects at run time.you will use ArrayList when you dont have to add or remove objects

    frequently from it. Because when you remove an object, all other objectsneed to be repositioned inside the ArrayList, if you have this kind of situation,

    try using LinkedList instaed

    13. Difference between List and Map?

    Map doesnt allow duplicate elements whereas List allows duplicate elements.List is an ordered collection Map may or may not be sorted depending on the

    type of Map. List allows null elements. Map may or may not allow null key or

    null values depending on the type of Map. For eg. HashMap allows null key aswell as null values while HashTable doesnt allow null values.

    14. Static Keyword?

    15. Difference between abstract class and an interface

    (1) An abstract class may contain complete or incomplete methods.Interfaces can contain only the signature of a method but no body. Thus an

    abstract class can implement methods but an interface can not implementmethods.

    (2) An abstract class can contain fields, constructors, or destructors andimplement properties. An interface can not contain fields, constructors, or

    destructors and it has only the property's signature but noimplementation.

    (3) An abstract class cannot support multiple inheritance, but an interface cansupport multiple inheritance. Thus a class may inherit several interfaces butonly one abstract class.

    4) A class implementing an interface has to implement all the methods of the

    interface, but the same is not required in the case of an abstract Class.(5) Various access modifiers such as abstract, protected, internal, public,

    virtual, etc. are useful in abstract Classes but not in interfaces.(6) Abstract classes are faster than interfaces.

    16. What is the abstract class?

    Abstract class is a class that can not be instantiated, it exists extensively for

    inheritance and it must be inherited. There are scenarios in which it is useful

    to define classes that is not intended to instantiate; because such classesnormally are used as base-classes in inheritance hierarchies, we call suchclasses abstract classes.

    Abstract classes cannot be used to instantiate objects; because abstract

    classes are incomplete, it may contain only definition of the properties ormethods and derived classes that inherit this implements its properties or

    methods.

  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    20/38

    Static, Value Types & interface doesn't support abstract modifiers. Staticmembers cannot be abstract. Classes with abstract member must also be

    abstract.

    17. What is the private class?

    Only nested classes can be private. If a top-level class were private, nothingcould access it.

    So, private nested classes are just like other private members (methods and

    variables)--they can only be accessed "within the body of the top level classthat

    encloses the declaration of the member or constructor"

    Private classes are to be used only by their declaring class (more or less) just

    like other private members

    18. Can we use the main method in the private class?

    You can use the main method in the private inner class but if the main

    method is declared as static then you have to declare your inner class also asa private static inner class in order to run the program without compilationerror. Static inner classes are not advisable.

    19. What is Synchronization?

    Synchronization is best use with the Multi-Threading in Java, Synchronizationis the capability to control the access of multiple threads to share resources.

    Without synchronization it is possible for one thread to modify a shared objectwhile another thread is in the process of using or updating that object's

    value.This often leads to an error.

    Example for Synchronization

    public synchronized void enqueue(Object item){

    // Body of method goes here

    }

    shorthand notation for

    public void enqueue(Object item){

    synchronized (this){

    //Body of method goes here}

    }

    20. What is Cloning? Different types of cloning?

  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    21/38

    cloning is the copying of an object to create an identical object. The methodclone() in Object makes a copy of the object by copying each field reference

    and primitive to the new object. In essence this is a shallow object.Implementers can override this to make a deeper copy of the object if

    necessary. Objects like String do not need to be copied since they areimmutable. As stated there are two basic types of cloning, shallow and deep.

    21. Inner classes?

    An inner class is a class that is defined within the definition of another class

    but outside any member definition. Inner classes should not be marked static.An Inner class cannot be instantiated directly, i.e. one can only instantiate an

    inner class by first instantiating the outer class.The Inner class has access to all the static as well as non-static

    public/protected/private fields of its enclosing outer class.

    Inner classes are used to provide implementation that are intimatelyconnected with the enclosing outer class.

    22. What is the difference between MVC and MVC2?

    In case of MVC1, the JSP page acts as Controller and view

    (i.e we need to provide the control logic and presentation

    logic as part of Jsp page)

    In case of MVC2, the ActionServlet acts as a controller and

    the JSP page acts as view.

    23. What is the HTTP?

    Hypertext Transfer Protocol (http) is a system for transmitting and receiving

    information across the Internet. Http serves as a request and responseprocedure that all agents on the Internet follow so that information can be

    rapidly, easily, and accurately disseminated between servers, which hold

    information, and clients, who are trying to access it. Http is commonly used toaccess html pages, but other resources can be utilized as well through http.

    In many cases, clients may be exchanging confidential information with aserver, which needs to be secured in order to prevent unauthorized access.

    For this reason, https, or secure http, was developed by Netscape corporationto allow authorization and secured transactions.

    24. Is HTTP call statefull or it is stateless? How to make it stateless?

    Fundamentally, HTTP as a protocol is stateless. In general, though, a

    stateless protocol can be made to act as if it were stateful, assumingyou've got help from the client. This happens by arranging for theserver to send the state (or some representative of the state) to the

    client, and for the client to send it back again next time.

    There are three ways this happens in HTTP. One is cookies, in whichcase the state is sent and returned in HTTP headers. The second is URL

    rewriting, in which case the state is sent as part of the response andreturned as part of the request URI. The third is hidden form fields,

  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    22/38

    in which the state is sent to the client as part of the response, andreturned to the server as part of a form's data (which can be in the

    request URI or the POST body, depending on the form's method).

    25. What is the singleton class? Can you give me some example?

    singleton class - has single Instance.

    The Singleton is a useful Design Pattern for allowing onlyone instance of your class, but common mistakes can

    inadvertently allow more than one instance to be created.

    The Singleton's purpose is to control object creation,

    limiting the number to one but allowing the flexibility tocreate more objects if the situation changes. Since there

    is only one Singleton instance, any instance fields of aSingleton will occur only once per class, just like static

    fields.

    //Eg Pgm.

    class Sample

    {void m1()

    {System.out.println("Method m1");

    }void m2()

    {

    System.out.println("Method m2");}private Sample()

    {System.out.println("Constructor");

    }public static void main(String[] args)

    {Sample s = new Sample();

    s.m1();s.m2();

    }

    26. What are the design patterns?

    If a problem occurs over and over again, a solution to that problem has been

    used effectively. That solution is described as a pattern. The design patterns

    are language-independent strategies for solving common object-orienteddesign problems. When you make a design, you should know the names of

    some common solutions. Learning design patterns is good for people tocommunicate each other effectively. In fact, you may have been familiar with

  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    23/38

    some design patterns, you may not use well-known names to describe them.SUN suggests GOF (Gang Of Four--four pioneer guys who wrote a book

    named "Design Patterns"- Elements of Reusable Object-Oriented Software),so we use that book as our guide to describe solutions. Please make you be

    familiar with these terms and learn how other people solve the codeproblems.

    27. Describe the Factory pattern.

    if we have a super class and n sub-classes, and based on data provided, we

    have to return the object of one of the sub-classes, we use a factory pattern.

    28. What is Auto Boxing/Boxing?

    Autoboxing is a new feature offered in the Tiger (1.5) release of Java SDK. In

    short auto boxing is a capability to convert or cast between object wrapper

    and its primitive type. Previously when placing a primitive data into one of the

    Java Collection Framework we have to wrap it to an object because the

    collection cannot work with primitive data. Also when calling a method that

    requires an instance of object than an int or long, than we have to convert it

    too.But now, starting from version 1.5 we were offered a new feature in the

    Java Language, which automate this process, this is call the Autoboxing.

    When we place an int value into a collection it will be converted into an

    Integer object behind the scene, on the other we can read the Integer value

    as an int type. In most way this simplify the way we code, no need to do an

    explicit object casting.

    29. What is the difference between sleep and wait?

    Thread.sleep() sends the current thread into the "Not Runnable" state for

    some amount of time. The thread keeps the monitors it has aquired -- i.e. ifthe thread is currently in a synchronized block or method no other thread can

    enter this block or method. If another thread calls t.interrupt() it will wake up

    the sleeping thread.

    Note that sleep is a static method, which means that it always affects thecurrent thread (the one that is executing the sleep method). A common

    mistake is to call t.sleep() where t is a different thread; even then, it is the

    current thread that will sleep, not the t thread.

    t.suspend() is deprecated. Using it is possible to halt a thread other than thecurrent thread. A suspended thread keeps all its monitors and since this state

    is not interruptable it is deadlock prone.

    object.wait() sends the current thread into the "Not Runnable" state, like

    sleep(), but with a twist. Wait is called on a object, not a thread; we call thisobject the "lock object." Before lock.wait() is called, the current thread must

  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    24/38

    synchronize on the lock object; wait() then releases this lock, and adds thethread to the "wait list" associated with the lock. Later, another thread can

    synchronize on the same lock object and call lock.notify(). This wakes up theoriginal, waiting thread. Basically, wait()/notify() is like sleep()/interrupt(),

    only the active thread does not need a direct pointer to the sleeping thread,but only to the shared lock object.

    30. Can we force garbage collection and if yes how?

    java follows a philosophy of automatic garbage collection, you can suggest or

    encourage the JVM to perform garbage collection but you can not force it.Once a variable is no longer referenced by anything it is available for garbage

    collection. You can suggest garbage collection with System.gc(), but this does

    not guarantee when it will happen. Local variables in methods go out of scopewhen the method exits. At this point the methods are eligible for garbage

    collection. Each time the method comes into scope the local variables are re-created.

    31. What all the access modifiers of the class, variable and methods describe in

    detail.

    If a class has public visibility, the class can be referenced by anywhere in theprogram. If a class has package visibility, the class can be referenced only in

    the package where the class is defined. If a class has private visibility, (it canhappen only if the class is defined nested in another class) the class can be

    accessed only in the outer class.

    If a variable is defined in a public class and it has public visibility, the variable

    can be reference anywhere in the application through the class it is defined in.If a variable has package visibility, the variable can be referenced only in the

    same package through the class it is defined in. If a variable has privatevisibility, the variable can be accessed only in the class it is defined in.

    If a method is defined in a public class and it has public visibility, the method

    can be called anywhere in the application through the class it is defined in. If

    a method has package visibility, the method can be called only in the samepackage through the class it is defined in. If a method has private visibility,

    the method can be called only in the class it is defined in.

  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    25/38

    ClassNested

    class

    Method, orMember

    variable

    InterfaceInterfacemethod

    signature

    publicvisible from

    anywhere

    same as its

    classsame as its class

    visible from

    anywhere

    visible from

    anywhere

    protected N/A

    its class

    and itssubclass

    its class and its

    subclass, andfrom its package

    N/A N/A

    package(default)

    only from itspackage

    only fromits package

    only from itspackage

    only from itspackage

    N/A, default ispublic

    private N/Aonly fromits class

    only from itsclass

    N/A N/A

    32. What in encapsulation?

    Encapsulation is the concept of hiding the implementation details of a classand allowing access to the class through a public interface. For this, we need

    to declare the instance variables of the class as private or protected.

    The client code should access only the public methods rather than accessingthe data directly. Also, the methods should follow the Java Bean's naming

    convention of set and get.

    Encapsulation makes it easy to maintain and modify code. The client code isnot affected when the internal implementation of the code changes as long as

    the public method signatures are unchanged.

    http://en.wikibooks.org/wiki/Java_Programming/Keywords/publichttp://en.wikibooks.org/wiki/Java_Programming/Keywords/protectedhttp://en.wikibooks.org/wiki/Java_Programming/Keywords/privatehttp://en.wikibooks.org/wiki/Java_Programming/Keywords/publichttp://en.wikibooks.org/wiki/Java_Programming/Keywords/protectedhttp://en.wikibooks.org/wiki/Java_Programming/Keywords/private
  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    26/38

    33. How the block of synchronization works?

    In Java you can mark a method or a block of code as synchronized.Synchronized blocks can be used to avoid race conditions.

    Here is a synchronized method:

    public synchronized void add(int value){

    this.count += value;

    }

    And here is a synchronized block of code inside an unsynchronized addmethod:

    public void add(int value){

    synchronized(this){

    this.count += value;

    }

    }

    Notice how the synchronized construct takes an object in parantheses. In the

    example "this" is used, which is the instance the add method is called on. Theobject taken in the parantheses by the synchronized construct is called a

    monitor object. The code is said to be synchronized on the monitor object. A

    synchronized method uses the object it belongs to as monitor object. A staticmethod uses the class object of the class the method belongs.

  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    27/38

    Only one thread can execute inside a code block synchronized on the samemonitor object.

    34. Can we synchronize the array list and variables?

    Yes we can synchronize the arraylist.

    Collections.synchronizedList(new ArrayList());

    35. Can we have public inner class?

    36. Why we need inner class. Give any real time example.

    The advantages of inner classes can be divided into three categories: anobject-oriented advantage,an organizational advantage, and a call-back

    advantageThe object-oriented advantage:

    the most important feature of the inner class is that it allows you to turnthings into objects that you normally wouldn't turn into objects. That allows

    your code to be even more object-oriented than it would be without innerclasses.

    Let's look at the member class. Since its instance is a member of its parentinstance, it has access to every member and method in the parent. At first

    glance, this might not seem like much; we already have that sort of accessfrom within a method in the parent class. However, the member class allows

    us to take logic out of the parent and objectify it. For example, a tree class

    may have a method and many helper methods that perform a search or walkof the tree. From an object-oriented point of view, the tree is a tree, not a

    search algorithm. However, you need intimate knowledge of the tree's data

    structures to accomplish a search. An inner class allows us to remove thatlogic and place it into its own class. So from an object-oriented point of view,

    we'vetaken functionality out of where it doesn't belong and have put it into its own

    class. Through the use of an inner class, we have successfully decoupled thesearch algorithm from the tree. Now, to change the search algorithm, we can

    simply swap in a new class. I could go on, but that opens up our code tomany of the advantages provided by object-oriented techniques. Used

    carefully, inner classes can provide a structural hierarchy that more naturallyfits your classes.

    The callback advantage:Most Java GUIs have some kind of component that instigates an

    actionPerformed() method call. Unfortunately, most developers simply havetheir main window implement ActionListener. As a result, all components

    share the same actionPerformed() method. To figure out which component

    performed the action, there is normally a giant, ugly switch in theactionPerformed() method.Whenever you see switches or large if/if else blocks,

    loud alarm bells should begin to ring in your mind. In general, such constructsare bad object-oriented design since

    a change in one section of the code may require a corresponding change inthe switch statement. Inner member classes and anonymous

    classes allow us to get away from the switched actionPerformed() method.Instead, we can define an inner class that implements ActionListener for each

  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    28/38

    component to which we want to listen. That may result in many inner classes.However, we can avoid large switch statements and have the added bonus of

    encapsulating our action logic. Moreover, that approach may improveperformance. In

    a switch where there are n comparisons, we can expectn/2 comparisons in the average case. Inner classes allow us to

    set up a 1:1 correspondence between the action performer and theaction listener. In a large GUI, such optimizations can make a substantial

    impact on performance.

    37. Can we declare all the methods of a class as static?

    Yes we can declare all the methods of the class as static.

    38. Can we declare the whole class as synchronized?

    The valid modifiers for a class are any

    annotation, public, protected, private, abstract, static, final, orstrictfp. It is illegal to place the keyword "synchronized" in front of

    a class.

    39. In the deep cloning can we modify the value of an object?

    40. If Jsp has the code to connect to DB, then whether jsp act as Controller

    in case of MVC ?

    We can say that jsp acts as a model.

    41. what is static import? Whether it is there in jdk 1.6?

    By adding the word static after the import keyword, you change your import

    to a static one.when an import is static, all the accessible methods andvariables of the class can be used without prefixing its access with the class

    name. For instance, if you static import the java.awt.Color class with import

    static java.awt.Color.*;, you just have to include RED in your code, instead ofColor.RED.Yes its there in jdk 1.6.

    42. which is better from this? 1. arraylist put inside a synchronized block and 2.

    Vector

    Vector is better as Vector is synchronized and ArraylList is not.Vector is thread safe.

    43. why final keyword is used? What is final class,final method?

    A java variable can be declared using the keyword final. Then the final

    variable can be assigned only once.

    A variable that is declared as final and not initialized is called a blank final

    variable. A blank final variable forces the constructors to initialise it.

    Java classes declared as final cannot be extended. Restricting inheritance!

    Methods declared as final cannot be overridden. In methods private is equalto final, but in variables it is not.

  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    29/38

    final parameters values of the parameters cannot be changed afterinitialization. Do a small java exercise to find out the implications of final

    parameters in method overriding.

    Java local classes can only reference local variables and parameters that aredeclared as final.

    A visible advantage of declaring a java variable as static final is, the compiled

    java class results in faster performance.

    44. Can we encapsulate behaviour of an object?

    An object encapsulates both state and behavior, where the behavior is

    defined by the actual state. Consider a door object. It has four states: closed,open, closing, opening. It provides two operations: open and close.

    Depending on the state, the open and close operations will behave differently.This inherent property of an object makes the design process conceptually

    simple. It boils down to two simple tasks: allocation and delegation ofresponsibility to the different objects including the inter-object interaction

    protocols.

    45. When you will use abstract class instead of Interface?

    Abstract class provides both methods with and without body. Adding new

    methods in abstract class in middle of development life cycle won't breakexisting sub classes unless these methods are declared as mustoverride. If

    there are frequent addition of new methods properties and so on. One shoulduse abstract. Whereas on the other hand interface can fill gap of multiple

    inheritance. One can implement from more than one interface. Not same withAbstract. One can inherit from only one abstract class.

    46. what are the new features in jdk 1.6? (if worked in 1.6)

    New Security Features and Enhancements

    Native platform Security (GSS/Kerberos) integration

    Java Authentication and Authorization Service (JAAS) loginmodule that employs LDAP authentication

    New Smart Card I/O API

    Integrated Web Services

    New API for XML digital signature services for secure webservices

    New Client and Core Java Architecture forXML-Web Services

    (JAX-WS) 2.0 APIs

    New support for Java Architecture forXML Binding (JAXB)2.0

    Scripting Language Support

    New framework and API forscripting languages

    http://www.javabeat.net/articles/13-introduction-to-java-60-new-features-parti-2.htmlhttp://www.javabeat.net/articles/13-introduction-to-java-60-new-features-parti-2.html
  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    30/38

    Mozilla Rhino engine for JavaScript built into the platform

    Enhanced Management and Serviceability

    ImprovedJMX Monitoring API

    Runtime Support for dTrace (Solaris 10 and future Solaris OS

    releases only) Improved memory usage analysis and leak detection

    Increased Developer Productivity

    JDBC 4.0 support (JSR 221)

    Significant library improvements

    Improvements to the Java Platform Debug Architecture (JPDA)& JVM Tool Interface

    Improved User Experience

    look-and-feel updates to better match underlying operatingsystem

    Improved desktop performance and integration

    Enhanced internationalization support

    47. Difference between Jsp and Servlets.

    Both servlet and jsp are web components. But servlet is best suited forrequest processing, handling the business logic while jsp is suitable for

    content generating. Its easy to include html tag in jsp rather thanservlet.Also jsp is compiled to servlet when first loaded to webserver. So in

    many framework servlet act as a controller while jsp as a view. Also implicit

    object and action elements available in jsp but not in servlet.

    48. Different type of beans./What are session beans and Entity beans?/

    Different type of Bean persistent. Explain them.

    i. Session Beans :Session beans are the brain of our EJB based application. Their methods

    should decide what should or should not happen. They maintain thebusiness logic. The client directly interacts with them, they are of two

    types :

    Stateless Session BeansThey do not maintain state in class level variables. They are thus fastest

    and most efficient of all. Since they do not save their state in class level

    variables, they are called as "Stateless". Stateful Session Beans

    They do maintain state in class level variables and each client is provideda different and specific Stateful Session bean. This is different from

    Stateless Session beans in which case the client can be provided anyStateless Session bean between requests since the Stateless Session

    beans haven't managed their state, to the client, all of them are equal.Due to this fact, Stateful Session beans are heavy beans, while Stateless

    Session beans are light and efficient.

    http://www.javabeat.net/articles/13-introduction-to-java-60-new-features-parti-3.htmlhttp://www.javabeat.net/articles/13-introduction-to-java-60-new-features-parti-3.html
  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    31/38

    ii. Entity Beans :Entity beans represent data in an EJB system. That data can reside in any

    data source including database. Entity beans are also of two types :

    Container-Managed Persistence Entity Beans :CMP bean's persistence is managed by the EJB container which is

    responsible for saving and retrieving the data from the underlying

    database for us. CMP beans are easier to develop and work well withdatabase access.

    Bean-Managed Persistence Entity Beans :BMP bean's persistence has to be managed by the EJB itself. While it gives

    more control to the EJB developer to save and retrieve data, they areharder to build as more coding is required. One use of BMP beans would

    be to retrieve and save data from non-database data sources like XMLfiles, JMS resources etc.

    iii. Message-Driven Beans :They are new in EJB 2.0 specification and provide a mechanism for EJBs to

    respond to asynchronous JMS messages from different sources. Message-

    Driven beans and JMS have opened a new paradigm for J2EE developersto create MOM ( Message Oriented Middleware ) based applications. We

    will learn more and more about this in separate articles on Stardeveloper.

    49. What is ajax, how does it work.

    AJAX is a term used to describe an approach to designing and implementing

    web applications. It is an acronym for Asynchronous JavaScript and XML. The

    term was first introduced in an article by Jesse James Garrett of AdaptivePath, a web-design firm based out of San Francisco. He conceived of the term

    when he realized the need for an easy, sellable way to pitch a certain style of

    design and building to clients.The primary purpose of AJAX is to help make web applications function more

    like desktop applications. HyperText Markup Language (HTML), the language

    that drives the World-Wide Web, was designed around the idea ofhypertextpages of text that could be linked within themselves to other documents. ForHTML to function, most actions that an end-user takes in his or her browser

    send a request back to the web server. The server then processes thatrequest, perhaps sends out further requests, and eventually responds with

    whatever the user requested.

    Ajax adds a layer to web application communication models. As previouslystated, in traditional web applications communication between the

    browser/client and the web server occurred directly between these twocomponents using HTTP requests. When users/clients request web pages, the

    server sends all the HTML and CSS code at once. If the user entersinformation into this page and requests more servers, the entire page must

    be loaded again. When using Ajax, the page is only loaded once. Anyprocessing or modification caused by additional user input occurs in real time.

    50. How to maintain the session.

    51. Different type of JDBC connection.

    http://www.wisegeek.com/what-is-an-acronym.htmhttp://www.wisegeek.com/what-is-html.htmhttp://www.wisegeek.com/what-is-html.htmhttp://www.wisegeek.com/what-is-a-web-server.htmhttp://www.wisegeek.com/what-is-an-acronym.htmhttp://www.wisegeek.com/what-is-html.htmhttp://www.wisegeek.com/what-is-html.htmhttp://www.wisegeek.com/what-is-a-web-server.htm
  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    32/38

    52. What is singleton pattern?This is one of the most commonly used patterns. There are some instances in

    the application where we have to use just one instance of a particular class.Lets take up an example to understand this.

    A very simple example is say Logger, suppose we need to implement thelogger and log it to some file according to date time. In this case, we cannot

    have more than one instances of Logger in the application otherwise the filein which we need to log will be created with every instance.We use Singleton

    pattern for this and instantiate the logger when the first request hits or when

    the server is started.

    53. What is MVC architecture and how struts works?

    The main aim of the MVC architecture is to separate the business logic and

    application data from the presentation data to the user.

    Here are the reasons why we should use the MVC design pattern.

    1. They are resuable : When the problems recurs, there is no need to inventa new solution, we just have to follow the pattern and adapt it as

    necessary.2. They are expressive: By using the MVC design pattern our application

    becomes more expressive.

    1). Model: The model object knows about all the data that need to bedisplayed. It is model who is aware about all the operations that can be

    applied to transform that object. It only represents the data of an application.The model represents enterprise data and the business rules that govern

    access to and updates of this data. Model is notaware about the presentation data and how that data will be displayed to the

    browser.

    2). View: The view represents the presentation of the application. The viewobject refers to the model. It uses the query methods of the model to obtain

    the contents andrenders it. The view is not dependent on the application logic. It remains

    same if there is any modification in the business logic. In other words, we cansay that it is the

    responsibility of the of the view's to maintain the consistency in itspresentation when the model changes.

    3). Controller: Whenever the user sends a request for something then italways go through the controller. The controller is responsible for intercepting

    the requests from

  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    33/38

    view and passes it to the model for the appropriate action. After the actionhas been taken on the data, the controller is responsible for directing the

    appropriate view to the user. In GUIs, the views and the controllers oftenwork very closely together.

    54. What is custom tag in JSP?

    Tag Files in JSP 2.0

    This tips explains about what are the advantages in the Custom Tags in JSP2.0. It also compares it with the previous JSP versions. Lets look into the tips

    for more detail.Developing custom tags in the previous JSP versions are tedious and it is

    considered as one of the complex task for the JSP developers. Because

    inorderto write a simple custom tag you have to learn many things andshould have good knowledge on Java also. Apart from that you have to use

    Tag APIs to create a complete tag library. Any small mistake will cause theerror and tag files will not work. To make the things easy for the JSP

    developers, JSP 2.0 has the advanced features for creating JSP custom taglibraries.The following are the mandatory for writing the custom tags in previous

    versions:

    Writing and compiling a tag handler.

    Defining the tag that is associated with the tag handler.

    Creating the TLD(Taglib Descriptor) files.

    What is Tag Files?JSP 2.0 has introduced the concept called tag files, which are nothing but the

    simple files works like a JSP file. They define all the functionalities requiredfor a custome tag. You are no longer required to write the Java file and

    compile it. These tag files are compiled dynamically by the JSP container.Even though, it is simple file, JSP container will convert these files into a Tag

    Library. But developers need not worry about them.Tag files just work like an JSP pages, it has the following implicit objects:

    request -> javax.servlet.http.HttpServletRequest

    response -> javax.servlet.http.HttpServletResponse

    out -> javax.servlet.jsp.JspWriter

    session -> javax.servlet.http.HttpSession

    application -> javax.servlet.ServletContext

    config -> javax.servlet.ServletConfig

    jspContext -> javax.servlet.jsp.JspContext

    All the abobe objects are available in the normal JSP files also.All the tag files must be put under the folder WEB-INF/tags or you can

    create the sub directory under it. The directory name must be specified whileimporting the tags in JSP file as follows:

  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    34/38

    55. What is JMS?

    Java Message Service: An interface implemented by most J2EE containers to

    provide point-to-point queueing and topic (publish/subscribe) behavior. JMS isfrequently used by EJB's that need to start another process asynchronously.

    For example, instead of sending an email directly from an EnterpriseJavaBean, the bean may choose to put the message onto a JMS queue to be

    handled by a Message-Driven Bean (another type of EJB) or another system

    in the enterprise. This technique allows the EJB to return to handling requestsimmediately instead of waiting for a potentially lengthy process to complete.

    What is user defined Exceptions?

    A user defined exception is a custom made exception class that is given by

    application provider that must extends exception declare in JAVA API classes.It is used to handle any unconventional error generated by your code. User

    defined exceptions can be created using try-catch keyword. In this you mustwrite method that is created in parent class Exception.

    For example, if the person is in the business of selling motorcycles and needto validate an order which has been placed by a customer, creating a user-

    defined exception in the Java programming language can be done by acreating a new class which can be named TooManyBikesException. This has

    been derived from the class exception or throwable, and if someone tries to

    place an order for more motorcycles than you can ship, you can simply throwa user-defined exception.

    What are Checked and Unchecked exceptions?

    A checked exception is any subclass of Exception (or Exception itself),excluding class RuntimeException and its subclasses.

    Making an exception checked forces client programmers to deal with thepossibility that the exception will be thrown. eg, IOException thrown by

    java.io.FileInputStream's read() method. Unchecked exceptions are

    RuntimeException and any of its subclasses. Class Error and its subclasses

    also are unchecked. With an unchecked exception, however, the compilerdoesn't force client programmers either to catch the exception or declare it in

    a throws clause. In fact, client programmers may not even know that theexception could be thrown. eg, StringIndexOutOfBoundsException thrown by

    String's charAt() method. Checked exceptions must be caught at compiletime. Runtime exceptions do not need to be. Errors often cannot be, as they

    tend to be unrecoverable.

  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    35/38

    What is Error?

    An Error is a subclass of Throwable that indicates serious problems that areasonable application should not try to catch. Most such errors are abnormal

    conditions. The ThreadDeath error, though a "normal" condition, is also a

    subclass of Error because most applications should not try to catch it.A method is not required to declare in its throws clause any subclasses of

    Error that might be thrown during the execution of the method but notcaught, since these errors are abnormal conditions that should never occur.

    What is garbage collection?

    When a Java object becomes unreachable to the program, then it is subjectedto garbage collection. The main use of garbage collection is to identify and

    discard objects that are no longer needed by a program so that theirresources

    can be reclaimed and reused.

    Can you call garbage collection? How?

    How will you create Thread? Which method is suitable?

    When a thread is created, it must be permanently bound to an object with arun() method. When the thread is started, it will invoke the object's run()method. More specifically, the object must implement the Runnable interface.

    There are two ways to create a thread. The first is to declare a class that

    extends Thread. When the class is instantiated, the thread and object arecreated together and the object is automatically bound to the thread. By

    calling the object's start() method, the thread is started and immediately callsthe object's run() method. Here is some code to demonstrate this method.

    // This class extends Threadclass BasicThread1 extends Thread {

    // This method is called when the thread runspublic void run() {

    }}

    // Create and start the threadThread thread = new BasicThread1();

    thread.start();

    The second way is to create the thread and supply it an object with a run()method. This object will be permanently associated with the thread. The

    object's run() method will be invoked when the thread is started. This method

  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    36/38

    of thread creation is useful if you want many threads sharing an object. Hereis an example that creates a Runnable object and then creates a thread with

    the object.class BasicThread2 implements Runnable {

    // This method is called when the thread runspublic void run() {

    }}

    // Create the object with the run() method

    Runnable runnable = new BasicThread2();

    // Create the thread supplying it with the runnable object

    Thread thread = new Thread(runnable);

    // Start the threadthread.start();

    How you will write the synchronized code?

    First of all to achieve Multithreading mechanism in java we should go for

    synchronization. And this can be done in two ways depending on therequirement.

    1. Synchronized block and

    2. Synchronized method.

    if you go for synchronized block it will lock a specific object.

    if you go for synchronized method it will lock all the objects.

    in other way Both the synchronized method and block are used to acquiresthe lock for an object. But the context may vary. Suppose if we want to

    invoke a critical method which is in a class whose access is not available then

    synchronized block is used. Otherwise synchronized method can be used.

    Synchronized methods are used when we are sure all instance will work onthe same set of data through the same function Synchronized block is used

    when we use code which we cannot modify ourselves like third party jars etc

    For a detail clarification see the below code

    for example:

    //Synchronized block

    class A{ public void method1() {...} }

    class B{

    public static void main(String s[]){ A objecta=new A();

    A objectb=new A();

  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    37/38

    synchronized(objecta){objecta.method1();}objectb.method1(); //not synchronized

    }}

    //synchronized method

    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();

    }}

    What is difference between sleep() and wait()?

    What are wait(),notify() and notifyAll() methods?

    The wait, notify, and notifyAll methods allow threads to coordinate theiractions. Sometimes, a thread may have to wait until a certain condition is

    true before proceeding. Consider a thread that continually processesmessages in a queue. This thread should wait until a new message arrives

    before the actual processing. The wait() method suspends the current thread

    until another thread issues notify() or notifyAll() (notify() simplycommunicates with one thread while notifyAll() communicates with all waitingthreads):

    public synchronized messageProcessor() {

    while(!messageSent) {try {

    wait();} catch (InterruptedException e) {}

    }

    .

    .

    (Message Processing Code).

    .}

    public synchronized messageSender() {

    sendMessageToQueue();messageSent = true;

    notifyAll();}

  • 8/2/2019 Diff Between JDK 1.4 and 1.5Interview Question

    38/38

    Note: The wait, notify, and notifyAll methods are usually used in synchronizedblocks. A waiting thread needs a lock on the objects and on the operations

    that should not be processed unless the condition is satisfied. If the loop isnot synchronized, other objects may get into the objects and code before the

    condition is satisfied.

    What is DOM in relation to ajax.What is session?What is Hibernate?Does forward and backward button is the part of DOM.Is HTTP is stateless or state full?How do we maintain session?What are the types of JDBC driver?What is singleton design pattern?What is synchronization?What is your project?

    What is your role in your project?What are your responsibilities?What is the meaning of static keyword in java?Can we declare a class as static?What is polymorphism?What is difference between interface and abstract class?In which scenario you will use Interface and abstract class?Which type of methods can present in Interface and abstract class?What is meaning of final keyword in java?What is difference between abstract class and final class?Can we declare a class as abstract and final at the same time? Why?What is difference between String and StringBuffer?Which interfaces are present in Collection? Which are there implementation classes?

    What is difference between List and Map?How you are handling Exceptions?