Which is the Best Java Web Framework ?

Java - Things to know before your OCJP Exam


Classes and Interfaces

1. Default constructor initializes the primitives to their default values ( 0 for int , 0.0 for float etc ) and Instance variables to null.

2.  All members of Interfaces are intrinsically public.

3.* Members of the interface cannot be declared private.

4.* Variables of an interface are intrinsically public , static and final and can be accessed directly by the implementing class.

5.* An object is eligible for garbage collection when it looses all its references.

7. Last Reference assigned null doesn't make the object eligible for gc. Reference should be assigned to some other object.

8. System.gc doesn't enforce garbage collection immediately.

9. All wrapper classes are immutable.


Keywords

1. We can't declare a method abstract as well as final.

2. Keywords are case sensitive.

3.* Final variables can be initialized while declaration as well as within constructor.

4. instanceOf returns true if the specified object is the instance of class , interface or any parent class / interface.

5. instanceOf used with null returns false and not exception.

6.* import static com.x is a valid syntax whereas static import com.x is invalid.

7.* Final methods cannot be overridden.

8. Final class cannot be subclassed.


Switch Statement

1. Only Integers, char, String and Enum are allowed in Switch statement.

2.*If there are no break statements in case blocks, it will execute all statements either till the next break statement or end of switch block

3.*Default case will be executed if there is no match, and statements thereafter till break or end of switch

4. Characters and their ASCII value can be used interchangeably



Constructor

1. Constructors can be overloaded.

2. *Constructors shouldn't have any return types , not even void.

3. Default constructor is provided by the compiler if we don't declare any constructor. If we declare a parameterized constructor, Compiler will not create any default non parameterized constructor for the class.

4. A constructor can only have either this or super statement and that statement should be the first statement in constructor.

5. If Constructor has been declared private, Objects of the class cannot be instantiated using new operator.

Overloading


1.*Methods can be overloaded on number of arguments and type of arguments.

2. Static methods can be overloaded.

3. Constructors can be overloaded. this( ) is used to call constructors in chain.

4. *Methods cannot be over overloaded on the basis of return type alone.

5. When overloaded on the co variant types, conflict is resolved by the type of reference.

Overridding


1.*Overriding Method should have same syntax and return type as Overridden method. If the number and type of arguments varies, it becomes overloading. If the return type is different, compiler gives compilation error i.e "The return type is incompatible with BaseClass.overriddenMethod()".

2.*No Explicit cast is required in case of Upcasting i.e derived class reference is assigned to Base class reference but explicit cast is required in case of Downcasting i.e Base Class reference is assigned to Derived class reference.

3. Downcasting may throw ClassCastException if object is found to be non compatible during runtime. That's why instanceof check should be made before doing the downcast.

4.*Overridding method cannot throw checked exception wider than the exception thrown by the overriden method. If the overridden method doesn't throw any exception, overriding method can throw any exception.   

5.*We cannot reduce the visibility of the overridden method. Means If the method in base class is public, we cannot declare it private in derived class.

6. Only instance methods can be overridden. Static methods and instance / static variables cannot be overridden.

7.*Final methods cannot be overridden.

8. If a method cannot be inherited, It cannot be overridden. So private methods cannot be overridden.


Exceptions


1. ArithmeticException is the subclass of RuntimeException and is an unchecked exception.

2.* Compiler gives error if we don't handle checked exceptions whereas unchecked exceptions are optional to be handled.

3. Either we should catch the checked exceptions or the method should be declared to throw those exceptions.

4.* Catch blocks for try should handle exceptions from specific to general. Compiler gives error if we have generalize catch before specific.

5.* Finally block is always executed whether an exception occurs or not.

6.* When an exception is thrown, rest statements in the try block are not executed.

7. try and then finally without catch is legal in java.

8. try without catch or finally is not legal.

9.* An overriding method cannot throw an exception wider than the exception being thrown from the overriden method.


Nested Classes


1. Static inner class cannot access instance members of the enclosing class.

2. Local class declared within static method cannot access instance members.

3.* Static inner class can be accessed without instance of the parent class.

4.* In case of local inner classes , we can even instantiate using new with the interface.

new runnable (){
     public void run() {}
}

is valid whereas

new runnable(); isn't

5. An inner class can access all elements of the parent class , even declared private.

6.* To instantiate the inner class object following code is used

OuterClass.InnerClass innerRef = outerRef.new InnerClass();

7. From code within the inner class, this refers to inner class. To access outer class we should do OuterClass.this.

8. An anonymous inner class can either extend one class or implement one interface only.

9 Anonymous inner class should be ended with a semi colon after curly brace.

10.* Static inner class can be instantited like this

OuterClass.InnerClass inner = new OuterClass.InnerClass();


Serialization


1. Serializable is a marker interface i.e a class need not override any method if it implements serializable interface.

2. A Class should be declared serializable if its serializing or deserializing. In case a class has objectInputStream.readObject() or objectOutputStream.writeObject(), it should be declared serializable.

3. ObjectOutputStream and ObjectInputStream wraps the FileInputStream and FileOutputStreamrespectively.

4. An Object can be serialized only if all of the composed objects are also either serializable or declared transient.

5. If we want any of the instance variable not to be serialized, we should declare it transient.

6. static variables are never serialized.

7. If a parent class is declared serializable , all its derived classes intrinsically becomes serializable. 

8. Object Class is not serializable.

9. If you serialize a collection , all its elements should be serializable.

10. Collection Interfaces are not serializable but all concrete classes are. 


Utility Classes


1.*DateFormat is an abstract class. It provides a getDateInstance() static method to get Date Instance.

2. Following are valid Locale constructor

Locale ( String language )
Locale ( String language, String country )
Locale ( String language , String country, String variant )

3. While doing formatting using %f for float, it rounds the float to the closest value if less decimals are required. For ex - 3.97 becomes 3.4 if we do %.1f

4.*NumberFormat.setMaximumFractionDigits() method sets the max no of digits allowed in fraction portion of number.

5. Calendar is an abstract class and hence concrete subclass object should be instantiated using Calendar.getInstance(). Usually it returns the object of GeorgianCalendar.

6. Following DateFormat initialization are correct.

DateFormat df = DateFormat.getInstance();

DateFormat df = DateFormat.getDateInstance();
DateFormat df = DateFormat.getDateInstance(DateFormat.FULL);

8. Out of the following code , only 3rd is correct

Date date = DateFormat.newInstance(DateFormat.LONG, Locale.US).parse(str); 

Date date = DateFormat.newInstance(DateFormat.LONG, Locale.US).format(str); 

Date date = DateFormat.getDateInstance(DateFormat.LONG, Locale.US).parse(str);

9. split() and macthes() methods are there in Pattern as well as String class.


File I /O


1.*File Objects are not used to read or write data. The possible operations that can be performed with File is to make empty new files / directories, searching for files and directories, deleting files and directories and working with paths.

2. FileReader and FileWriter are usually wrapped by BufferedReader, BufferedWriter and PrintWriter for performance and convenience.

3. BufferedWriter provides a newline() method to create platform specific line separator automatically.

4.*After Java 1.5, PrintWriter can be build using File and String too along with OutputStream and FileWriter.

5. flush() is used to flush the residual characters in the buffer to the file. It should be the statement before close.

6.*file.createNewFile doesn't create the file and returns false if the file with the same name is already there.

7. file.mkdir() is used to create a new directory.

8. File constructor (File,String) can be used to create a file in the sub directory alternatively instead of specifying the complete path as String using (String) constructor.

9.  When there is no more data to read using fileReader.read(), deadline returns null as a mark of read completion.

10.*We cannot delete a directory using (File)dir.delete() if its not empty though we can always rename it using dir.renameTo(). To rename it we should specify correct file handle for the new Name as it being null will result in NullPointerException.

11. We can search for files and directories by using (File)dir. list() method and get the list of files and sub directories and then we can loop through the list to find the match.
  

Collections

1. TreeSet and TreeMap are sorted collections i.e they store the elements in an order.

2.*compareTo(Obj obj1) method needs to be implemented if the class implements comparable interface whereas compare(Obj obj1, Obj obj2) needs to be implemented if it implements comparator inyterface.

3. After Java 1.5, TreeSet implements NavigableSet which in turn extends SortedSet. Earlier version used to have TreeSet implementing SortedSet.

4.*A Class must override hashCode method if its overridding equal method. Not doing the same may create trouble in with hash collections and hash search.

5. A Class can override hashCode even if it's not overridding equals method.

6.*If equals method is not overridden, Two objects are treated equal only if they are same i.e obj1 == obj2.

7.*HashCode method should be implemented such that it should generate same code for an object unless its state is changed. There shouldn't be use of random functions to generate the hashcode.

8.*Returning constant value as the hasCode means all instances will be in same Bucket and hence is even worse than Linear Search.


9. Collection is an interface whereas Collections is a utility class.

10. Set doesn't allow duplicate values.

11. Set can have only one null value but not more than one as duplicates are not allowed.

12. Collections can be of objects only and not of primitives.

13. Arrays.sort only takes arrays as arguments whereas Collections.sort only takes list as argument.TreeSet is used for sorting Set and TreeMap is used for sorting Map.

14. LinkedHashMap maintains the entries in the order in which they were last accessed.

15. HashTable is thread safe whereas HashMap is not. That's why HashMap is faster than HashTable.

16. HashMap can have null keys as well as null values whereas HashTable cannot have either.

17. Sorted collections ( TreeMap , TreeSet ) cannot have heterogeneous objects. Reason being heterogenous object cannot be compared and hence elements cannot be sorted. It throws ArrayStoreException if we try to add non compatible object.

17. Map interface doesn't extend the Collection interface. List, Set and Queue extends Collection interface.

18.*If an instance of a class needs to be added to a sorted collection, either the class implements comparable interface or Comparator should be specified during construction of sorted collection.

19.*peek() method of PriorityQueue accesses the highest priority element but doesn't remove it , whereas poll() removes the highest priority element from the queue.



Var Args


1. Var Args argument should have data type followed by three dots.

2. Three dots should be consecutive and not separated by even space.

3. We can have space before and after the dots. Java ignores the space before dealing with it.

4. If there is a var args in the method, it should be only one and the last one.

5.*Internally Java treats var args as array. That is why Java doesn't allow overloaded method to have var args if there is already a method with an array of same type.

String

1.*.equals() compares the content of the object whereas == compares to see if the references are holding the same object.

2Java maintains a String Pool for reusing String objects.

3.*String objects are immutable. 

4. StringBuffer and StringBuilder object are mutable

5. StringBuffer is thread safe whereas StringBuilder is not.

6.*Literals with double quotes are String Literals. 

7. Modifying String objects is not cost effective. 

8.*Comparing non homogeneous objects using equals always returns false irrespective of their content.

9.*.equals method matches the content of String because equals method has been overridden in it.

10. StringBuffer doesn't override the equals method.

11.  String literals gets sorted when added to some collections because it implements comparable interface and hence it defines the compareTo method. StringBuffer does not implement Comparable interface.

12. String is a final class i.e it cannot be subclassed. StringBuffer and StringBuilder are not final classes.

13. String and StringBuilder class implements serializable, comparable and charSequence. StringBuffer only implements serializable.

14. StringBuffer and StringBuilder implements Builder pattern



Multithreading



1.*Thread.yield() doesn't guarantee that the Thread will keep waiting until execution of other threads.

2.*run method can be called directly but in that case it doesn't initiate new thread.

3. invoking start twice on same thread leads to IllegalStateException.

4.*Sequence in which multiple runnable threads are executed is system dependent and cannot be predicted.

5. Only methods ( static , instance ) and blocks can be synchronized. Variables cannot be synchronized.

6. InterruptedException is the checked exception for sleep method.

7. sleep is a static method and puts the current thread to sleep for specified time.

8. If the synchronized block is on a string literal, all threads will try to get lock on a common object as its picked from String pool.

9. synchronized cannot be applied to a constructor.

10. wait and notify should be there in synchronized section only.

11. Overridden method run cannot throw any checked exception.

12. There are object spcific locks and class specific locks.

13. suspend() method is used to suspend the execution of a thread for a period of time. We can then restart the thread by using resume() method.

14.*yield and sleep are static methods of Thread Class. join is the instance method of Thread Class. wait, notify and notifyAll are methods of Object class.


Generics



Following Generic Declarations are good

List<Exception> li = new ArrayList<Exception>();

List<? extends Exception> li = new ArrayList<FileNotFoundException>(); 

ArrayList<? extends Exception> li = new ArrayList<FileNotFoundException>();

ArrayList<?> li = new ArrayList<FileNotFoundException>();

ArrayList<?> li = new ArrayList<>();

ArrayList<String> li = new ArrayList<>();

List<? super FileNotFoundException> li = new ArrayList<FileNotFoundException>();

List<? super FileNotFoundException> li = new ArrayList<Exception>();

List<? extends Exception> li = new ArrayList<Exception>();


Following declarations result in compile time error

List<Exception> li = new ArrayList<FileNotFoundException>(); // argument type should be same.

ArrayList<Exception> li = new ArrayList<FileNotFoundException>(); // argument type should be same.

ArrayList<Integer> li = new <Integer>ArrayList(); // Wrong placement for the type.

List<Exception> li = new List<Exception>(); // List is not a concrete class but an interface

ArrayList<? extends String> li = new ArrayList<FileNotFoundException>(); // FileNotFoundException doesn't extend String

List<> li = new ArrayList<>(); // incorrect argument

List<? super Exception> li = new ArrayList<FileNotFoundException>(); // FileNotFoundException is not super class of Exception

List<Integer> li = new ArrayList<int>(); // Same types should be defined, Autoboxing doesn't work here.


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
comments powered by Disqus




×

Try our new Java Interview Questions Search Tool.

There are more than 1000 questions with practice tests.

It's updated daily and It's Awesome.


×

Try our new Java Practice Test tool.

There are more than 200 questions and expanding quickly. It's updated daily and It's Awesome.