Java Interview Questions

Share Embed Donate


Short Description

Download Java Interview Questions...

Description

What is a Marker Interface? - An interface with no methods. Example: Serializabl e, Remote, Cloneable What interface do you implement to do the sorting? - Comparable What is the eligibility for a object to get cloned? - It must implement the Clon eable interface What is the purpose of abstract class? - It is not an instantiable class. It pro vides the concrete implementation for some/all the methods. So that they can reu se the concrete functionality by inheriting the abstract class. What is the difference between interface and abstract class? - Abstract class de fined with methods. Interface will declare only the methods. Abstract classes ar e very much useful when there is a some functionality across various classes. In terfaces are well suited for the classes which varies in functionality but with the same method signatures. What do you mean by RMI and how it is useful? - RMI is a remote method invocatio n. Using RMI, you can work with remote object. The function calls are as though you are invoking a local variable. So it gives you a impression that you are wor king really with a object that resides within your own JVM though it is somewher e. What is the protocol used by RMI? - RMI-IIOP What is a hashCode? - hash code value for this object which is unique for every object. What is a thread? - Thread is a block of code which can execute concurrently wit h other threads in the JVM. What is the algorithm used in Thread scheduling? - Fixed priority scheduling. What is hash-collision in Hashtable and how it is handled in Java? - Two differe nt keys with the same hash value. Two different entries will be kept in a single hash bucket to avoid the collision. What are the different driver types available in JDBC? - 1. A JDBC-ODBC bridge 2 . A native-API partly Java technology-enabled driver 3. A net-protocol fully Jav a technology-enabled driver 4. A native-protocol fully Java technology-enabled d river Is JDBC-ODBC bridge multi-threaded? - No Does the JDBC-ODBC Bridge support multiple concurrent open statements per connec tion? - No What is the use of serializable? - To persist the state of an object into any pe rminant storage device. What is the use of transient? - It is an indicator to the JVM that those variabl es should not be persisted. It is the users responsibility to initialize the val ue when read back from the storage. What are the different level lockings using the synchronization keyword? - Class level lock Object level lock Method level lock Block level lock What is the use of preparedstatement? - Preparedstatements are precompiled state ments. It is mainly used to speed up the process of inserting/updating/deleting

especially when there is a bulk processing. What is callable statement? Tell me the way to get the callable statement? - Cal lablestatements are used to invoke the stored procedures. You can obtain the cal lablestatement from Connection using the following methods prepareCall(String sq l) prepareCall(String sql, int resultSetType, int resultSetConcurrency) In a statement, I am executing a batch. What is the result of the execution? - I t returns the int array. The array contains the affected row count in the corres ponding index of the SQL. Can a abstract method have the static qualifier? - No What are the different types of qualifier and what is the default qualifier? - p ublic, protected, private, package (default) What is the super class of Hashtable? - Dictionary What is a lightweight component? - Lightweight components are the one which does n t go with the native call to obtain the graphical units. They share their parent component graphical units to render them. Example, Swing components What is a heavyweight component? - For every paint call, there will be a native call to get the graphical units. Example, AWT. What is an applet? - Applet is a program which can get downloaded into a client environment and start executing there. What do you mean by a Classloader? - Classloader is the one which loads the clas ses into the JVM. What are the implicit packages that need not get imported into a class file? - j ava.lang What is the difference between lightweight and heavyweight component? - Lightwei ght components reuses its parents graphical units. Heavyweight components goes w ith the native graphical unit for every component. Lightweight components are fa ster than the heavyweight components. What are the ways in which you can instantiate a thread? - Using Thread class By implementing the Runnable interface and giving that handle to the Thread class. What are the states of a thread? - 1. New 2. Runnable 3. Not Runnable 4. Dead What is a socket? - A socket is an endpoint for communication between two machin es. How will you establish the connection between the servlet and an applet? - Using the URL, I will create the connection URL. Then by openConnection method of the URL, I will establish the connection, through which I can be able to exchange d ata. What are the threads will start, when you start the java program? - Finalizer, M ain, Reference Handler, Signal Dispatcher Quick Revision Tips For JAVA *********************** An identifier in java must begin with a letter , a dollar sign($), or an undersc ore (-); subsequent characters may be letters, dollar signs, underscores, or dig its.

There are three top-level elements that may appear in a file. None of these elem ents is required. If they are present, then they must appear in the following or der: -package declaration -import statements -class definitions A java source file (.java file) can't have more than one public class , interfac e or combination of both. "goto" is a keyword in Java. NULL is not a keyword, but null is a keyword in Java. A final class can't be subclassed. A final method can't be overridden but a non final method can be overridden to f inal method. Abstract classes can't be instantiated and should be subclassed. Primitive Wrapper classes are immutable. A static method can't refer to "this" or "super". A static method can't be overridden to non-static and vice versa. The variables in java can have the same name as method or class. All the static variables are initialized when the class is loaded. An interface can extend more than one interface, while a class can extend only o ne class. The variables in an interface are implicitly final and static. If the interface , itself, is declared as public the methods and variables are implicitly public. Variables cannot be synchronized. Instance variables of a class are automatically initialized, but local variables of a function need to be initialized explicitly. An abstract method cannot be static because the static methods can't be overridd en. The lifecycle methods of an Applet are init(), start(), stop() and destroy(). The transient keyword is applicable to variables only. The native keyword is applicable to methods only. The final keyword is applicable to methods , variables and classes. The abstract keyword is applicable to methods and classes. The static keyword is applicable to variables, methods or a block of code called static initializes. A native method can't be abstract but it can throw exception(s). A final class cannot have abstract methods. A class can't be both abstract and final. A transient variable may not be serialized.

All methods of a final class are automatically final. While casting one class to another subclass to superclass is allowed without any type casting. e.g.. A extends B , B b = new A(); is valid but not the reverse. The String class in java is immutable. Once an instance is created, the string i t contains cannot be changed. e.g. String s1 = new String("test"); s1.concat("test1"); Even after calling conc at() method on s1, the value of s1 will remain to be "test". What actually happe ns is a new instance is created. But the StringBuffer class is mutable. The + and += operators are the only cases of operator overloading in java and is applicable to Strings. Bit-wise operators - &, ^ and | operate on numeric and boolean operands. The short circuit logical operators && and || provide logical AND and OR operati ons on boolean types and unlike & and | , these are not applicable to integral t ypes. The valuable additional feature provided by these operators is the right o perand is not evaluated if the result of the operation can be determined after e valuating only the left operand. The difference between x = ++y; and x = y++; In the first case y will be incremented first and then assigned to x. In second case first y will be assigned to x then it will be incremented. Please make sure you know the difference between > and >>>(unsigned rights hift) operators. The initialization values for different data types in java is as follows byte = 0, int = 0, short = 0, char = '\u0000', long = 0L, float = 0.0f, double = 0.0d, boolean = false, object referenece (of any object) = null. Setting the object reference to null makes it a candidate for garbage collection . An overriding method may not throw a checked exception unless the overridden met hod also throws that exception or a superclass of that exception. Interface methods can't be native, static, synchronized, final, private, protect ed or abstract. Abstract classes can have constructors , and it can be called by super() when it s subclassed. A final variable is a constant and a static variable is like a global variable. The String class is a final class, it can't be subclassed. The Math class has a private constructor, it can't be instantiated. The random() method of Math class in java returns a random number , a double , b etween 0.0 and 1.0. The java.lang.Throwable class has two subclasses : Exception and Error. An Error indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.

The two kinds of exceptions in java are : Compile time (Checked ) and Run time ( Unchecked) exceptions. All subclasses of Exception except the RunTimeException a nd its subclasses are checked exceptions. Examples of Checked exception : IOException, ClassNotFoundException. Examples of Runtime exception :ArrayIndexOutOfBoundsException,NullPointerExcepti on, ClassCastException, ArithmeticException, NumberFormatException. The unchecked exceptions do not have to be caught. A try block may not be followed by a catch but in that case, finally block must follow try. While using multiple catch blocks, the type of exception caught must progress fr om the most specific exception to catch to the superclass(es) of these exception s. More than one exception can be listed in the throws clause of a method using com mas. e.g. public void myMethod() throws IOException, ArithmeticException. On dividing an integer by 0 in java will throw ArithmeticException. The various methods of Java.lang.Object are clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString and wai t. The Java.lang.System is a final class and can't be subclassed. Garbage collection in java cannot be forced. The methods used to call garbage co llection thread are System.gc() and Runtime.gc() To perform some task when an object is about to be garbage collected, you can ov erride the finalize() method of the Object class. The JVM only invokes finalize( ) method once per object. The signature of finalize() method of Object class is : protected void finalize() throws Throwable. The parent classes of input and output streams : InputStream and OutputStream cl ass are abstract classes. File class can't be used to create a new file. For that any other output stream class such as FileOutputStream or filter streams like PrintWriter should be used . Please note that java will create a file only when the file is not available. For the RandomAccessFile constructor, the mode argument must either be equal to "r" or "rw". In java, console input is accomplished by reading from System.in . System.in is an object of type InputStream; System.out and System.err are object s of type PrintStream. Both FileInputStream and FileOutputStream classes throws FileNotFoundException. In earlier versions of java, FileOutputStream() threw an IOException when an out put could not be created. System.in is an object of type InputStream; System.out and System.err are object s of type PrintStream. A method can't be overridden to be more private. e.g.. a public method can only be overridden to be public. Both primitives and object references can be cast. If inner class is declared in a method then it can access only final variables o f the particular method but can access all variables of the enclosing class.

To refer to a field or method in the outer class instance from within the inner class, use Outer.this.fieldname . Inner classes may not declare static initializers or static members unless they are compile time constants i.e. static final var = value; A nested class cannot have the same name as any of its enclosing classes. Inner class may be private, protected, final, abstract or static. An example of creation of instance of an inner class from some other class: class Outer { public class Inner{} } class Another { public void amethod() { Outer.Inner i = new Outer().new Inner(); } } Classes defined in methods can be anonymous, in which case they must be instanti ated at the same point they are defined. These classes can't have explicit const ructor and may implement interface or extend other classes. The Thread class resides in java.lang package and need not be imported. The sleep and yield methods of Thread class are static methods. The range of Thread priority in java is 1-10. The minimum priority is 1 and the maximum is 10. The default priority of any thread in java is 5. There are two ways to provide the behavior of a thread in java: extending the Th read class or implementing the Runnable interface. The only method of Runnable interface is "public void run();". New thread take on the priority of the thread that spawned it. Using the synchronized keyword in the method declaration, requires a thread obta in the lock for this object before it can execute the method. A synchronized method can be overridden to be not synchronized and vice versa. In java terminology, a monitor is any object that has some synchronized code. Both wait() and notify() methods must be called in synchronized code. The notify() mthod moves one thread, that nto the Ready state. This could be any of The notifyAll() method moves all threads, the Ready state. Every object has a lock and at any moment ne single thread.

is waiting on this object's monitor, i the waiting threads. waiting on this object's monitor into that lock is controlled by, at most, o

There are two ways to mark code as synchronized: a.) Synchronize an entire method by putting the synchronized modifier in the met hod's declaration. b.) Synchronize a subset of a method by surrounding the desired lines of code wi th curly brackets ({}).

The argument to switch can be either byte, short , char or int. The expression for an if and while statement in java must be a boolean. Breaking to a label (using break means that the loop at the label wi ll be terminated and any outer loop will keep iterating. While a continue to a l abel (using continue continues execution with the next iteration of the labeled loop. A static method can only call static variables or other static methods, without using the instance of the class. e.g. main() method can't directly access any no n static method or variable, but using the instance of the class it can. instanceof is a java keyword not instanceOf. The if() statement in java takes only boolean as an argument. Please note that i f (a=true){}, provided a is of type boolean is a valid statement and the code in side the if block will be executed. The (-0.0 == 0.0) will return true, while (5.0==-5.0) will return false. An abstract class may not have even a single abstract method but if a class has an abstract method it has to be declared as abstract. Collection is an Interface where as Collections is a helper class. The default Layout Manager for Panel and Applet is Flow. For Frame and Window it s BorderLayout. The FlowLayout always honors the a component's preferred size. BorderLayout honors the preferred width of components on the East and West, whil e the preferred height is honored for the components in the North and South. The java.awt.event package provides seven adapter classes, one for each listener interface. All these adapter classes have do-nothing methods (empty bodies) , i mplementing listener interface. A componenet subclass may handle its own events by calling enableEvents(), passi ng in an even mask. The Listener interfaces inherit directly from java.util.EventListener interface. A Container in java is a Component (Container extends Component) that can contai n other components. Graphics class is abstract, hence cannot be instantiated. The repaint() method invokes a component's update() method() which in turn invok es paint() method. The Applet class extends Panel, Frame class extends Window. A String in java is initialized to null, not empty string and an empty string is not same as a null string. The statement float f = 5.0; will give compilation error as default type for flo ating values is double and double can't be directly assigned to float without ca sting. The equals() method in String class compares the values of two Strings while == compares the memory address of the objects being compared. e.g. String s = new String("test"); String s1 = new String("test");

s.equals(s1) will return true while s==s1 will return false. The valueOf() method converts data from its internal format into a human-readabl e form. It is a static method that is overloaded within String class for all of Java's built-in types, so that each type can be converted properly into a string . The main difference between Vector and ArrayList is that Vector is synchronized while the ArrayList is not. A Set is a collection, which cannot contain any duplicate elements and has no ex plicit order to its elements. A List is a collection, which can contain duplicate elements, and the elements a re ordered. A Map does not implement the Collection interface. The following definition of main method is valid : static public void main(Strin g[] args). The main() method can be declared final. The example of array declaration along with initialization - int k[] = new int[] {1,2,3,4,9}; The size of an array is given by arrayname.length. The local variables (variables declared inside method) are not initialized by de fault. But the array elements are always initialized wherever they are defined b e it class level or method level. In an array , the first element is at index 0 and the last at length-1. Please n ote that length is a special array variable and not a method. The octal number in java is preceded by 0 while the hexadecimal by 0x (x may be in small case or upper case) e.g. octal :022 hexadecimal :0x12 A constructor cannot be native, abstract, static, synchronized or final. Constructors are not inherited so not possible to override them. A constructor body can include a return statement providing no value is returned . A constructor never return a value. If you specify a return value, the JVM (java virtual machine) will interpret it as a method. A call to this() or super() in a constructor must be placed at the first line. If a class contains no constructor declarations, then a default constructor that takes no arguments is supplied. This default constructor invokes the no-argumen t constructor of the super class via super() call (if there is any super class). Be careful for static and abstract key word in the program. Also be careful for private keyword in front of a class. The UTF characters in java are as big as they need to be while Unicode character s are all 16 bits.

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF