FQS Question Compile
FQS Question Compile
FQS Question Compile
NEXT
Encapsulation: Encapsulation refers to creation of self-contained data types, containing properties and behaviour. The code to manipulate data, and actual data to be manipulated are modularised into a single logical entity. In terms of Java, this entity is called class which can contain data members(property) and member methods(behaviour). The physical instance of class is an object. The binding of properties and methods together provides controlled access to the data members and hence ensures security of data. Encapsulation is thus also associated with data hiding. Abstraction: Abstraction is closely linked with encapsulation. Encapsulation prevents data from being accessed direclty. Abstraction refers to the feature of providing the functionality required, without disclosing the details of implementation. The actual processing is kept hidden from outside world. Inheritance: Inheritance facilitates class hierarchy. It is a major principle of Object Oriented Programming. The main idea behind OOP was to avoid code repetation. Inheritance allows the data and methods (structure and behaviour) of a parent class to be passed down to the subclasses in class hierarchy. The subclasses may implement more specific behaviour independently. A common example is that of Vehical. All vehicals have some features and behaviour in common. But, a Truck may have some specific characteristics which are different from a Car. The Truck class and Car class will both inherit properties and methods of Vehical class, and they can additional ones in their class respectively. Moreover, they can also override the parent class behaviour. One more advantage of inheritance is that it makes adding a functionality much easier. Say, if a new method is required, it is easy to create a new subclass and add the required functionality. All current features will be inherited by the subclass. Polymorphism: Polymorphism means having many forms. It allows a method to have more than implementation, depending upon certain conditions. There are two kinds of polymorphism: Static or compile-time polymorphism and dynamic or runtime polymorphism. Static polymorphism is implemented through method overloading. A method having same name can have multiple implementations, depending upon the argument(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 method will be called by looking at the signature of the called method. In runtime polymorphism, a subclass may override a superclass method for more
specific behaviour. The decision of which method to call is made at runtime. The calling code may declare the object to be of parent type. At runtime, depending upon the actual type of the object, the correct method will be invoked. An example may be of open() method for superclass Document. The subclasses doc and xls both override open() method. But it may not be known beforehand which document will be opened. At runtime, depending upon the object on which open() is called, the correct Document object's open() method will be invoked.
There is a logical difference between abstract class and interface. Conceptually, a class should extend another class when it exhibits a more specialized behaviour of the 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 necessary for it to be a specialized version of the interface. It should be noted that an interface name is always an adjective, eg. Runnable. Hence, although a set of properties and behaviour may be given to a class both through abstract class and interface, an abstract class is used for defining the core identity of a class with a more specialized behaviour 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 the signature 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 thought of as a purely abstract class. For this reason, adding new functionality to abstract class is easier since default implementation may be provided in the abstract class itself. Whereas in case of interface, all implementating classes need to be modified to adjust the new method. A Java class has the liberty of implementing multiple interfaces, but can extend only 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
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_foo foo# 5foo -foo
$foo - Valid. _bar - Valid ___foo__bar - Valid __5_foo - Valid foo# - Invalid. # is not allowed in a legal identifier 5foo - Invalid. An identifier cannot start with a number -foo - Invalid. An identifier cannot contain - character..
NEXT
A Java class name can begin with a small case letter. The class will compile successfully. 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.
A final class is a class which cannot be extended. A common question is - does it not violate the major object oriented principle of inheritance? The answer is that there may be certain scenarios when the programmer wants complete confidence that the methods of her class will never be overridden. Final class is generally useful while building APIs or libraries. The best example 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 classes should only be used when there is a surety that the class is improvised to its maximum and there will nevCan an abstract class have non-abstract methods? NEXT
Yes, an abstract class can have non-abstract methods. er be need to specialize its behaviour.
An interface method can never be marked final. Interface methods are by default abstract. The sole purpose of interface is to be extended or rather implemented by another class. Hence, an implementing class is "required" to provide implementation for all interface methods. Any code marking interface methods final will give compilation error.
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 new subclass 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 a different package? NEXT
Protected members are accessible to subclasses in different package only through inheritance. They cannot access the protected member using a reference to the super class. not follow any rules of method overriding.
Yes. Protected member has same scope as default access plus subclasses in different package (through inheritance). Members having default scope are accessible to all classes within the same package. But the protected member can be accessed by the non-subclass in same package only using a reference to the class containing the protected member. Protected = Default + SubclasseCan a protected member be accessed by a non-subclass in the same package? NEXT
Yes. Protected member has same scope as default access plus subclasses in different package (through inheritance). Members having default scope are accessible to all classes within the same package. But the protected member can be accessed by the non-subclass in same package only using a reference to the class containing the protected member. Protected = Default + Subclasses of different package s of different package
If an argument is marked final, it cannot be modified in that method ie. it cannot be assigned a new value.
NEXT
Final class - A class that cannot be subclassed/extended Final method - A final method cannot be overridden by subclasses Final 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 once cannot be changed. For reference variables, the variable cannot be reassigned to refer to a different object. However, the final reference variable allows the object it refers to be modified. In Java a constant is defined my marking the variable static and 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 a constant. Finally - A finally block follows either a try or the last catch block. This block always executes, irrespective of whether an exception occurred or not. It is generally used to write cleanup code as it is guaranteed to run, even if a return is encountered in the 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 no guarantee that code in the overridden finalize method will be executed. that method if marked final.
Var-args are variable argument lists introduced in Java 5. Using this, a method may accept a variable number of arguments(0 to many). The arguments are stored in an array of the declared type hence this argument should be treated as an array in the method. 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 name Example: void fooMethod(int x, String... s) ii) Var-arg should be the last argument in the method signature iii) There cannot be more than one var-arg in a method Var-args have a great effect in overloading and overriding. A method with var-arg in an overloaded list of methods will always be chosen last. Widening and boxing are chosen over var-args in overloading.
Can you declare a method with more than one var-arg? NEXT
Yes a constructor can be private. This is useful in Singleton design pattern where the constructor is made private so that no code can directly instantiate the Singleton class. Instantiation is controlled by a static method which creates a new object 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 have constructors. They are called when a concrete subclass is instantiated.
A constructor cannot be marked static. A constructor is used for instantiation whereas a static method is used to implement class specific behaviour. Static methods cannot access instance specific data. Hence, it is meaningless to mark a constructor static.
NEXT
A static variable or class variable is accessed using dot operator on the classname (<classname>.<varname>). But it is not wrong to use an object reference to access the static member. The Java compiler allows this without error. All it cares about is the type of the reference declared. Since from the declaration, it knows that the reference variable is of which class type, there is no problem using dot operator on the reference to access a static member. The following code illustrates both 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); } }
Local variables are stored in a segment of memory called stack. This includes primitives and references to objects created using new keyword. The objects themselves will be created on the heap.
Yes an enum can have constructors. The constructor can be used to assign properties to the enum constants. But they cannot be invoked explicitly. An enum can have only a limited number of instances which are declared inside it. These instances are known at compile time. The constructor is automatically invoked with the argument(s) defined in the enum constants. We cannot directly invoke the constructor. enum JavaCoder { NEWBIE(1), PROFICIENT(2), EXPERT(3);
JavaCoder(int level) { this.level=level; } private int level; //property public int getLevel() {return level;} }
A static data member is used to hold class specific property, independent of any instances of the class. There is only one copy of a static variable shared across all instances. Static members are initialized only once when the class is loaded in the JVM. If not initialized explicitly, primitives are initialized to 0 and references to null by default. Member methods can also be marked static. This method may be called without creating any instance, using dot operator on the classname. A static method can only 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 executed when the class is loaded. Static initialization blocks are used to provide logical initialization 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 be performed. A static initialization block is executed when the class is first loaded in the 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 a class 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 }
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 will the constructor get invoked? NEXT
An enum constructor cannot be invoked directly. It is invoked automatically when the declared enum constants are created.
In object-oriented programming, Deadly Diamond of Death is a condition of ambiguity which arises due to multiple inheritance. The phrase comes from the shape 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 D calls a method of class A (which D does not override), which is overridden both by B and C. Then the situation becomes ambiguous as it is unclear which version of the method will D inherit. How is multiple inheritance achieved in Java. NEXT
Multiple inheritance is achieved in Java through Interfaces. In Java, a class cannot extend more than once class. However, it can implement multiple interfaces. An interface can be thought of as a purely abstract class where methods which all subclasses should have are declared but not defined. The implementing classes can define their own implementation of the interface methods.
Polymorphism is one of the core principles of object oriented programming. Polymorphism refers to the ability of having different implementations for one particular 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, a reference of type A (supertype) can point to an object of class B (subtype). Say, we create such a reference and assign an object of subclass B to it, and then invoke the method on the reference. The JVM will be able to resolve the call to the subclass method at 'runtime' since the actual 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 can have constructors and they are called when a subclass is instantiated. An abstract class constructor cannot be invoked directly and will result in 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); }Consider the following code:
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).
Yes, Java allows method to be overloaded in a subclass. The normal rules for overloading hold true for overloading in a subclass. We should not mix it method overriding.
Can the return type of an overriding method be different from that of overridden method? NEXT
No. The return type of an overriding method should be same as, or a subclass of,
Covariant returns are introduced in Java 5. As of Java 5, the return type of an overriding method can be different from that of the overridden method as long as the new type is a subtype of the declared return type of the overridden superclass method. Before Java 5, Can an overriding method in subclass throw an unchecked exception which is not declared in the overridden method of superclass? NEXT
Yes. An overriding method can throw any Runtime/Unchecked exceptions, irrespective of it being declared in the super class overridden method. The restriction 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
This code does not compile. Here obj1 is declared as a supertype reference and assigned a subtype object. Since the play() method in superclass Foo declares a checked exception, the compiler thinks that obj1.play() is a method call which declares 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 exception which is not declared in superclass? NEXT
Yes, can overloaded method can declare new or broader checked exceptions. The restriction 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 at compile time, the compiler sees reference h as of type Human and hence binds the call to the first assign method which takes Human object as argument.
Java classes cannot extend more than one class. Can an interface extend more than one interface?
NEXT
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 an instance of that class. This method can also be used to implement a singleton pattern where the static method will return a new instance only if the class is none exists, else it returns the same instance.
Can you define a constructor in an abstract class? If yes, when will it be invoked? NEXT
Yes, abstract classes can have constructors. They are invoked when a subclass is instantiated. An abstract class constructor cannot be invoked directly and will result in 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 a constructor? NEXT
This is done using this(). If the constructor to be called accepts an argument, then the parameter should be passed while invoking this().
The return type of toString() method is String. The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of: getClass().getName() + '@' + Integer.toHexString(hashCode()) Java specs recommend this method to be overridden to return a more meaningful information about the object.
What is the default behaviour of equals() method? When should you override equals() method? NEXT
The equals method of Object class uses == operator to compare two object references, which returns true iff both the non-null references point to the same object. The equals() method should be overridden for a more meaningful comparison based on some class property or condition. The best example is the String class of Java API which overrides the equals method. The String class returns true if we compare two different String objects having same value. If we want to use our class in a data structure which compares two instances for equivalence, then we should override equals() method. The Collection framework data structures of type Set and Map expect the objects and keys respectively, being used in the collection to override equals. The Set will not be able to maintain uniqueness and we will not be able to use our class instances as keys in a Map if we do not override equals.
The hashCode based Set implementations are HashSet and LinkedHashSet. Implementations of Map interface using hashcode are Hashtable, HashMap and LinkedHashMap.
The Java specifications have a hint that the default implementation for Object.hashCode() returns an integer derived from the memory address of the object. 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 the hashCode method on each of the two objects must produce the same integer result."What happens when you use a transient variable to calculate the hashCode() value? NEXT
A transient variable should not be used to calculate the hashCode value. The reason is that transient variables are not serialized and they come with a default value when a previously serialized object is deserialized. Hence, after deserialization, the hashCode value of the object will be different from the value before serialization. If the 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.
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 a descendant of Map interface which does not extend the Collection interface.
Vector methods are synchronized for thread-safety while methods of ArrayList are not. Hence, ArrayList is not safe to be shared between multiple threads. Since vector methods are synchronized, it add a performance hit as well. ArrayList operates much faster than Vector. Vector is a data structure available since old Java versions (JDK 1.0) while ArrayList was added later. Vector class was refactored to implement List interface for inclusion in the collection framework. Both Vector and ArrayList can be iterated over by calling the iterator and listIterator methods which return iterators which are fail-fast. However, Vector also has an elements() method which returns an Enumeration of the Vector elements. This Enumeration is not fail-What is the difference between HashMap and Hashtable? NEXT
Methods of Hashtable are synchronized for thread-safety while those of HashMap are not. A HashMap allows null values and one null key. Hashtable does not allow any key or
value to be null. Due to thread-safe behaviour of Hashtable, a HashMap gives better performance over 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, which implementation of List interface will be fastest? NEXT
LinkedList is a better choice for insertion in the middle. The complexity of insertion for 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 provides retrieval operations in constant time. ArrayList also implements the RandomAccess marker interface which signifies that it is fast for accessing elements from the middle.
What is the importance of equals() method for Set and Map implementations? NEXT
How do HashSet and LinkedHashSet differ? Give a scenario when you will use LinkedHashSet. NEXT
HashSet is unordered while LinkedHashSet is the ordered version of HashSet. It maintains a doubly-linked list across the elements and maintains insertion order.
PREV
What will happen if you create a HashSet and do not override the hashCode() method? NEXT
The default Object.hashCode() implementation returns a unique value for each object. If we create a HashSet and do not override hashCode method for the class used, then objects considered to be meaningfully equal will be allowed in the set as equals method will fail for them. Thus the HashSet will not be able to maintain uniqueness.
A LinkedHashMap will be a better choice over HashMap for faster iteration as it maintains 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.
Generics were introduced in Java 5. They are used in Collection Framework to create type-safe collections. Before Generics, there was no way to specify to the compiler the type of the collection being created. The declaration of an ArrayList containing String would be :
List strList = new ArrayList(); Although this list might be meant for containing Strings only, it could not be specified in any way. The compiler will not throw any errors/warnings if some other type is inserted in to the list. However, while retrieval, a cast will be required. There is a possibility of the compiler throwing a ClassCastException at runtime if the correct object was not inserted in the list. for(Iterator i = strList.iterator();i.hasNext();) { String str = (String)i.next(); //Probability of getting ClassCastException System.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 typed collections. Now an arraylist meant to contain Strings can be declared as: List<String> strList = new ArrayList<String>(); 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.
Autoboxing is a feature introduced in Java 5. Due to this, primitives can now be automatically boxed and unboxed to the corresponding Wrapper classes. Before Java5, incrementing an Integer value involved explicitly unwrapping the Integer object, incrementing the int value, rewrapping it back to the Integer object. This resulted in unwanted extra code. With autoboxing and unboxing, the code will be much simpler. Integer i = new Integer(10); i++; //automatically unwraps object i, increments the int value and rewraps it again Autoboxing is also useful in collections since they expect the primitive values wrapped in proper objects. The boxing and unboxing can be done implicitly by the compiler. Map<String,Integer> myMap = new TreeMap<String,Integer>(); myMap.put("Hello",100); //the int value is automatically boxed to Integer object
There are some methods in the Java API which return collections which are backed by the other ie changes to one collection affects the other as well. The most
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 original TreeSet. The new elements will also be reflected in the subSet (provided they fall in the 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. This nature can be known from the documentation of the methods.
The method Arrays.asList(T... a) returns a fixed-size list which is backed by the array ie. changes to the returned list write through to the array. This is the best way to convert array to list. The simplest way to convert a list to array is using Collection.toArray(). This method returns an array containing all elements of the collection. It allocates new memory 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 of parent type? ArrayList<Car> carList = new ArrayList<Toyota>(); //will this work
NEXT
No we cannot assign an ArrayList of a subtype to a reference of ArrayList of supertype. Polymorphism does not apply to generic types.
Is there any way you can pass an ArrayList of subtype (ArrayList<Child> arrChild) to a method accepting an ArrayList of supertype(method1(ArrayList<Parent> arr))? Is there any limitation?
NEXT
This can be done using the wildcard <?>. The method declaration needs to be changed to method1(ArrayList<? extends Parent> arr) which means the method will accept an ArrayList of Parent type or of any class (abstract/concrete) that passes the instanceOf test for Parent. The disadvantage is that this wildcard can be used only on condition that the method makes no modification to the passed ArrayList. The compiler will throw an error if any attempt to add to the ArrayList is made. The method should be a read only method.
<? extends ParentType> - Using this wildcard, a collection reference can be assigned an instance of a collection of type ParentType or any of its sub-types (anything passing instanceOf test for ParentType) <? super SubType> - Using this wildcard, a collection reference can be assigned an instance of a collection of type SubType or any of its super types. <?> - Using this wildcard, a collection reference can be assigned an instance of a collection of any type.
What is the difference between ArrayList<?> myList and ArrayList<Object> myList? NEXT
The ArrayList<?> accepts an ArrayList of any type. However, method accepting such an arraylist will not be able to add anything to it. ArrayList<Object> quite different from ArrayList<?>. ArrayList<Object> will only accept an ArrayList of type Object, not even its subtypes. However, addition to the list is permitted.What is the difference between java.util.Iterator and java.util.ListIterator? NEXT
ListIterator extends Iterator. The differences between the two are: Iterator is used to iterate over any type of collection. ListIterator iterates over List only, as the name suggests. Iterator traverses forward only while ListIterator traverses both forward and
backward. Using ListIterator, we can get the index of the element given by a subsequent call to next() or previous(). This is not possible using Iterator (Iterator also iterates over collections where index is not maintained.) A ListIterator can add an element at any point using add(E e) or modify an element using set(E e).
There are two ways to make a HashMap synchronized. The option should be chosen based on the application. One option is to use Collections.synchronizedMap(Map<K,V> m) which returns a thread-safe map backed by the specified map. This method uses simple locking mechanism and allows serial access. Only one operation is allowed on the map at any point of time. However, it should be kept in mind that the returned map still needs manual synchronization if it needs to be iterated over as the map methods are independently synchronized. This options brings in much performance overhead due to blocking operations but provides better data-consistency. This should be chosen for write-intensive operations. The second option is to use a ConcurrentHashMap. This class uses optimized techniques to provide full concurrency of retrievals and adjustable expected concurrency for updates. It does not synchronize on the entire map but only on a part of it. Read operations are non-blocking and may overlap with an update. It provides better performance than Collections.synchronizedMap(Map) and should be used in multiple read, less frequent write operations.
A fail-fast iterator throws ConcurrentModificationException if the collection is structurally modified while iterating over it. As per the Javadoc: "In the face of concurrent modification, the Iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future." A fail-safe iterator allows modification to the collection during iteration and does not throw this exception as it works on a clone of the collection.
NEXT
f you have a class inside another class, how many class files will you get on compilation? 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 for it on compilation. So there will be two class files. The class file name for the inner class will be prefixed by the outer class name and a $ symbol (OuterClass$InnerClass.class).Can you invoke a regular inner class using java 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 another class)? NEXT
To access a regular inner class, an instance of the outer class is required. If the inner class is instantiated inside an outer class method itself, it can be done using the inner class name only since already one instance of the outer class exists, through which the outer class method will be called.
No. A non-static inner class is associated with an instance of the outer class. It cannot contain any static methods. There will be no way to access the static method since 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 other member of that class.
How will you instantiate a non-static inner class from any code outside the outer class? NEXT
We need an instance of the outer class to instantiate a regular inner class outside the 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 is bonded, inside the inner class? NEXT
The inner class can get the enclosing class reference using <OuterClassName>.this.
Can the access modifiers public, private and protected be applied to inner class? NEXT
Yes. Since the inner class is just like any other member of the class (instance variables, methods), the access modifiers public, private and protected can be applied to it.
Can an inner class be final? NEXT Yes,. Why is it not possible to access a local variable inside a method-local inner class defined in the same method? NEXT
Local variables are created on the stack and exist only as long as the life of the method 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 may happen if the reference to it is passed to some other code. If the inner class used a local variable, it would not be alive at that point of time. Thus, method local inner classes are not allowed to use local variables. inner class can be marked final.
Yes. The main purpose of creating an anonymous inner class is to override one or more 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, extending the 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 Thread class, we are not making any specialized version of Thread, having any specific properties. 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 class while 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
is joined to the end of t'. This means that the currently running thread will leave the running state and will not become runnable until thread t has finished executing. If we use the overloaded version of join(long millis), then the current thread waits for at 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 lock associated 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 class loaded 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.
Yes, main method can be overloaded. However, the JVM recognizes only the static main 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.
Yes. Making the main() method final will not result in any error and code will run without any altered behaviour. Since main() is a static method, it is implicitly not allowed to be overridden by the subclasses. Hence, there is no use of making main() final.
associate or enable a class with specific functionality. Specific methods which provide the functionality test whether the object passes instanceOf test for the marker interface. Examples are RandomAccess, Cloneable, Serializable etc. To test if an object is serializable, the ObjectOutputStream method writeObject() will check if the object is instanceOf Serializable. If not, it throws a NotSeriazableException.
Yes, an interface can contain a class definition. The class will be a nested class within the interface and will be public and static implicitly.
Upcasting means casting a reference variable up in the inheritance tree to a more general 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 a more specific type. It is always recommended to use instanceOf test before downcasting to avoid runtime failures. Animal c = new Cat(); if(c instanceOf Cat) Cat c1 = (Cat)c; //explicit downcast
Yes it is possible.
Consider a scenario when a thread enters a synchronized method of an object. The thread goes to sleep before exiting the method. Can other
threads access any other synchronized method of that object? What about non-synchronized methods? NEXT
A thread does not release its lock while it is sleeping. Thus, any other thread which cannot access other synchronized methods on the same object. However, access to non-synchronized methods is not restricted.
Every class loaded in JVM has a corresponding instance of java.lang.Class. The expression Myclass.class represents the instance of java.lang.Class which represents Myclass.
Static imports is a new feature in Java 5. Static imports can be used where we want to 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 StringBuilder class? NEXT
The only difference between StringBuffer and StringBuilder is that StringBuffer methods are synchronized for thread-safety. StringBuilder was introduced in Java 1.5. StringBuilder should be used for faster performance if thread-safety is not desired.
String objects are immutable because once a String object is created, it is never modified. If we call concat() on a String object, the compiler creates a new String object containing the concatenated string and returns the new object. If a reference to this object is not saved, the concatenated value will be lost. The original 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 variable pointing 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 String object is created in the normal memory. Also, the string constant "newstring" will be 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 be hello The concat method does not change the original string object but returns a new
When should you choose to use StringBuffer instead of String objects and why? 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 new object is created. This is a waste of memory since so many waste objects will fill up the 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
java.io.Console class can be used to access the character-based console device associated with the JVM. Existence of the console is dependent on the underlying platform and also how the JVM is invoked. The unique instance of the console is obtained by calling System.console(). It returns null if a console is not present. The Console class has methods to read lines and password and also write formatted string to the console.
Serialization means saving the state of a Java object. To implement serialization, Java uses high-level methods in
java.io.ObjectOutputStream and java.io.ObjectInputStream. The class being serialized 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(new FileOutputStream("SerialDemo.ser")); os.writeObject(se); os.close(); } catch(Exception e) { e.printStacktrace(); } try { ObjectInputStream is = new ObjectInputStream(new FileInputStream("SerialDemo.ser")); se = (SerialDemo)is.readObject(); is.close(); } catch(Exception e) { e.printStacktrace(); } } }
How does serialization happen for an object which contains a reference to an object of another user-defined class? NEXT
When an object is serialized, a deep-copy of that object takes place and the complete object-graph is saved. So, if the object contains references to other objects, the state of those objects will also be saved., provided they are also Serializable. If the object being referred to is not Serializable, the compiler will throw a java.io.NotSerializableException.
I would like to serialize an object which contains a non-serializable object reference. How will I achieve this? What will be the value of the non-serializable object reference upon deserialization? NEXT
The non-serializable object reference can be marked transient. In this way, the compiler will allow serialization of the object, without saving the state of the non-serializable object which is referred inside it. On deserialization, the member
I would like to serialize an object of class A (which is serializable). But class A contains a reference to class B object which is not serializable. Is there 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 included in 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/deserialization process. We must call defaultWriteObject() and defaultReadObject() first in the methods for the normal serialization to happen. Then the extra information about the 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 for their data type upon deserialization.
Yes. It is allowed. In this case, only the state of the serializable subclass wil be maintained. Any state inherited from the non-serializable superclass will be reset to the default/initially assigned values upon deserialization. This is so because, upon
deserialization, the constructor for first the non-serializable superclass, and all constructors 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 of the inherited variable i? NEXT
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 a catch or a finally block or both. Try without catch is ok as long as a finally block is present after it. There cannot be a try block without both catch and finally.
PREV
Which is the parent class of Exception class? NEXT
java.lang.Throwable
An Exception represents a situation which may have occurred if some condition/resource required for normal execution of a program is not present. Rarely, exceptions can also occur due to a programming error. An exception can be handled to avoid program failure. Exceptions which are subclasses of RuntimeException need not be handled in the code. All other exceptions are checked 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 taken an unchecked exceptions and need not be handled in the code. The code compiles fine without a handle for errors. Although an Error can be legally handled in a catch block (code will compile), it makes no sense to handle an Error, because error conditions are usually fatal and program cannot recover from the situation. The code to handle the error may never get a chance to execute. Examples of Error are OutOfMemoryError, StackOverflowError.
Exceptions which are subclasses of RuntimeException and also all subclasses of class Error are unchecked exceptions. All other Exception classes are checked exceptions. The application can generally recover programmatically from checked exceptions. The code needs to handle them using try-catch block or declare that the method throws this particular exception to the caller. Example of a checked exception is FileNotFoundException. Runtime exceptions may sometimes happen due to a programming error. Examples are NullPointerException, ArrayIndexOutOfBoundsException etc. They need not be handled in the code. Errors are also unchecked exceptions. The application generally cannot recover from an Error. Examples of Error are OutOfMemoryError, StackOverflowError. The compiler does not need unchecked exceptions to be handled in the code.
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.
There is a class called java.lang.Void which represents the Java keyword void. This class is not exactly a wrapper class for void. The constructor for the class is final and hence it cannot be instantiated. This class is used in the Java Reflection API to represent the return type void for a method.
Reflection is a feature which gives the ability to examine and modify the runtime behaviour of an application. The reflection API can be used to inspect the program structures and get information about the fields, methods, annotations, type etc at runtime. For example, the method getDeclaredMethods() returns an array of object representations of all methods declared for a particular class.
NEXT
Java 5 introduced some additional wrapper classes in java.util.concurrent.atomic package. These are: AtomicBoolean AtomicInteger AtomicLong AtomicReference<V> They provide atomic operations for assignment, addition and increment. These classes are mutable and cannot be used as a replacement for the regular wrapper classes. The AtomicInteger and AtomicLong classes are subclasses of the Number class.What does the expression "Double.TYPE" represent? NEXT
Double.TYPE represents the instance of java.lang.Class which respresents the primitive type double.
Cloneable interface is a marker interface. This interface is implemented by a class which allows a field-for field copy of its objects. The class implementing Cloneable interface must override Object.clone() method with a public method. Invoking Object.clone() method on an instance that does not implement the Cloneable interface 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 implementing clone(), 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 not want to modify the original object. Creating a new object using new will initialize the state to default values. This will not be desired when a copy of the object is needed.
Prototype Pattern uses cloning. This pattern uses a prototypical instance which is cloned to create new objects.
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 no guarantee that code in the overridden finalize method will be executed.