+ All Categories
Home > Documents > FQS Question Compile

FQS Question Compile

Date post: 03-Apr-2018
Category:
Upload: satish-babu
View: 230 times
Download: 0 times
Share this document with a friend

of 40

Transcript
  • 7/28/2019 FQS Question Compile

    1/40

    What are the properties of OOP?

    NEXT

    Encapsulation:Encapsulation refers to creation of self-contained data types, containing propertiesand behaviour. The code to manipulate data, and actual data to be manipulated aremodularised into a single logical entity. In terms of Java, this entity is called classwhich can contain data members(property) and member methods(behaviour). Thephysical instance of class is an object. The binding of properties and methodstogether provides controlled access to the data members and hence ensuressecurity of data. Encapsulation is thus also associated with data hiding.

    Abstraction:Abstraction is closely linked with encapsulation. Encapsulation prevents data frombeing accessed direclty. Abstraction refers to the feature of providing the

    functionality required, without disclosing the details of implementation. The actualprocessing is kept hidden from outside world.

    Inheritance:Inheritance facilitates class hierarchy. It is a major principle of Object OrientedProgramming. The main idea behind OOP was to avoid code repetation. Inheritanceallows the data and methods (structure and behaviour) of a parent class to bepassed down to the subclasses in class hierarchy. The subclasses may implementmore specific behaviour independently. A common example is that of Vehical. Allvehicals have some features and behaviour in common. But, a Truck may havesome specific characteristics which are different from a Car. The Truck class and Carclass will both inherit properties and methods of Vehical class, and they can

    additional ones in their class respectively. Moreover, they can also override theparent class behaviour.

    One more advantage of inheritance is that it makes adding a functionality mucheasier. Say, if a new method is required, it is easy to create a new subclass and addthe required functionality. All current features will be inherited by the subclass.

    Polymorphism:Polymorphism means having many forms. It allows a method to have more thanimplementation, depending upon certain conditions. There are two kinds ofpolymorphism: Static or compile-time polymorphism and dynamic or runtimepolymorphism.

    Static polymorphism is implemented through method overloading. A methodhaving same name can have multiple implementations, depending upon theargument(s) passed to it. For example, there can be two methods called add(int x,int y) and add(float x, float y). The compiler decides at compile time which methodwill be called by looking at the signature of the called method.

    In runtime polymorphism, a subclass may override a superclass method for more

  • 7/28/2019 FQS Question Compile

    2/40

    specific behaviour. The decision of which method to call is made at runtime. Thecalling code may declare the object to be of parent type. At runtime, dependingupon the actual type of the object, the correct method will be invoked. An examplemay be of open() method for superclass Document. The subclasses doc and xlsboth override open() method. But it may not be known beforehand which documentwill be opened. At runtime, depending upon the object on which open() is called,

    the correct Document object's open() method will be invoked.

    What is the difference between Abstract class and Interface?

    NEXT

    There is a logical difference between abstract class and interface. Conceptually, aclass should extend another class when it exhibits a more specialized behaviour ofthe extended class.On the other hand, implementing an interface means the implementing class has

    the ability to exhibit a certain behaviour defined by the interface. It is not necessaryfor it to be a specialized version of the interface. It should be noted that an interfacename is always an adjective, eg. Runnable. Hence, although a set of properties andbehaviour may be given to a class both through abstract class and interface, anabstract class is used for defining the core identity of a class with a more specializedbehaviour whereas an interface is used for giving a class ability to do something.

    The technical differences between abstract class and interface are listed below:

    An abstract class can define methods with default implementation or just thesignature to be overridden. But methods of an interface are always abstract. There

    can never be a method implementation in an interface. An interface can be thoughtof as a purely abstract class. For this reason, adding new functionality to abstractclass is easier since default implementation may be provided in the abstract classitself. Whereas in case of interface, all implementating classes need to be modifiedto adjust the new method.

    A Java class has the liberty of implementing multiple interfaces, but can extendonly one abstract class. Hence interface facilitates multiple inheritance in Java.

    An abstract class is considered to perform faster than an interface.

    Access level of all interface members is public by default, whereas abstract class is

    free to define member

    Are identifiers in Java case sensitive?

    NEXT

  • 7/28/2019 FQS Question Compile

    3/40

    Yes, identifiers are case sensitive. "javafoo" is different from "JAVAFOO".

    s with any access modifier.

    PREV

    Which of the following are valid identifiers:$foo_bar___foo__bar__5_foofoo#5foo

    -foo

    $foo - Valid._bar - Valid___foo__bar - Valid__5_foo - Validfoo# - Invalid. # is not allowed in a legal identifier5foo - Invalid. An identifier cannot start with a number-foo - Invalid. An identifier cannot contain - character..

    Can a Java class name start with a small case letter?

    NEXT

    A Java class name can begin with a small case letter. The class will compilesuccessfully. However, it is against the standard Java Code Conventions to do so. As

    per the standard, a Java class name must begin with upper case letter.

    What do you mean by final class in Java?

    NEXT

  • 7/28/2019 FQS Question Compile

    4/40

    A final class is a class which cannot be extended.A common question is - does it not violate the major object oriented principle ofinheritance? The answer is that there may be certain scenarios when theprogrammer wants complete confidence that the methods of her class will never beoverridden. Final class is generally useful while building APIs or libraries. The bestexample is String class in the Java API. It makes sense to mark the String class final

    since all string behaviour needs to be consistent. However, in practice, final classesshould only be used when there is a surety that the class is improvised to itsmaximum and there will nevCan an abstract class have non-abstractmethods?

    NEXT

    Yes, an abstract class can have non-abstract methods.

    er be need to specialize its behaviour.

    Can an interface method be marked final?

    NEXT

    An interface method can never be marked final. Interface methods are by defaultabstract. The sole purpose of interface is to be extended or rather implemented byanother class. Hence, an implementing class is "required" to provideimplementation for all interface methods. Any code marking interface methods

    final will give compilation error.

    Can private method be overridden by a subclass?

    NEXT

    A private method is not visible to subclasses and hence cannot be overriden.However, if the subclass defines a method having same name as the private

    superclass method, the code will compile fine. This method will just be a newsubclass method which happens to have the same name as the superclass method.This method need Can a protected member be accessed by a subclass in adifferent package?

    NEXT

  • 7/28/2019 FQS Question Compile

    5/40

    Protected members are accessible to subclasses in different package only throughinheritance. They cannot access the protected member using a reference to thesuper class.

    not follow any rules of method overriding.

    Can a protected member be accessed by a non-subclass in the samepackage?

    NEXT

    Yes. Protected member has same scope as default access plus subclasses indifferent package (through inheritance). Members having default scope are

    accessible to all classes within the same package. But the protected member can beaccessed by the non-subclass in same package only using a reference to the classcontaining the protected member.Protected = Default + SubclasseCan a protected member be accessed by anon-subclass in the same package?

    NEXT

    Yes. Protected member has same scope as default access plus subclasses indifferent package (through inheritance). Members having default scope are

    accessible to all classes within the same package. But the protected member can beaccessed by the non-subclass in same package only using a reference to the classcontaining the protected member.Protected = Default + Subclasses of different package

    s of different package

    What happens when a method argument is marked final?

    NEXT

    If an argument is marked final, it cannot be modified in that method ie. it cannot beassigned a new value.

    What are the different uses of keyword final in Java?

  • 7/28/2019 FQS Question Compile

    6/40

    NEXT

    Final class - A class that cannot be subclassed/extendedFinal method - A final method cannot be overridden by subclassesFinal variable - If an instance variable is marked final, it can be initialized only once

    and cannot be reinitialized. For primitive type variables, the value assigned oncecannot be changed. For reference variables, the variable cannot be reassigned torefer to a different object. However, the final reference variable allows the object itrefers to be modified. In Java a constant is defined my marking the variable staticand final.Final arguments - Method arguments and local variables can also be marked final.The local variable cannot be modified in What is the difference between final,finally and finalize?

    NEXT

    Final - Used to prevent class inheritance, method overriding or to declare aconstant.Finally - A finally block follows either a try or the last catch block. This block alwaysexecutes, irrespective of whether an exception occurred or not. It is generally usedto write cleanup code as it is guaranteed to run, even if a return is encountered inthe try block.Finalize - Finalize is a method of Object class which can be overridden. This method"may" be called by the garbage collector before the object is destroyed. There is noguarantee that code in the overridden finalize method will be executed.

    that method if marked final.

    What do you mean by var-args? How is it implemented in Java?

    NEXT

    Var-args are variable argument lists introduced in Java 5. Using this, a method mayaccept a variable number of arguments(0 to many). The arguments are stored in anarray of the declared type hence this argument should be treated as an array in themethod. Even constructors can have var-args. The following points are to be kept in

    mind:i) Syntax - Argument type followed by ellipsis(...) and then the argument nameExample: void fooMethod(int x, String... s)ii) Var-arg should be the last argument in the method signatureiii) There cannot be more than one var-arg in a methodVar-args have a great effect in overloading and overriding. A method with var-argin an overloaded list of methods will always be chosen last. Widening and boxingare chosen over var-args in overloading.

  • 7/28/2019 FQS Question Compile

    7/40

    Can you declare a method with more than one var-arg?

    NEXT

    No. A method can have only one var-arg.

    Can a constructor be marked private?

    NEXT

    Yes a constructor can be private. This is useful in Singleton design pattern wherethe constructor is made private so that no code can directly instantiate theSingleton class. Instantiation is controlled by a static method which creates a newobject only if the class in not instantiated before.

    class SingletonExample {private static SingletonExample instance=null;private SingletonExample() {}public static SingletonExample getInstance() {if(instance==null)instance = new SingletonExample();return instance;}}Can a constructor be marked abstract?

    NEXT

    A constructor cannot be marked abstract. However, abstract classes haveconstructors. They are called when a concrete subclass is instantiated.

    Can a constructor be marked static?

    NEXT

    A constructor cannot be marked static. A constructor is used for instantiationwhereas a static method is used to implement class specific behaviour. Staticmethods cannot access instance specific data. Hence, it is meaningless to mark aconstructor static.

    Can you access a static variable using object of the class?

  • 7/28/2019 FQS Question Compile

    8/40

    NEXT

    A static variable or class variable is accessed using dot operator on the classname(.). But it is not wrong to use an object reference to

    access the static member. The Java compiler allows this without error. All it caresabout is the type of the reference declared. Since from the declaration, it knowsthat the reference variable is of which class type, there is no problem using dotoperator on the reference to access a static member. The following code illustratesboth uses.class JavaStatic {static int foo = 0;public JavaStatic() {foo++;}public static void main(String... args) {JavaStatic job = new JavaStatic();

    System.out.println(JavaStatic.foo);System.out.println(job.foo);}}

    Where are local variables stored in memory?

    NEXT

    Local variables are stored in a segment of memory called stack. This includesprimitives and references to objects created using new keyword. The objectsthemselves will be created on the heap.

    Can an enum have a constructor?

    NEXT

    Yes an enum can have constructors. The constructor can be used to assignproperties to the enum constants. But they cannot be invoked explicitly. An enumcan have only a limited number of instances which are declared inside it. Theseinstances are known at compile time. The constructor is automatically invoked withthe argument(s) defined in the enum constants. We cannot directly invoke theconstructor.enum JavaCoder {NEWBIE(1), PROFICIENT(2), EXPERT(3);

  • 7/28/2019 FQS Question Compile

    9/40

    JavaCoder(int level) {this.level=level;}private int level; //propertypublic int getLevel() {return level;}}

    What is a static member?

    NEXT

    A static data member is used to hold class specific property, independent of anyinstances of the class. There is only one copy of a static variable shared across allinstances. Static members are initialized only once when the class is loaded in theJVM. If not initialized explicitly, primitives are initialized to 0 and references to nullby default.

    Member methods can also be marked static. This method may be called withoutcreating any instance, using dot operator on the classname. A static method canonly access other static members of the class.A class nested within another class can also be marked static.Again, we can mark an initialization block static as well. This block is also executedwhen the class is loaded. Static initialization blocks are used to provide logicalinitialization of class members, based on some conditions, looping or error handling

    .What is an initialization block? When is it executed?

    NEXT

    An initialization block is a block of code where some logical operation can beperformed. A static initialization block is executed when the class is first loaded inthe JVM. An instance initialization block is executed when an instance is created. It

    just runs once in both the cases. There may be multiple initialization blocks in aclass and they will be executed in the order of their appearance in the class.Instance initialization blocks will run after all super constructors have executed.Example:class InitBlockDemo {static int x;int y;

    static { x=10; } //this is a static init block{ y=20; } //this is an instance init block}

    What is the type of an enum constant (members of an enum)?

  • 7/28/2019 FQS Question Compile

    10/40

    NEXT

    Each member of an enum is of the same type ie the same enum type. Eg.enum JavaCoder { NEWBIE, PROFICIENT, EXPERT}

    In the above enum declaration, all members NEWBIE, PROFICIENT AND EXPERT,are constants of type JavaCoder.

    Can you invoke an enum constructor directly? If yes, how. If no, when willthe constructor get invoked?

    NEXT

    An enum constructor cannot be invoked directly. It is invoked automatically whenthe declared enum constants are created.

    What is ?Deadly Diamond of Death??

    NEXT

    In object-oriented programming, Deadly Diamond of Death is a condition ofambiguity which arises due to multiple inheritance. The phrase comes from theshape of the class diagram of the scenario showing the inheritance relations.

    Say classes B and C inherit from A. Class D inherits both from B and C. Now, if Dcalls a method of class A (which D does not override), which is overridden both byB and C. Then the situation becomes ambiguous as it is unclear which version of themethod will D inherit.

    How is multiple inheritance achieved in Java.

    NEXT

    Multiple inheritance is achieved in Java through Interfaces. In Java, a class cannotextend more than once class. However, it can implement multiple interfaces. Aninterface can be thought of as a purely abstract class where methods which allsubclasses should have are declared but not defined. The implementing classes candefine their own implementation of the interface methods.

  • 7/28/2019 FQS Question Compile

    11/40

    Explain runtime polymorphism in Java.

    NEXT

    Polymorphism is one of the core principles of object oriented programming.

    Polymorphism refers to the ability of having different implementations for oneparticular method. Java supports both compile time and runtime polymorphism.

    Runtime polymorphism is achieved in Java by method overriding.

    Say a base class A defines a method which is overridden by subclass B. Now, areference of type A (supertype) can point to an object of class B (subtype). Say, wecreate such a reference and assign an object of subclass B to it, and then invoke themethod on the reference.

    The JVM will be able to resolve the call to the subclass method at 'runtime' since theactual object held by the reference variable is that of subtype. This is also known as

    'dynamic dispatch'.

    class A {public void echoLine() {System.out.println("In base.....");}}

    class B extends A {public void echoLine() {System.out.println("In derived....");}}

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

    A ob = new B();ob.echoLine();}Can you create instance of an abstract class?

    NEXT

    We can never create instance of an abstract class. However, abstract classes canhave constructors and they are called when a subclass is instantiated. An abstractclass constructor cannot be invoked directly and will result in compiler error. It canonly be called from a subclass constructor using super.abstract class A {int x;A(int x) {this.x=x;}class B extends A {B(int x) {super(x);}Consider the following code:

  • 7/28/2019 FQS Question Compile

    12/40

    public class Car {public void start() {System.out.println(?Car started?);}

    }public class Fiat extends Car {

    protected void start() {System.out.println(?Fiat started?);

    }}

    Will this code compile?

    NEXT

    This code will not compile since the overriding method has a more restrictive access

    level (protected) than the overridden method (public).

    }

    }

    Can a method be overloaded in a subclass?

    NEXT

    Yes, Java allows method to be overloaded in a subclass. The normal rules foroverloading hold true for overloading in a subclass. We should not mix it methodoverriding.

    Can the return type of an overriding method be different from that ofoverridden method?

    NEXT

    No. The return type of an overriding method should be same as, or a subclass of,

  • 7/28/2019 FQS Question Compile

    13/40

    the return type declared in the overridden superclass method.

    What do you understand by covariant returns?

    NEXT

    Covariant returns are introduced in Java 5. As of Java 5, the return type of anoverriding method can be different from that of the overridden method as long asthe new type is a subtype of the declared return type of the overridden superclassmethod. Before Java 5, Can an overriding method in subclass throw anunchecked exception which is not declared in the overridden method ofsuperclass?

    NEXT

    Yes. An overriding method can throw any Runtime/Unchecked exceptions,irrespective of it being declared in the super class overridden method. Therestriction is only for checked exceptions.

    this would result in compilation error.

    Will the following code compile?class Foo {public void play() throws FileNotFoundException{

    //do Foo play}}class Bar extends Foo {

    public void play() {//do Bar play}}class TestFooBar {public static void main(String[] args) {

    Foo obj1 = new Bar();Bar obj2 = new Bar();

    obj1.play();obj2.play();}}

    NEXT

  • 7/28/2019 FQS Question Compile

    14/40

    This code does not compile. Here obj1 is declared as a supertype reference andassigned a subtype object. Since the play() method in superclass Foo declares achecked exception, the compiler thinks that obj1.play() is a method call whichdeclares a checked exception and which needs to be handled, although at runtime,the subclass method will be called.

    Can overloaded method in a subclass declare new checked exceptionwhich is not declared in superclass?

    NEXT

    Yes, can overloaded method can declare new or broader checked exceptions. Therestriction is in the case of overriding and not overloading.

    What will be the output?class Human { }class Employee extends Human { }class Test {public void assign(Human obj) {System.out.println(?Assigned to human?);}public void assign(Employee obj) {System.out.println(?Assigned to employee?);}

    public static void main(String[] args) {

    Human h = new Employee();Test t = new Test();

    t.assign(h);}

    }

    NEXT

    The output is "Assigned to human".This is a scenario of method overloading. Since the method calls are decided atcompile time, the compiler sees reference h as of type Human and hence binds thecall to the first assign method which takes Human object as argument.

    Java classes cannot extend more than one class. Can an interface extendmore than one interface?

  • 7/28/2019 FQS Question Compile

    15/40

    NEXT

    Yes, an interface can extend more than one interface.

    How will you instantiate a class with only private constructor?

    NEXT

    We can create a public static method in the class to instantiate and return aninstance of that class. This method can also be used to implement a singletonpattern where the static method will return a new instance only if the class is noneexists, else it returns the same instance.

    Can you define a constructor in an abstract class? If yes, when will it beinvoked?

    NEXT

    Yes, abstract classes can have constructors. They are invoked when a subclass isinstantiated. An abstract class constructor cannot be invoked directly and will resultin compiler error. It can only be called from a subclass constructor using super.abstract class A {int x;A(int x) {this.x=x;}class B extends A {B(int x) {super(x);}}

    How will you invoke another constructor of the same class from within aconstructor?

    NEXT

    This is done using this(). If the constructor to be called accepts an argument, thenthe parameter should be passed while invoking this().

  • 7/28/2019 FQS Question Compile

    16/40

    What is the output of toString method?

    NEXT

    The return type of toString() method is String. The toString method for class Objectreturns a string consisting of the name of the class of which the object is aninstance, the at-sign character `@', and the unsigned hexadecimal representationof the hash code of the object. In other words, this method returns a string equal tothe value of:getClass().getName() + '@' + Integer.toHexString(hashCode())Java specs recommend this method to be overridden to return a more meaningfulinformation about the object.

    What is the default behaviour of equals() method? When should youoverride equals() method?

    NEXT

    The equals method of Object class uses == operator to compare two objectreferences, which returns true iff both the non-null references point to the sameobject.The equals() method should be overridden for a more meaningful comparisonbased on some class property or condition. The best example is the String class ofJava API which overrides the equals method. The String class returns true if wecompare two different String objects having same value.If we want to use our class in a data structure which compares two instances forequivalence, then we should override equals() method. The Collection frameworkdata structures of type Set and Map expect the objects and keys respectively, beingused in the collection to override equals. The Set will not be able to maintainuniqueness and we will not be able to use our class instances as keys in a Map if wedo not override equals.

    Which Collection classes use hashCode() method?

    NEXT

    The hashCode based Set implementations are HashSet and LinkedHashSet.Implementations of Map interface using hashcode are Hashtable, HashMap andLinkedHashMap.

  • 7/28/2019 FQS Question Compile

    17/40

    What is the return type of hashCode() method?

    NEXT

    The return type of hashCode() method is int.

    What does hashCode() method return by default?

    NEXT

    The Java specifications have a hint that the default implementation forObject.hashCode() returns an integer derived from the memory address of theobject. But this is not a requirement and may vary upon different JVM

    implementations.

    If two objects are considered equal, does it imply that their hashCode()values are equal as well?

    NEXT

    Yes. The Java specification has a contract for hashCode method stating that:"If two objects are equal according to the equals(Object) method, then calling thehashCode method on each of the two objects must produce the same integer

    result."What happens when you use a transient variable to calculate thehashCode() value?

    NEXT

    A transient variable should not be used to calculate the hashCode value. The reasonis that transient variables are not serialized and they come with a default valuewhen a previously serialized object is deserialized. Hence, after deserialization, thehashCode value of the object will be different from the value before serialization. Ifthe object was used as a key in a Map previously, we will not be able to match the

    key with the new deserialized object as the equals method will fail.

    Which classes/interfaces are derived from the Collection interface?

    NEXT

  • 7/28/2019 FQS Question Compile

    18/40

    The Collection interface hierarchy is as follows:Collection (interface)|

    _________________________________|________________________| | |Set (interface) List (interface) Queue (interface)

    | | |_______|_______ |--ArrayList |--PriorityQueue| | | |HashSet SortedSet (interface) |--Vector || | | |LinkedHashSet NavigableSet (interface) |-------LinkedList-------||TreeSetIs TreeMap part of the Collection interface inheritance tree?

    NEXT

    TreeMap is not part of the Collection interface inheritance tree. TreeMap is adescendant of Map interface which does not extend the Collection interface.

    What is the difference between ArrayList and Vector?

    NEXT

    Vector methods are synchronized for thread-safety while methods of ArrayList arenot. Hence, ArrayList is not safe to be shared between multiple threads.Since vector methods are synchronized, it add a performance hit as well. ArrayListoperates much faster than Vector.Vector is a data structure available since old Java versions (JDK 1.0) while ArrayListwas added later. Vector class was refactored to implement List interface forinclusion in the collection framework.Both Vector and ArrayList can be iterated over by calling the iterator and listIteratormethods which return iterators which are fail-fast. However, Vector also has anelements() method which returns an Enumeration of the Vector elements. ThisEnumeration is not fail-What is the difference between HashMap andHashtable?

    NEXT

    Methods of Hashtable are synchronized for thread-safety while those of HashMapare not.A HashMap allows null values and one null key. Hashtable does not allow any key or

  • 7/28/2019 FQS Question Compile

    19/40

    value to be null.Due to thread-safe behaviour of Hashtable, a HashMap gives better performanceover Hashtable.Iterator for HashMap is fail-fast while the enumerator for Hashtable is not so.

    fast.

    If you need to insert an element in the middle of list, whichimplementation of List interface will be fastest?

    NEXT

    LinkedList is a better choice for insertion in the middle. The complexity of insertionfor LinkedList is O(1).

    Which list will you choose when you need fast iteration over the list?

    NEXT

    ArrayList is the better option for fast iteration. It is index based and providesretrieval operations in constant time. ArrayList also implements the RandomAccessmarker interface which signifies that it is fast for accessing elements from themiddle.

    What is the importance of equals() method for Set and Mapimplementations?

    NEXT

    How do HashSet and LinkedHashSet differ? Give a scenario when you willuse LinkedHashSet.

    NEXT

    HashSet is unordered while LinkedHashSet is the ordered version of HashSet. Itmaintains a doubly-linked list across the elements and maintains insertion order.

    PREV

  • 7/28/2019 FQS Question Compile

    20/40

    What will happen if you create a HashSet and do not override thehashCode() method?

    NEXT

    The default Object.hashCode() implementation returns a unique value for eachobject. If we create a HashSet and do not override hashCode method for the classused, then objects considered to be meaningfully equal will be allowed in the set asequals method will fail for them. Thus the HashSet will not be able to maintainuniqueness.

    What is the difference between Comparable and Comparator interface?

    NEXT

    A LinkedHashMap will be a better choice over HashMap for faster iteration as itmaintains a double-linkedWhich kind of tree does TreeMap and TreeSet use?

    NEXT

    Both TreeMap and TreeSet use a Red-Black tree structure.

    list across all the elements.

    Which kind of tree does TreeMap and TreeSet use?

    NEXT

    Both TreeMap and TreeSet use a Red-Black tree structure.

    What do you mean by typed and untyped collection (generics)?

    NEXT

    Generics were introduced in Java 5. They are used in Collection Framework tocreate type-safe collections.Before Generics, there was no way to specify to the compiler the type of thecollection being created. The declaration of an ArrayList containing String wouldbe :

  • 7/28/2019 FQS Question Compile

    21/40

    List strList = new ArrayList();Although this list might be meant for containing Strings only, it could not bespecified in any way. The compiler will not throw any errors/warnings if some othertype is inserted in to the list. However, while retrieval, a cast will be required. Thereis a possibility of the compiler throwing a ClassCastException at runtime if thecorrect object was not inserted in the list.

    for(Iterator i = strList.iterator();i.hasNext();) {String str = (String)i.next(); //Probability of getting ClassCastExceptionSystem.out.println(str);}These pre-Java 5 collections are called untyped or raw type collections.To detect these type-unsafe operations at compile time, Java 5 makes use of typedcollections. Now an arraylist meant to contain Strings can be declared as:List strList = new ArrayList();This declaration eliminates the need of a cast when the list element is taken out.The compiler verifies at compile time if the type constraints are being violated.

    What do you mean by autoboxing?

    NEXT

    Autoboxing is a feature introduced in Java 5. Due to this, primitives can now beautomatically boxed and unboxed to the corresponding Wrapper classes. BeforeJava5, incrementing an Integer value involved explicitly unwrapping the Integerobject, incrementing the int value, rewrapping it back to the Integer object. Thisresulted in unwanted extra code. With autoboxing and unboxing, the code will bemuch simpler.

    Integer i = new Integer(10);i++; //automatically unwraps object i, increments the int value and rewraps itagainAutoboxing is also useful in collections since they expect the primitive valueswrapped in proper objects. The boxing and unboxing can be done implicitly by thecompiler.Map myMap = new TreeMap();myMap.put("Hello",100); //the int value is automatically boxed to Integer object

    What do you mean by a backed collection?

    NEXT

    There are some methods in the Java API which return collections which are backedby the other ie changes to one collection affects the other as well. The most

  • 7/28/2019 FQS Question Compile

    22/40

    common methods are:For TreeSet --headSet(e, b)tailSet(e, b)subSet(a, b)For TreeMap--

    headMap(k, b)tailMap(k, b)subMap(a, b)Say, we create a subSet from a TreeSet and add new elements to the originalTreeSet. The new elements will also be reflected in the subSet (provided they fall inthe range of the subSet). The opposite condition will also be true.There are many other methods in the API (like

    java.util.Collections.newSetFromMap(map)) which return backed collections. Thisnature can be known from the documentation of the methods.

    How do you an array to list and vice versa?

    NEXT

    The method Arrays.asList(T... a) returns a fixed-size list which is backed by thearray ie. changes to the returned list write through to the array. This is the best wayto convert array to list.The simplest way to convert a list to array is using Collection.toArray(). Thismethod returns an array containing all elements of the collection. It allocates newmemory for the array and hence the returned array can be modified in any way.

    Can you assign an ArrayList of a subtype to a reference of ArrayList ofparent type?ArrayList carList = new ArrayList(); //will this work

    NEXT

    No we cannot assign an ArrayList of a subtype to a reference of ArrayList ofsupertype. Polymorphism does not apply to generic types.

    Is there any way you can pass an ArrayList of subtype (ArrayListarrChild) to a method accepting an ArrayList ofsupertype(method1(ArrayList arr))? Is there any limitation?

  • 7/28/2019 FQS Question Compile

    23/40

    NEXT

    This can be done using the wildcard . The method declaration needs to bechanged to method1(ArrayList

  • 7/28/2019 FQS Question Compile

    24/40

    backward.Using ListIterator, we can get the index of the element given by a subsequent callto next() or previous(). This is not possible using Iterator (Iterator also iteratesover collections where index is not maintained.)A ListIterator can add an element at any point using add(E e) or modify an elementusing set(E e).

    Can you make a HashMap synchronized?

    NEXT

    There are two ways to make a HashMap synchronized. The option should be chosenbased on the application.One option is to use Collections.synchronizedMap(Map m) which returns athread-safe map backed by the specified map. This method uses simple lockingmechanism and allows serial access. Only one operation is allowed on the map atany point of time. However, it should be kept in mind that the returned map stillneeds manual synchronization if it needs to be iterated over as the map methodsare independently synchronized. This options brings in much performanceoverhead due to blocking operations but provides better data-consistency. Thisshould be chosen for write-intensive operations.The second option is to use a ConcurrentHashMap. This class uses optimizedtechniques to provide full concurrency of retrievals and adjustable expectedconcurrency for updates. It does not synchronize on the entire map but only on apart of it. Read operations are non-blocking and may overlap with an update. Itprovides better performance than Collections.synchronizedMap(Map) and shouldbe used in multiple read, less frequent write operations.

    What are fail-safe and fail-fast iterators?

    NEXT

    A fail-fast iterator throws ConcurrentModificationException if the collection isstructurally modified while iterating over it. As per the Javadoc: "In the face ofconcurrent modification, the Iterator fails quickly and cleanly, rather than riskingarbitrary, non-deterministic behavior at an undetermined time in the future."A fail-safe iterator allows modification to the collection during iteration and does notthrow this exception as it works on a clone of the collection.

    Can an inner class be static?

  • 7/28/2019 FQS Question Compile

    25/40

    NEXT

    Yes, but they are referred to as static nested class.

    Can there be an inner class inside a method?

    NEXT

    Yes, method-local inner classes can exist.

    f you have a class inside another class, how many class files will you get oncompilation?

    Can you identify the inner class by looking at the class file name?

    NEXT

    Since the inner class is also a separate class, there will be a separate class file forit on compilation. So there will be two class files. The class file name for the innerclass will be prefixed by the outer class name and a $ symbol(OuterClass$InnerClass.class).Can you invoke a regular inner class usingjava tool?java OuterClass$InnerClass

    NEXT

    No. The regular inner can be invoked only through an instance of the outer class.

    How can you access a regular inner class (class defined within anotherclass)?

    NEXT

    To access a regular inner class, an instance of the outer class is required. If theinner class is instantiated inside an outer class method itself, it can be done usingthe inner class name only since already one instance of the outer class exists,through which the outer class method will be called.

  • 7/28/2019 FQS Question Compile

    26/40

    Can a non-static inner class contain a static method?

    NEXT

    No. A non-static inner class is associated with an instance of the outer class. Itcannot contain any static methods. There will be no way to access the static methodsince to access the inner class, we need to go through an outer class instance.

    Can an inner class access private members of the outer class?

    NEXT

    Yes. An inner class (regular/non-static) is nothing but a member of the outer class.

    Hence it can access the private members of the outer class just like any othermember of that class.

    How will you instantiate a non-static inner class from any code outside theouter class?

    NEXT

    We need an instance of the outer class to instantiate a regular inner class outsidethe enclosing class. The instance will be created in the following way:OuterClass outer = new OuterClass();OuterClass.InnerClass inner = outer.new InnerClass();

    How will you access the outer class reference to which the inner class isbonded, inside the inner class?

    NEXT

    The inner class can get the enclosing class reference using

    .this.

    Can the access modifiers public, private and protected be applied to innerclass?

    NEXT

  • 7/28/2019 FQS Question Compile

    27/40

    Yes. Since the inner class is just like any other member of the class (instancevariables, methods), the access modifiers public, private and protected can beapplied to it.

    Can an inner class be abstract?

    NEXT

    Yes, inner class can be marked abstract.

    Can an inner class be final?

    NEXT

    Yes,.

    Why is it not possible to access a local variable inside a method-local innerclass defined in the same method?

    NEXT

    Local variables are created on the stack and exist only as long as the life of themethod call. But all objects are created on the heap. It may be possible that the

    method-local inner class instance is still alive after the method ends. This mayhappen if the reference to it is passed to some other code. If the inner class used alocal variable, it would not be alive at that point of time. Thus, method local innerclasses are not allowed to use local variables.

    inner class can be marked final.

    Can a method-local inner class be marked public, private or protected?

    NEXT

    Method-local inner classes cannot be marked public, private or protected.

    Can you define an inner class within a static method?

    NEXT

  • 7/28/2019 FQS Question Compile

    28/40

    Yes, a static method can contain an inner class.

    Is it possible to override a method in an anonymous inner class?

    NEXT

    Yes. The main purpose of creating an anonymous inner class is to override one ormore methods of the superclass.

    In how many ways can you create a thread and which method is a better

    way? Explain.

    NEXT

    A thread can be created in two ways.i) Extend the java.lang.Thread class and override the run() method.class FooThread extends Thread {public void run() {System.out.println("Running foo task...");}}ii) The second approach is to implement the Runnable interface.class FooRunnable implements Runnable {public void run() {System.out.println("Running foo task...");}}It is always better to take the second approach to create a thread. Firstly, extendingthe Thread class to create a thread is not exactly compliant to the OOP principles.A subclass is a more specialized version of the superclass. By extending the Threadclass, we are not making any specialized version of Thread, having any specificproperties. However, we do want our thread to have the ability to be run. Hence,implementing Runnable is the correct approach.Secondly, if we extend Thread class, if restricts our thread to extend any other classwhile it is not so while implementing Runnable.

    What happens when you call the join() method on a Thread instance?

    NEXT

    If join is called on a thread instance t, ie t.join(), then the 'currently running thread

  • 7/28/2019 FQS Question Compile

    29/40

    is joined to the end of t'. This means that the currently running thread will leave therunning state and will not become runnable until thread t has finished executing. Ifwe use the overloaded version of join(long millis), then the current thread waits forat most millis milliseconds for t to die.

    When a thread enters a synchronized method, which lock does it obtain?What happens when the method is static?

    NEXT

    When a thread enters a non-static synchronized method, it obtains the lockassociated with the current instance of the object on which the method is executing.

    If the method is a static one, then it acquires a lock on that class itself. Every classloaded in JVM has a corresponding instance of java.lang.Class. Locking on the class

    means locking on the instance of java.lang.Class which represents that class.

    Can main() method be overloaded?

    NEXT

    Yes, main method can be overloaded. However, the JVM recognizes only the staticmain with String[] as parameter and void return type, as the program entry point.Any overloaded versions of main will be ignored by the JVM for execution entry

    point and needs to be called manually.

    Can main() method be declared final?

    NEXT

    Yes. Making the main() method final will not result in any error and code will runwithout any altered behaviour. Since main() is a static method, it is implicitly notallowed to be overridden by the subclasses. Hence, there is no use of making main()final.

    What is a marker interface?

    NEXT

    A marker interface is an interface without any fields or methods. It is used to

  • 7/28/2019 FQS Question Compile

    30/40

    associate or enable a class with specific functionality. Specific methods whichprovide the functionality test whether the object passes instanceOf test for themarker interface. Examples are RandomAccess, Cloneable, Serializable etc. To testif an object is serializable, the ObjectOutputStream method writeObject() willcheck if the object is instanceOf Serializable. If not, it throws aNotSeriazableException.

    Can a class be defined inside an interface?

    NEXT

    Yes, an interface can contain a class definition. The class will be a nested classwithin the interface and will be public and static implicitly.

    What is meant by upcasting and downcasting?

    NEXT

    Upcasting means casting a reference variable up in the inheritance tree to a moregeneral type. Upcast generally happens implicitly and does not need an explicit cast.This is because a subclass is guaranteed to do everything that a superclass can do.

    Cat c = new Cat();Animal c1 = c; //implicit upcast

    Downcasting means casting a reference variable down the inheritance tree to amore specific type. It is always recommended to use instanceOf test beforedowncasting to avoid runtime failures.Animal c = new Cat();if(c instanceOf Cat)Cat c1 = (Cat)c; //explicit downcast

    Can there be an abstract class with no abstract methods?

    NEXT

    Yes it is possible.

    Consider a scenario when a thread enters a synchronized method of anobject. The thread goes to sleep before exiting the method. Can other

  • 7/28/2019 FQS Question Compile

    31/40

    threads access any other synchronized method of that object? What aboutnon-synchronized methods?

    NEXT

    A thread does not release its lock while it is sleeping. Thus, any other thread whichcannot access other synchronized methods on the same object. However, access tonon-synchronized methods is not restricted.

    When we say Myclass.class, what does it represent?

    NEXT

    Every class loaded in JVM has a corresponding instance of java.lang.Class. Theexpression Myclass.class represents the instance of java.lang.Class whichrepresents Myclass.

    What is meant by static imports?

    NEXT

    Static imports is a new feature in Java 5. Static imports can be used where we wantto use static members of a class. It imports all static members of a class.import static java.lang.System.out;import static java.lang.Integer.*;public class StaticImportDemo {public static void main(String[] args) {out.println(MAX_VALUE);out.println(toString(99));}}

    What is the difference between String, StringBuffer and StringBuilderclass?

    NEXT

    String objects are immutable while StringBuffer/StringBuilder objects are mutable.

  • 7/28/2019 FQS Question Compile

    32/40

    The only difference between StringBuffer and StringBuilder is that StringBuffermethods are synchronized for thread-safety. StringBuilder was introduced in Java1.5. StringBuilder should be used for faster performance if thread-safety is notdesired.

    Why are Strings called immutable objects?

    NEXT

    String objects are immutable because once a String object is created, it is nevermodified. If we call concat() on a String object, the compiler creates a new Stringobject containing the concatenated string and returns the new object. If areference to this object is not saved, the concatenated value will be lost. Theoriginal String object was not modified.

    PREV

    What is the difference between the two String initialization syntax?String s = ?newstring?; and String s = new String(?newstring?);

    NEXT

    In the first syntax, just one String object is created and one reference variablepointing to it. The object is created in the String constant pool maintained by JVM.

    In the second case, two String objects are created. Since new is called, one Stringobject is created in the normal memory. Also, the string constant "newstring" willbe placed in the String constant pool.

    What will be the output if the following code lines execute?String s = ?hello?;s.concat(? world?);

    System.out.println(s);

    NEXT

    The output will behelloThe concat method does not change the original string object but returns a new

  • 7/28/2019 FQS Question Compile

    33/40

    concatenated string which was lost in this case.

    When should you choose to use StringBuffer instead of String objects andwhy?

    NEXT

    StringBuffer should be used when the String will undergo a lot of modifications.Since String objects are immutable, each time a String object is modified, a newobject is created. This is a waste of memory since so many waste objects will fill upthe heap. In case of StringBuffer, the modification is done on the same object.

    What will be the output for following lines of code?

    StringBuffer s = new StringBuffer(?hello?);

    s.append(? world?);System.out.println(s);

    NEXT

    This code will printhello world

    What is the purpose of java.io.Console class added in Java 6?

    NEXT

    java.io.Console class can be used to access the character-based console deviceassociated with the JVM. Existence of the console is dependent on the underlyingplatform and also how the JVM is invoked. The unique instance of the console isobtained by calling System.console(). It returns null if a console is not present. TheConsole class has methods to read lines and password and also write formattedstring to the console.

    What is meant by Serialization and how is it achieved in Java?

    NEXT

    Serialization means saving the state of a Java object.To implement serialization, Java uses high-level methods in

  • 7/28/2019 FQS Question Compile

    34/40

    java.io.ObjectOutputStream and java.io.ObjectInputStream. The class beingserialized must implement Serializable interface. Here is a small example:class SerialDemo implements Serializable {public static void main(String[] args) {SerialDemo se = new SerialDemo();try {

    ObjectOutoutStream os = new ObjectOutputStream(newFileOutputStream("SerialDemo.ser"));os.writeObject(se);os.close();} catch(Exception e) {e.printStacktrace();}try {ObjectInputStream is = new ObjectInputStream(newFileInputStream("SerialDemo.ser"));se = (SerialDemo)is.readObject();is.close();

    } catch(Exception e) {e.printStacktrace();}}}

    How does serialization happen for an object which contains a reference toan object of another user-defined class?

    NEXT

    When an object is serialized, a deep-copy of that object takes place and thecomplete object-graph is saved. So, if the object contains references to otherobjects, the state of those objects will also be saved., provided they are alsoSerializable. If the object being referred to is not Serializable, the compiler willthrow a java.io.NotSerializableException.

    I would like to serialize an object which contains a non-serializable objectreference. How will I achieve this? What will be the value of thenon-serializable object reference upon deserialization?

    NEXT

    The non-serializable object reference can be marked transient. In this way, thecompiler will allow serialization of the object, without saving the state of thenon-serializable object which is referred inside it. On deserialization, the member

  • 7/28/2019 FQS Question Compile

    35/40

    object reference will point to null.

    I would like to serialize an object of class A (which is serializable). Butclass A contains a reference to class B object which is not serializable. Isthere any way to get an object of same state (including state of class B

    object) upon deserialization?

    NEXT

    Yes. We can implement a couple of private methods in the class we want to serialize.The code to save the state of the non-serializable object manually can be includedin these methods. The methods are:private void writeObject(ObjectOutputStream os) {

    // code to save non-serializable object state}

    private void readObject(ObjectInputStream is) {// code to read non-serializable object state}If these methods are present, they will be called during serialization/deserializationprocess. We must call defaultWriteObject() and defaultReadObject() first in themethods for the normal serialization to happen. Then the extra information aboutthe non-serial object can be saved/retrieved.

    class Serial implements Serializable {transient int i = 99;

    }

    What will be the value of variable i upon deserialization?

    NEXT

    The value of i will be 0 because transient variables are given the default value fortheir data type upon deserialization.

    Can we serialize an instance of a class having non-serializable super

    class? .

    NEXT

    Yes. It is allowed. In this case, only the state of the serializable subclass wil bemaintained. Any state inherited from the non-serializable superclass will be reset tothe default/initially assigned values upon deserialization. This is so because, upon

  • 7/28/2019 FQS Question Compile

    36/40

    deserialization, the constructor for first the non-serializable superclass, and allconstructors above that class in the inheritance tree will run.

    class A {int i ;public A() {i=100;}

    }class B extends A implements Serializable {int j =11;

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

    B ob = new B();ob.i=200;ob.j=99;

    //code to serialize ob}}

    What will be the value of j if we deserialize ob? What will be the value ofthe inherited variable i?

    NEXT

    The value of j will be 99. The value of i will be 100.

    Is the following code snippet legal?try {

    //some code}finally { //some code}

    NEXT

    Yes this is a perfectly legal code. The try block needs to be followed by at least acatch or a finally block or both. Try without catch is ok as long as a finally block ispresent after it. There cannot be a try block without both catch and finally.

    PREV

    Which is the parent class of Exception class?

    NEXT

  • 7/28/2019 FQS Question Compile

    37/40

    java.lang.Throwable

    Differentiate between Error and Exception? Is it possible to handle anerror?

    NEXT

    An Exception represents a situation which may have occurred if somecondition/resource required for normal execution of a program is not present.Rarely, exceptions can also occur due to a programming error. An exception can behandled to avoid program failure. Exceptions which are subclasses ofRuntimeException need not be handled in the code. All other exceptions arechecked exceptions and must be handled or declared.An Error is an unusual, fatal situation which may interrupt the normal execution of

    a program. The application generally cannot recover from an Error. Errors are takenan unchecked exceptions and need not be handled in the code. The code compilesfine without a handle for errors.Although an Error can be legally handled in a catch block (code will compile), itmakes no sense to handle an Error, because error conditions are usually fatal andprogram cannot recover from the situation. The code to handle the error may neverget a chance to execute. Examples of Error are OutOfMemoryError,StackOverflowError.

    What are checked and unchecked exceptions?

    NEXT

    Exceptions which are subclasses of RuntimeException and also all subclasses ofclass Error are unchecked exceptions. All other Exception classes are checkedexceptions.The application can generally recover programmatically from checked exceptions.The code needs to handle them using try-catch block or declare that the methodthrows this particular exception to the caller. Example of a checked exception isFileNotFoundException.Runtime exceptions may sometimes happen due to a programming error. Examplesare NullPointerException, ArrayIndexOutOfBoundsException etc. They need not behandled in the code. Errors are also unchecked exceptions. The applicationgenerally cannot recover from an Error. Examples of Error are OutOfMemoryError,StackOverflowError. The compiler does not need unchecked exceptions to behandled in the code.

    public void fun(){

  • 7/28/2019 FQS Question Compile

    38/40

    try {//may throw IOException}catch(IOException e) {throw e;}}Is the above code legal?

    NEXT

    No. This code will not compile.Since the code throws the IOException back to the caller after handling it in catch,the method fun() needs to declare that it throws an IOException.

    ArrayIndexOutOfBoundsException is a checked or unchecked exception?

    NEXT

    It is an unchecked exception. Parent class of ArrayIndexOutOfBoundsException isIndexOutOfBoundsException which is a subclass of RuntimeException.

    Is there a wrapper class for type "void" in Java?

    NEXT

    There is a class called java.lang.Void which represents the Java keyword void. Thisclass is not exactly a wrapper class for void. The constructor for the class is final andhence it cannot be instantiated. This class is used in the Java Reflection API torepresent the return type void for a method.

    What do you understand by reflection?

    NEXT

    Reflection is a feature which gives the ability to examine and modify the runtimebehaviour of an application. The reflection API can be used to inspect the programstructures and get information about the fields, methods, annotations, type etc atruntime. For example, the method getDeclaredMethods() returns an array of objectrepresentations of all methods declared for a particular class.

    What is meant by Atomic wrapper classes?

  • 7/28/2019 FQS Question Compile

    39/40

    NEXT

    Java 5 introduced some additional wrapper classes in java.util.concurrent.atomicpackage. These are:AtomicBoolean

    AtomicIntegerAtomicLongAtomicReferenceThey provide atomic operations for assignment, addition and increment. Theseclasses are mutable and cannot be used as a replacement for the regular wrapperclasses. The AtomicInteger and AtomicLong classes are subclasses of the Numberclass.What does the expression "Double.TYPE" represent?

    NEXT

    Double.TYPE represents the instance of java.lang.Class which respresents theprimitive type double.

    What is Cloneable interface?

    Cloneable interface is a marker interface. This interface is implemented by a classwhich allows a field-for field copy of its objects. The class implementing Cloneableinterface must override Object.clone() method with a public method. Invoking

    Object.clone() method on an instance that does not implement the Cloneableinterface results in the exception CloneNotSupportedException.

    Is the constructor called when clone() is called on an object?

    No. No constructor is called when ab object is cloned. Hence, while implementingclone(), care should be taken to do proper initializations of the cloned object.

    In which scenario will you clone an object?

    Cloning an object will be useful if I need a copy of the object at runtime but do notwant to modify the original object. Creating a new object using new will initializethe state to default values. This will not be desired when a copy of the object isneeded.

    Which design pattern uses the concept of cloning objects?

  • 7/28/2019 FQS Question Compile

    40/40

    Prototype Pattern uses cloning. This pattern uses a prototypical instance which iscloned to create new objects.

    Object.clone() returns a deep or shallow copy of an object?

    The default implementation in Object.clone() method returns a shallow copy.

    When does the finalize() method run?

    Finalize is a method of Object class which can be overridden. This method "may" becalled by the garbage collector before the object is destroyed. There is noguarantee that code in the overridden finalize method will be executed.


Recommended