You are on page 1of 62

Java Interview Questions

Basics of JAVA What is java? Java is an object oriented Platform Independent computer programming language. What is java slogan? Write Once Run any ware. Why java is suitable for Internet? Security problems on Internet are eliminated through java. How many types of memory areas are allocated by JVM? Many types: 1. Class loader : Class loader is a subsystem of JVM that is used to load class files. 2. Class(Method) area : Class(method ) area stores per-class structures such as run time constant pool, field and method data, the code for methods. 3. Heap : It is the run time data area in which objects are allocated. 4. Stack : Java stack stores frames. It holds local variables and partial results, and plays a part in method invocation and returns. 5. Program counter Register : It contains the address of the JVM instruction currently being executed. 6. Native method stack : It contains all the native methods used in the application. What is the default value of the local variables? The local variables are not initialized to any default value, neither primitives nor object references. Is Java a pure object oriented language? Java uses primitive data types and hence is not a pure object oriented language. Are arrays primitive data types? In Java, Arrays are objects. What is the most important feature of Java? Java is a platform independent language. What do you mean by platform independence? Platform independence means that we can write and compile the java code in one platform (eg Windows) and can execute the class in any other supported platform eg (Linux,Solaris,etc). What is a JVM? JVM is Java Virtual Machine which is a run time environment for the compiled java class files. Are JVM's platform independent? JVM's are not platform independent. JVM's are platform specific run time implementation provided by the vendor. What is the difference between a JDK and a JVM? JDK is Java Development Kit which is for development purpose and it includes execution environment also. But JVM is purely a run time environment and hence you will not be able to compile your source files using a JVM.

How to define a constant variable in Java? The variable should be declared as static and final. So only one copy of the variable exists for all instances of the class and the value can't be changed also. static final int PI = 2.14; is an example for constant. Public static void main(String args[]) If I do not provide any arguments on the command line, then the String array of main method will be empty or null? It is empty but not null. Should a main() method be compulsorily declared in all java classes? No not required. main() method should be defined only if the source class is a java application. What is the return type of the main() method? Main() method doesn't return anything hence declared void. Why is the main() method declared static? main() method is called by the JVM even before the instantiation of the class hence it is declared as static. Why is the main method static ? So that it can be invoked without creating an instance of that class What is the arguement of main() method? main() method accepts an array of String object as arguement. Can a main() method be overloaded? Yes. You can have any number of main() methods with different method signature and implementation in the class. Can a main() method be declared final? Yes. Any inheriting class will not be able to have it's own default main() method. (Yes, such as public static final void main(String args[]){}) Does the order of public and static declaration matter in main() method? No. It doesn't matter but void should always come before main(). What happens if String args[] is not written in main( ) method ? When main( ) method is written without String args[] as: Public static void main( ) The code will compile but JVM cannot run the code beause it cannot recognize the main( ) as the method from were it should start execution of the Java program. Remember JVM always looks for main( ) method with string type array as parameter. Can you call the main( ) method of a class from another class ? Yes , we can call the main( ) method of a class from another class using Classname.main( ) . At the time of calling the main( ) method, we should pass a string type array to it. Can we execute a program without main() method? Yes, one of the way is by using static block.

----------oooooooo-----------Can a source file contain more than one class declaration? Yes a single source file can contain any number of Class declarations but only one of the class can be declared as public. Which package is imported by default? java.lang package is imported by default even without a package declaration. Can a class declared as private be accessed outside it's package? Not possible. a class be declared as protected? A class can't be declared as protected. only methods can be declared as protected. What is the access scope of a protected method? A protected method can be accessed by the classes within the same package or by the subclasses of the class in any package.

Ranges
How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters? Unicode requires 16 bits and ASCII require 7 bits Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns. What is the range of the char type? The range of the char type is 0 to 216 - 1 (i.e. 0 to 65535.) What is the range of the short type? The range of the short type is -(215) to 215 - 1. (i.e. -32,768 to 32,767) -------ooooooo-------Why isn't there operator overloading? Because C++ has proven by example that operator overloading makes code almost impossible to maintain. Which characters may be used as the second character of an identifier, but not as the first character of an identifier? The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier. How is rounding performed under integer division? The fractional part of the result is truncated. This is known as rounding toward zero. What restrictions are placed on the values of each case of a switch statement? During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value.

What is the difference between a while statement and a do while statement? A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do while statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do whilestatement will always execute the body of a loop at least once. What are the legal operands of the instanceof operator? The left operand is an object reference or null value and the right operand is a class, interface, or array type. Are true and false keywords? The values true and false are not keywords. What happens when you add a double value to a String? The result is a String object. To what value is a variable of the boolean type automatically initialized? The default value of the boolean type is false.

Casting
Can a double value be cast to a byte? Yes, a double value can be cast to a byte. Can a Byte object be cast to a double value? No, an object cannot be cast to a primitive value. What is implicit casting ? Ans). Automatic casting done by the Java compiler internally is called implicit casting . Implicit casting is done to converty a lower data type into a higher data type. What is explicit casting ? Ans). The cating done by the programmer is called explicit cating. Explicit casting is compulsory while converting from a higher data type to a lower data type. What are the rules for casting primitive types ? You can cast any non Boolean type to any other non boolean type. You cannot cast a boolean to any other type; you cannot cast any other type to a boolean What are the rules for Object reference casting ? Casting from Old types to Newtypes Compile time rules : - When both Oldtypes and Newtypes are classes, one should be subclass of the other - When both Oldtype ad Newtype are arrays, both arrays must contain reference types (not primitive), and it must be legal to cast an element of Oldtype to an element of Newtype - You can always cast between an interface and a non-final object Runtime rules : - If Newtype is a class. The class of the expression being converted must be Newtype or must inherit from Newtype - If NewType is an interface, the class of the expression being converted must implement Newtype

Statements
What are control statements ? Control statements are the statements which alter the flow of execution and provide better control to the programmer on the flow of execution. They are useful to write better and complex programs. What is the difference between a break statement and a continue statement? A break statement results in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the loop statement. Why goto statements are not available in Java ? Goto statements lead to confusion for a programmer. Especially in a large program, if several goto statements are used, the programmer would be preplexed while understanding the flow from where to where the control is jumping. Can a for statement loop indefinitely? Yes, a for statement can loop indefinitely. For example, consider the following: for(;;); What is the difference between an if statement and a switch statement? The if statement is used to select among two alternatives. It uses a boolean expression to decide which alternative should be executed. The switch statement is used to select among multiple alternatives. It uses an int expression to determine which alternative should be executed. Out of do..while and while - - which loop is efficient ? In a do..while loop, the statements are executed without testing the condition , the first time. From the second time only the condition is observed. This means that the programmer does not have control right from the beginning of its execution. In a while loop, the condition is tested first and then only the statements are executed. This means it provides better control right from the beginnig. Hence, while loop is more efficient than do.. while loop.

--------oooooooooo-------To what value is a variable of the String type automatically initialized? The default value of an String type is null. What is the difference between a field variable and a local variable? A field variable is a variable that is declared as a member of a class. A local variable is a variable that is declared as local to a method. How does Java handle integer overflows and underflows? It uses those low order bytes of the result that can fit into the size of the type allowed by the operation. Is sizeof a keyword? The sizeof operator is not a keyword.

Operators
What is the difference between the prefix and postfix forms of the ++ operator?

The prefix form performs the increment operation and returns the value of the increment operation. The postfix form returns the current value all of the expression and then performs the increment operation on that value. What is the difference between >> and >>> ? Both bitwise right shift operator( >> ) and bitwise zero fill right shift operator( >>> ) are used to shift the bits towards right. The difference is that >> will protect the sign bit whereas the >>> operator will not protect the sign bit. It always fills 0 in the sign bit. What is the difference between the Boolean & operator and the && operator? If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped. Which Java operator is right associative? The = operator is right associative. Is the ternary operator written x : y ? z or x ? y : z ? It is written x ? y : z. What is a modulo operator % ? This operator gives the value which is related to the remainder of a division e.g x=7%4 gives remainder 3 as an answer What are different types of operators in Java ? - Uniary ++, , +, -, |, ~, () - Arithmetic *, /, %,+, -Shift <<, >>, >>> - Comparison =, instanceof, = =,!=,Bitwise &, ^, |Short Circuit &&, ||Ternary ?:Assignment = How does bitwise (~) operator work ? Ans: It converts all the 1 bits in a binary value to 0s and all the 0 bits to 1s, e.g 11110000 coverts to 00001111 Can shift operators be applied to float types ? No, shift operators can be applied only to integer or long types What happens to the bits that fall off after shifting ? They are discarded What values of the bits are shifted in after the shift ? In case of signed left shift >> the new bits are set to zero. But in case of signed right shift it takes the value of most significant bit before the shift, that is if the most significant bit before shift is 0 it will introduce 0, else if it is 1, it will introduce 1 ----------ooooooooo----------Why pointeres are eliminated from java.? 1.Pointers lead to confusion for a programmer. 2. Pointers may crash a program easily, for example , when we add two pointers, the program crashers immediately.

3. Pointers break security. Using pointers, harmful programs like Virus and other hacking programs can be developed. Because of the above reasons, pointers have been eliminated from java. What is the difference between a function and a method.? A method is a function that is written in a class. We do not have functions in java; instead we have methods. This means whenever a function is written in java,it should be written inside the class only. But if we take C++, we can write the funtions inside as well as outside the class . So in C++, they are called member funcitons and not methods. Which part of JVM will allocate the memory for a java program.? Class loader subsystem of JVM will allocate the necessary memory needed by the java program. Which algorithm is used by garbage collector to remove the unused variables or objects from memory.? Garbage collector uses many algorithems but the most commonly used algorithm is mark and sweep. How can you call the garbage collector.? Garbage collector is automatically invoked when the program is being run. It can be also called by calling gc() method of Runtime class or System class in Java. What is JIT Compiler ? JIT compiler is the part of JVM which increases the speed of execution of a Java program. What is an API document ? An API document is a .html file that contains description of all the features of a softwar, a product, or a technology. API document is helpful for the user to understand how to use the software or technology. What is the difference between #include and import statement.? #include directive makes the compiler go to the C/C++ standard library and copy the code from the header files into the program. As a result, the program size increases, thus wasting memory and procssors time. import statement makes the JVM go to the Java standard library, execute the code there , and substitute the result into the program. Here, no code is copied and hence no waste of memory or processors time.so import is an efficient mechanism than #include. What is the difference between print( ) and println( ) method ? Both methods are used to display the results on the monitor . print( ) method displays the result and then retains the cursor in the same line, next to the end of the result. println( ) displays the result and then throws the cursor to the next line. What is the difference between float and double? Float can represent up to 7 digits accurately after decimal point, where as double can represent up to 15 digits accurately after decimal point. What is a Unicode system ? Unicode system is an encoding standard that provides a unique number for every character, no matter what the platform, program, orlanguage is. Unicode uses 2 bytes to represent a single character. How are positive and negative numbers represented internally ? Positive numbers are represented in binary using 1s complement notation and negative numbers are represented by using 2s complement notation.

What is the difference between return and System.exit(0) ? Return statement is used inside a method to come out of it. System.exit( 0) is used in any method to come of the program. What is the difference between System.out.exit(0) and System.exit(1) ? System.exit(0) terminates the program normally. Whereas System.exit(1) terminates the program because of some error encountered in the program. What is the difference between System.out ,System.err and System.in? System.out and System.err both represent the monitor by default and hence can be used to send data or results to the monitor. But System.out is used to display normal messages and results whereas System.err is used to display error messages and System.in represents InputStream object, which by default represents standard input device, ie, keyboard. On which memory, arrays are created in Java? Arrays are created on dynamic memory by JVM. There is no question of static memory in Java; every thing( variables, array, object etc.) is created on dynamic memory only. Is String a class or data type ? String is a class in java.lang package. But in Java, all classes are also considered as data types. So we can take String as a data type also. Can we call a class as a data type ? Yes, a class is also called user-defined data type. This is because a use can dreate a class. What is object reference ? Object reference is a unique hexadecimal number representing the memory address of the object. It is useful to access the members of the object. What is difference between == and equals() while comparing strings ? which one is reliable ? Ans). = = operator compares the references of the sting objects. It does not compare the contents of the objects. equals( ) method compares the contents. While comparing the strings, equals( ) method should be used as it yields the correct result. What is a string constant pool ? Ans). Sring constant pool is a separate block of memory where the string objects are held by JVM. If a sting object is created directly, using assignment operator as: String s1 = Hello,then it is stored in string constant pool. Explain the difference between the following two statements: 1. String s=Hello 2. String s = new String(Hello); Ans). In the first statement, assignment operator is used to assign the string literal to the String variales. In this case, JVM first of all checks whether the same object is already available in the string constant pool. If it is available , then it creates another reference to it. If the same object is not available , then it creates another object with the content Hello and stores it into the string constant pool. In the second statement, new operator is used to create the string object, in this case, JVM always creates a new object without looking in the string constant pool. Java compiler stores the .class files in the path specified in CLASSPATH environmental variable. True/False Ans : False

OOPS Constructor What is constructor? Constructor is just like a method that is used to initialize the state of an object.(It is invoked at the time of Instantiation) What is the purpose of default constructor? The default constructor provides the default values to the objects. {The java compiler creates a default constructor only if there is no constructor in the class} Does Constructor return any value? Yes, that is current instance(You can not use return type yet it returns a value). Is constructor inherited? No, constructor is not inherited. Can you make a constructor final? No, constructor can not be final. Can you use this() and super() both in a constructor? No, becoz super() or this() must be the first statement.. Does a class inherit the constructors of its superclass? A class does not inherit constructors from any of its superclasses. When does the compiler supply a default constructor for a class? The compiler supplies a default constructor for a class if no other constructors are provided. What is constructor chaining and how is it achieved in Java ? A child object constructor always first needs to construct its parent (which in turn calls its parent constructor.). In Java it is done via an implicit call to the no-args constructor as the first statement. How are this() and super() used with constructors? this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.
What is the difference between a constructor and a method? A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator. A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.

When is a constructor called, before or after creating the object ? A Constructor is called concurrently when the object creation is going on. JVM first allocates memory for the object and then executes the constructor to initialize the instance variables. By the time, object creation is completed, the constructor execution is also completed. What is the difference between default constructor and parameterized constructor?

Default constructor: Default constructor is useful to initialize all objects with same data. Default constructor does not have any parameters. When data is not passed at the time of creating an object, default constructor is called.

Parameter constructor: Parameterized constructor is useful to initialize each object with different data. Parameterized constructor will have 1 or more parameters When data is passed at the time of creating an object parameterized constructor is called.

What is the difference between a constructor and a method ? Constructors: A constructor is used to initialize the instance variables of a class. A constructors name and class name should be same. A constructor is called only once per object. Methods: A mehtod is used for any general purpose processing or calcultaions. A mehtods name and class name can be same or different. A method can be called several times on the object.

A constructor is called at the time of creating object. A method can be called after creating the object.

What is constructor overloading ? Ans). Writing two or more constructors with the same name but with difference in the parameters is called constructor overloading. Such constructors are useful to perform different tasks.

Static keyword What is static variable? Static variable is used to refer the common property of all objects(that is not unique for each object) (static variable gets memory only once in class area at the time of class loading) What is the importance of static variable? static variables are class level variables where all objects of the class refer to the same variable. If one object changes the value then the change gets reflected in all the objects. What happens to a static variable that is defined within a method of a class ? Can't do it. You'll get a compilation error. How many static initializers can you have ? As many as you want, but the static initializers and class variable initializers are executed in textual order and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope. When are static and non static variables of the class initialized ? Ans: The static variables are initialized when the class is loaded. Non static variables are initialized just before the constructor is called. What is static method? A static method belongs to the class rather than object of a class

A static method can be invoked without the need for creating an instance of a class. Static method can access static data member and can change the value of it.

When will you define a method as static? When a method needs to be accessed even before the creation of the object of the class then we should declare the method as static. Can a class be declared as static? We can not declare top level class as static, but only inner class can be declared static. What are the restriction imposed on a static method or a static block of code? A static method should not refer to instance variables without creating an instance and cannot use "this" operator to refer the instance. I want to print "Hello" even before main() is executed. How will you acheive that? Place the statement inside a static block of code. Static blocks get executed when the class gets loaded into the memory and even before the creation of an object. Hence it will be executed before the main() method. And it will be executed only once. Can we declare a static variable inside a method? Static varaibles are class level variables and they can't be declared inside a method. If declared, the class will not compile. What does it mean that a method or field is "static"? Static variables and methods are instantiated only once per class. In other words they are class variables, not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class. Static methods can be referenced with the name of the class rather than the name of a particular object of the class (though that works too). That's how library methods like System.out.println() work. out is a static field in the java.lang.System class. When are automatic variable initialized ? Ans: Automatic variable have to be initialized explicitly.

this keyword super keyword final keyword What is blank final variable? A final variable, not initialized at the time of declaration , is known as blank final variable. Can we initialize blank final variable? Yes, only in constructor if it is non-static. If it is static blank final variable ,it be initialized only in the static block. What is the purpose of declaring a variable as final? A final variable's value can't be changed. final variables should be initialized before using them. What is the impact of declaring a method as final?

A method declared as final can't be overridden. A sub-class can't have the same method signature with a different implementation. I don't want my class to be inherited by any other class. What should i do? You should declared your class as final. But you can't define your class as final, if it is an abstract class. A class declared as final can't be extended by any other class. Can you give few examples of final classes defined in Java API? java.lang.String, java.lang.Math are final classes. Can we take private methods and final methods as same ? Yes. The Java compiler assigns the value for the private methods at the time of compilation. Also private methods can not be modified at run time. This is the same cases with final methods also. Neither the private methods nor the final methods can be overriden . So, private methods can be taken as final methods. abstract class What is an Abstract Class and what is it's purpose? A Class which doesn't provide complete implementation is defined as an abstract class. Abstract classes enforce abstraction. Can a abstract class be declared final? Not possible. An abstract class without being inherited is of no use and hence will result in compile time error. What is use of a abstract variable? Variables can't be declared as abstract. only classes and methods can be declared as abstract. Can abstract modifier be applied to a variable ? No it is applied only to class and methods When does the compiler insist that the class must be abstract ? If one or more methods of the class are abstract. If class inherits one or more abstract methods from the parent abstract class and no implementation is provided for that method If class implements an interface and provides no implementation for those methods How is abstract class different from final class ? Abstract class must be subclassed and final class cannot be subclassed Can you create an object of an abstract class? Not possible. Abstract classes can't be instantiated. Can a abstract class be defined without any abstract methods? Yes it's possible. This is basically to avoid instance creation of the class. What is an abstract method? An abstract method is a method whose implementation is deferred to a subclass. Can an abstract class be final? An abstract class may not be declared as final.

What does it mean that a method or class is abstract? An abstract class cannot be instantiated. Abstract methods may only be included in abstract classes. However, an abstract class is not required to have any abstract methods, though most of them do. Each subclass of an abstract class must override the abstract methods of its superclasses or it also should be declared abstract. Interface What is interface? What is use of interface? It is similar to class which may contain methods signature only but not bodies. Methods declared in interface are abstract methods. We can implement many interfaces on a class which support the multiple inheritance. Class C implements Interface I containing method m1 and m2 declarations. Class C has provided implementation for method m2. Can i create an object of Class C? No not possible. Class C should provide implementation for all the methods in the Interface I. Since Class C didn't provide implementation for m1 method, it has to be declared as abstract. Abstract classes can't be instantiated. Can a method inside a Interface be declared as final? No not possible. Doing so will result in compilation error. public and abstract are the only applicable modifiers for method declaration in an interface. Can an Interface implement another Interface? Interfaces doesn't provide implementation hence a interface cannot implement another interface. Can an Interface extend another Interface? Yes an Interface can inherit another Interface, for that matter an Interface can extend more than one Interface. Can a Class extend more than one Class? Not possible. A Class can extend only one class but can implement any number of Interfaces. Why is an Interface be able to extend more than one Interface but a Class can't extend more than one Class? Basically Java doesn't allow multiple inheritance, so a Class is restricted to extend only one Class. But an Interface is a pure abstraction model and doesn't have inheritance hierarchy like classes(do remember that the base class of all classes is Object). So an Interface is allowed to extend more than one Interface. Can an Interface be final? Not possible. Doing so will result in compilation error. Can a class be defined inside an Interface? Yes it's possible. Can an Interface be defined inside a class? Yes it's possible. What is a Marker Interface? An Interface which doesn't have any declaration inside but still enforces a mechanism. Can we define private and protected modifiers for variables in interfaces?

No. What modifiers are allowed for methods in an Interface? Only public and abstract modifiers are allowed for methods in interfaces. When can an object reference be cast to an interface reference? An object reference be cast to an interface reference when the object implements the referenced interface.
What is the difference between an Interface and an Abstract class? An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.

Can we define private and protected modifiers for variables in interfaces? No Is it is necessary to implement all methods in an interface? Yes. All the methods have to be implemented. Which is the default access modifier for an interface method? Ans : public. Can we define a variable in an interface ? and what type it should be ? Yes we can define a variable in an interface. They are implicitly final and static. What is the difference between an abstract class and an interface ? Abstract class An abstract class is written when there are some common features shared by all the objects. Interface An interface is written when all the features are implemented differently in different objects.

When an abstract class is written, it is the duty of An interface is written when the programmer wants to the programmer to provide sub classes to it. leave the implementation to the third party vendors. An abstract class contains some abstract methods and also some concrete methods. An interface contains only abstract methods. An abstract class contain instance variables also. All the abstract methods of the abstract class should be implemented in its sub classes. Abstract class is declared by using the keyword abstract. An interface can not contain instance variables. It contains only constants. All the (abstract) methods of the interface should be implemented in its implementation classes. Interface is declared using the keyword interface.

Inner classes What is nested class? If all the methods of a inner class is static then it is a nested class.

What is inner class? If the methods of the inner class can only be accessed via the instance of the inner class, then it is called inner class. What is the diffrence between inner class and nested class? When a class is defined within a scope of another class, then it becomes inner class. If the access modifier of the inner class is static, then it becomes nested class. What is anonymous inner class ? Ans). Anonymous inner class is an inner class whose name is not mentioned, and for which only one object is created. What modifiers may be used with an inner class that is a member of an outer class? A (non-local) inner class may be declared as public, protected, private, static, final, or abstract. What is the difference between a static and a non-static inner class? A non-static inner class may have object instances that are associated with instances of the classs outer class. A static inner class does not have any object instances. What modifiers can be used with a local inner class? A local inner class may be final or abstract.

Inheritance What is Inheritance ? Ans). Deriving new classes from existing classes such that the new classes acquire all the features of existing classes is called inheritance. Why multiple inheritance is not supported in java? To reduce the complexity and simplify the language, multiple inheritance is not supported in java in case of class. What is composition? Holding the reference of the other class within some other class is known as composition. What is aggregation? It is a special type of composition. If you expose all the methods of a composite class and route the method call to the composite method through its reference , then it is called aggregation. What are some alternatives to inheritance? Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesnt force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass). Why super class members are available to sub class ? Ans). Because, the sub class object contains a copy of super class object.

What is the advantage of inheritance ? Ans). In inheritance a programmer reuses the super class code without rewriting it, in creation of sub classes So, developing the classes becomes very easy. Hence, the programmers productivity is increased. Why multiple inheritance is not available in Java ? Ans). Multiple inheritance is not available in Java for the following reasons: 1. It leads to confusion for a Java program. 2. The programmer can achieve multiple inheritance by using interfaces. 3. The programmer can achieve multiple inheritance by repeatedly using single inheritance. How many types of inheritance are there ? Ans). There are two types of inheritances single and multiple. All other types are there combinations of these two.However, Java supports only single inheritance. Polymorphism

Overloading What is method overloading ? Writing two or more methods in the same class in such a way that each mehtod has same name but with different parameters is called method overloading. Why method overloading is not possible by changing the return type in java? Becoz of ambiguity. Can we overload main() method? Yes Which object oriented Concept is achieved by using overloading and overriding? Polymorphism. Why does Java not support operator overloading? Operator overloading makes the code very difficult to read and maintain. To maintain code simplicity, Java doesn't support operator overloading. What restrictions are placed on method overloading? Two methods may not have the same name and argument list but different return types. Can a method be overloaded based on different return type but same argument type ? No, because the methods can be called without using their return type in which case there is ambiquity for the compiler. What is method signature ? Ans). Method signature represents the method name along with method parmeters. Overriding What is method overriding?

If a subclass provides a specific implementation of a method that is already provided by its parent., it is known as method overriding. It is used for runtime polymorphism and to provide the specific implementation of the method. (or) Writing two or more methods in super and sub classes such that the methods have same name and same signature is called method overriding. What restrictions are placed on method overriding? Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. The overriding method may not throw any exceptions that may not be thrown by the overridden method. Can we override static method? No, becoz they are the part of class not object. Can you override private methods ? No, private methods are not available in the sub classes, so they cannot be overriden. Why we can not override static method? It is becoz the static method is part of class and it bound with class where as instance method is bound with object and static gets memory in class area and instance gets memory in heap area. Can we override the overloaded method? Yes. What is the difference between method overriding and overloading? Overriding is a method with the same name and arguments as in a parent, whereas overloading is the same method name but different arguments What is the difference between method overloading and method overriding ? MethodOverloading: Writing two or more methods with the same name but with different signatures is called method overloading. Method overloading is done in the same class. In method overloading, method return type can be same or different. Method Overriding: Writing two or more methods with the same name and same signatures is called method overriding. Method overriding is done in super and sub classes. In method overriding method return type should also be same.

JVM decides which method is called depending on JVM decides which method is called depending on the the difference in the method signatures. data type (class) of the object used to call the method. Method overriding is done when the programmer wants Method overloading is done when the programmer to provide a different implementation(body) for the wants to extend the already available features. same feature. Method overloading is code refinement. Same method is refined to perform a different task. Method overriding is code replacement. The sub class method overrides(replaces) the super class method.

Access modifiers If a variable is declared as private, where may the variable be accessed? A private variable may only be accessed within the class in which it is declared. If a class is declared without any access modifiers, where may the class be accessed? A class that is declared without any access modifiers is said to have package access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package. If a method is declared as protected, where may the method be accessed? A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.

What is the difference between a public and a non-public class? A public class may be accessed outside of its package. A non-public class may not be accessed outside of its package What modifiers may be used with a top-level class? A top-level class may be public, abstract, or final.
State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers. public : Public class is visible in other packages, field is visible everywhere (class must be public too) private : Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature. protected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature.This access is provided even to subclasses that reside in a different package from the class that owns the protected feature. default :What you get by default ie, without any access modifier (ie, public private or protected).It means that it is visible to all within a particular package.

Access Modifiers Same Class Same Package Subclass Other packages


public protected No access modifier private Y Y Y Y Y Y Y N Y Y N N Y N N N

First row {public Y Y Y Y} should be interpreted as:


Y A member declared with public access modifier CAN be accessed by the members of the same class. Y A member declared with public access modifier CAN be accessed by the members of the same package.

Y A member declared with public access modifier CAN be accessed by the members of the subclass. Y A member declared as public CAN be accessed from Other packages.

Second row {protected Y Y Y N} should be interpreted as:


Y A member declared with protected access modifier CAN be accessed by the members of the same class. Y A member declared with protected access modifier CAN be accessed by the members of the same package. Y A member declared with protected access modifier CAN be accessed by the members of the subclass. N A member declared with protected access modifier CANNOT be accessed by the members of the Other package.

Class level access modifiers (java classes only) Only two access modifiers is allowed, public and no modifier If a class is public, then it CAN be accessed from ANYWHERE. If a class has no modifer, then it CAN ONLY be accessed from same package. Packages What is a Java package and how is it used? A Java package is a naming context for classes and interfaces. A package is used to create a separate name space for groups of classes and interfaces. Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces. What restrictions are placed on the location of a package statement within a source code file? A package statement must appear as the first line in a source code file (excluding blank lines and comments). What are packages ? what is use of packages ? The package statement defines a name space in which classes are stored If you omit the package, the classes are put into the default package. Signature... package pkg; Use: * It specifies to which package the classes defined in a file belongs to. * Package is both naming and a visibility control mechanism. What is difference between importing "java.applet.Applet" and "java.applet.*;" ? "java.applet.Applet" will import only the class Applet from the package java.applet Where as "java.applet.*" will import all the classes from java.applet package. What do you understand by package access specifier? public: Anything declared as public can be accessed from anywhere private: Anything declared in the private cant be seen outside of its class. default: It is visible to subclasses as well as to other classes in the same package. By default, all program import the java.lang package. True/False Ans : True User-defined package can also be imported just like the standard packages. True/False Ans : True

AWT AND SWING


The event delegation model, introduced in release 1.1 of the JDK, is fully compatible with the event model. a) True b) False Ans : b. A component subclass that has executed enableEvents( ) to enable processing of a certain kind of event cannot also use an adapter as a listener for the same kind of event. a) True b) False Ans : b. What is the highest-level event class of the event-delegation model? The java.util.EventObject class is the highest-level class in the event-delegation hierarchy. What interface is extended by AWT event listeners? All AWT event listeners extend the java.util.EventListener interface. What class is the top of the AWT event hierarchy? The java.awt.AWTEvent class is the highest-level class in the AWT event class hierarchy. What event results from the clicking of a button? The ActionEvent event is generated as the result of the clicking of a button. What is the relationship between an event-listener interface and an event-adapter class? An event-listener interface defines the methods that must be implemented by an event handler for a particular kind of event. An event adapter provides a default implementation of an event-listener interface. In which package are most of the AWT events that support the event-delegation model defined? Most of the AWTrelated events of the event-delegation model are defined in the java.awt.event package. The AWTEvent class is defined in the java.awt package. What is the advantage of the event-delegation model over the earlier event-inheritance model? The event-delegation has two advantages over the event-inheritance model. They are : It enables event handling by objects other than the ones that generate the events. This allows a clean separation between a components design and its use. It performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly process unhandled events, as is the case of the event-inheritance model. What is the purpose of the enableEvents( ) method? The enableEvents( ) method is used to enable an event for a particular object. Which of the following are true? a) The event-inheritance model has replaced the event-delegation model. b) The event-inheritance model is more efficient than the event-delegation model. c) The event-delegation model uses event listeners to define the methods of event-handling classes. d) The event-delegation model uses the handleEvent( ) method to support event handling. Ans : c. Which of the following is the highest class in the event-delegation model?

a) java.util.EventListener b) java.util.EventObject c) java.awt.AWTEvent d) java.awt.event.AWTEvent Ans : b. What is the difference between a window and a frame ? Ans). A window is a frame without any borders and title, whereas a frame contains borders and title.
Difference between Swing and Awt? AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works faster than AWT.

What is event delegation model ? Ans). Event delegation model represents that when an event is generated by the user on a component, it is delegated to a listener interface and the listener calls a mehtod in response to the event. Finally , the event is handled by the method. Which model is used to provide actions to AWT components ? Ans). Event delegation model. What is an adapter class ? Ans). An adapter class is an implementation class of a listener which contains all methods implemented with empty body. For example, WindowAdapter is an adapter class of WindowListener interface. Adapter classes reduce overhead on programming while working with listener interfaces. What is the default layout in a frame ? Ans). BorderLayout. What is the default layout in an applet ? Ans). FlowLayout. What are Java Foundation classes ? Ans). Java Foundation classes (JFC) represented a class library developed in pure Java which is an extension to AWT. Discuss about the MVC architecture in JFC/ swing ? Ans). Model- View Controller is a model used in swing components. Model represents the data of the component. View represents its appearance and controller is a mediater between the model and the view.MVC represents the separation of model of an object from its view and how it is controlled. What are the various window panes available in swing ? Ans). There are 4 window panes: Glass pane, Root pane, Layered pane, and Content pane. Where are the borders available in swing ? Ans). All borders are available in BorderFactory class in javax.swing.border package.

APPLETS What is an Applet? Should applets have constructors?

Applet is a dynamic and interactive program that runs inside a Web page displayed by a Java capable browser. We dont have the concept of Constructors in Applets. What is an applet ? An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java application because it has the entire Java API at its disposal. How do we read number information from my applets parameters, given that Applets getParameter() method returns a string? Use the parseInt() method in the Integer Class, the Float(String) constructor in the Class Float, or the Double(String) constructor in the class Double. What is applet life cycle ? An applet is born with init( ) method and starts functioning with start( ) method. To stop the applet, the stop( ) method is called and to terminate the applet completely from memory, the destroy( ) method is called. Once the applet is terminated, we should reload the HTML page again to get the applet start once again from init( ) method. This cyclic way of executing the methods is called applet life cycle. Where are the applets executed ? Ans). Applets are executed by a program called applet engine which is similar to virtual machine that exists inside the web browser at client side. How can I arrange for different applets on a web page to communicate with each other? Name your applets inside the Applet tag and invoke AppletContexts getApplet() method in your applet code to obtain references to the other applets on the page. How do I select a URL from my Applet and send the browser to that page? Ask the applet for its applet context and invoke showDocument() on that context object. Eg. URL targetURL; String URLString AppletContext context = getAppletContext(); Try { targetUR L = new URL(URLString); } catch (Malformed URLException e) { // Code for recover from the exception } context. showDocument (targetURL); Can applets on different pages communicate with each other? No. Not Directly. The applets will exchange the information at one meeting place either on the local file system or at remote system. How do Applets differ from Applications? Appln: Stand Alone Applet: Needs no explicit installation on local m/c. Appln: Execution starts with main() method. Applet: Execution starts with init() method. Appln: May or may not be a GUI Applet: Must run within a GUI (Using AWT)

How do I determine the width and height of my application? Use the getSize() method, which the Applet class inherits from the Component class in the Java.awt package. The getSize() method returns the size of the applet as a Dimension object, from which you extract separate width, height fields. Eg. Dimension dim = getSize (); int appletwidth = dim.width (); What is AppletStub Interface? The applet stub interface provides the means by which an applet and the browser communicate. Your code will not typically implement this interface. Miscellaneous topics What is the diff b/w object oriented programming language and object based programming language? Object based programming language follow all the features of OOPs except Inheritance. Ex: JavaScript, VBScript and etc. What will be the initial value of an object reference which is defined as an instance variable? The Object references are all initialized to null in java Can you have virtual functions in java? Yes, all functions in java are virtual by default. What is covariant return type? Now, since java5, it possible to override any method by changing the return type if the return type of the subclass overriding method is subclass type. It known as covariant return type. What is the % operator? It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand by the second operand. Which class is extended by all other classes? The Object class is extended by all other classes. Which non-Unicode letter characters may be used as the first character of an identifier? The non-Unicode letter characters $ and _ may appear as the first character of an identifier What is the return type of a program's main() method? void. Can an anonymous class be declared as implementing an interface and extending a class? An anonymous class may implement an interface or extend a superclass, but may not be declared to do both. Is null a keyword? The null value is not a keyword. What is mutable object and immutable object?

If a object value is changeable then we can call it as Mutable object. (Ex., StringBuffer, ) If you are not allowed to change the value of an object, it is immutable object. (Ex., String, Integer, Float, ) What is the basic difference between string and stringbuffer object? String is an immutable object. StringBuffer is a mutable object. What is the purpose of Void class? The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the primitive Java type void. What is reflection? Reflection allows programmatic access to information about the fields, methods and constructors of loaded classes, and the use reflected fields, methods, and constructors to operate on their underlying counterparts on objects, within security restrictions. What is a DatabaseMetaData? Comprehensive information about the database as a whole. What is Locale? A Locale object represents a specific geographical, political, or cultural region How will you load a specific locale? Using ResourceBundle.getBundle(); Is JVM a compiler or an interpreter? Interpreter When you think about optimization, what is the best way to findout the time/memory consuming process? Using profiler Are there any other classes whose objects are immutalbe ? Yes, classes like Character, Byte, Integer, Float, Double, Long..called wrapper classes are created as immutable.Classes like Class, BigInteger, Big Decimal are also immutable. What are the methods in Object? clone, equals, wait, finalize, getClass, hashCode, notify, notifyAll, toString Can you instantiate the Math class? You cant instantiate the math class. All the methods in this class are static. And the constructor is not public. What is singleton? It is one of the design pattern. This falls in the creational pattern of the design pattern. There will be only one instance for that entire JVM. You can achieve this by having the private constructor in the class. For eg., public class Singleton { private static final Singleton s = new Singleton(); private Singleton() { } public static Singleton getInstance() { return s; } // all non static methods } What is DriverManager? The basic service to manage set of JDBC drivers. What is Class.forName() does and how it is useful? It loads the class into the ClassLoader. It returns the Class. Using that you can get the instance ( classinstance.newInstance() ).

What is the purpose of the System class? The purpose of the System class is to provide access to system resources. Name the eight primitive Java types. The eight primitive types are byte, char, short, int, long, float, double, and boolean. Which class should you use to obtain design information about an object? The Class class is used to obtain information about an objects design.

Garbage Collection
What is garbage collection ? The runtime system keeps track of the memory that is allocated and is able to determine whether that memory is still useable. This work is usually done in background by a low-priority thread that is referred to as garbage collector. When the gc finds memory that is no longer accessible from any live thread it takes steps to release it back to the heap for reuse
What is the purpose of garbage collection in Java, and when is it used? The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.

What is garbage collection? What is the process that is responsible for doing that in java? Reclaiming the unused memory by the invalid objects. Garbage collector is responsible for this process How will you invoke any external process in Java? Runtime.getRuntime().exec(.) What is the finalize method do? Before the invalid objects get garbage collected, the JVM give the user a chance to clean up some resources before it got garbage collected. How many times may an objects finalize() method be invoked by the garbage collector? An objects finalize() method may only be invoked once by the garbage collector. Can an object be garbage collected while it is still reachable? A reachable object cannot be garbage collected. Only unreachable objects may be garbage collected. Does System.gc and Runtime.gc() guarantee garbage collection ? No Can you change the reference of the final object ? Ans: No the reference cannot be change, but the data in that object can be changed -----------ooooooooooo------------

Where can static modifiers be used ? They can be applied to variables, methods and even a block of code, static methods and variables are not associated with any instance of class When are the static variables loaded into the memory ?

During the class load time When are the non static variables loaded into the memory ? They are loaded just before the constructor is called Where is native modifier used ? It can refer only to methods and it indicates that the body of the method is to be found else where and it is usually written in non java language What are transient variables ? A transient variable is not stored as part of objects persistent state and they cannot be final or static What is synchronized modifier used for ? It is used to control access of critical code in multithreaded programs What are volatile variables ? It indicates that these variables can be modified asynchronously What are the rules for primitive arithmetic promotion conversion ? For Unary operators : If operant is byte, short or a char it is converted to an int. If it is any other type it is not converted For binary operands : If one of the operands is double, the other operand is converted to double Else If one of the operands is float, the other operand is converted to float Else If one of the operands is long, the other operand is converted to long Else both the operands are converted to int What are the rules for object reference assignment and method call conversion ? An interface type can only be converted to an interface type or to object. If the new type is an interface, it must be a superinterface of the old type. A class type can be converted to a class type or to an interface type. If converting to a class type the new type should be superclass of the old type. If converting to an interface type new type the old class must implement the interface. An array maybe converted to class object, to the interface cloneable, or to an array. Only an array of object references types may be converted to an array, and the old element type must be convertible to the new element When do you use continue and when do you use break statements ? When continue statement is applied it prematurely completes the iteration of a loop. When break statement is applied it causes the entire loop to be abandoned. Which is used to get the value of the instance variables? Dot notation. The new operator creates a single instance named class and returns a reference to that object. a)True b)False Ans: a. A class is a template for multiple objects with similar features. a)True b)False Ans: a. What is mean by garbage collection?

When an object is no longer referred to by any variable, Java automatically reclaims memory used by that object. This is known as garbage collection. What are methods and how are they defined? Methods are functions that operate on instances of classes in which they are defined. Objects can communicate with each other using methods and can call methods in other classes. Method definition has four parts.They are name of the method, type of object or primitive type the method returns, a list of parameters and the body of the method. A method's signature is a combination of the first three parts mentioned above. What is calling method? Calling methods are similar to calling or referring to an instance variable. These methods are accessed using dot notation. Ex: obj.methodname(param1,param2) Which method is used to determine the class of an object? getClass( ) method can be used to find out what class the belongs to. This class is defined in the object class and is available to all objects. All the classes in java.lang package are automatically imported when a program is compiled.a)True b)False Ans: a. How can class be imported to a program? To import a class, the import keyword should be used as shown.;import classname; How can class be imported from a package to a program? import java . packagename . classname (or) import java.package name.*; What is a constructor? A constructor is a special kind of method that determines how an object is initialized when created. Which keyword is used to create an instance of a class? Ans: new. Which method is used to garbage collect an object? Ans: finalize (). Constructors can be overloaded like regular methods. a)True b)False Ans: a. What is casting? Casting is bused to convert the value of one type to another. Casting between primitive types allows conversion of one primitive type to another.a)True b)False Ans: a. Casting occurs commonly between numeric types. a)True b)False Ans: a. Boolean values can be cast into any other primitive type. a)True b)False

Ans: b. Casting does not affect the original object or value. a)True b)False Ans: a. Which cast must be used to convert a larger value into a smaller one? Ans: Explicit cast. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters? Unicode requires 16 bits, ASCII require 7 bits (although the ASCII character set uses only 7 bits, it is usually represented as 8 bits), UTF-8 represents characters using 8, 16, and 18 bit patterns, UTF-16 uses 16bit and larger bit What are wrapper classes? Wrapper classes are classes that allow primitive types to be accessed as objects. For example, Integer, Double. These classes contain many methods which can be used to manipulate basic data types Does garbage collection guarantee that a program will not run out of memory? No, it doesnt. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection. The main purpose of Garbage Collector is recover the memory from the objects which are no longer required when more memory is needed. What is a native method? A native method is a method that is implemented in a language other than Java. For example, one method may be written in C and can be called in Java How can you write a loop indefinitely? for(;;) //for loop while(true); //always true Can an anonymous class be declared as implementing an interface and extending a class? An anonymous class may implement an interface or extend a superclass, but may not be declared to do both What is the purpose of finalization? The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected. For example, closing a opened file, closing a opened database Connection. What is a class? A class is a blueprint, or prototype, that defines the variables and the methods common to all objects of a certain kind. What is a object? An object is a software bundle of variables and related methods. An instance of a class depicting the state and behavior at that particular time in real world. What is a method? Method of a functionality which can be called to perform specific tasks. Is multiple inheritance allowed in Java? No, multiple inheritance is not allowed in Java. What is interpreter and compiler?

Java interpreter converts the high level language code into a intermediate form in Java called as bytecode, and then executes it, where as a compiler converts the high level language code to machine language making it very hardware specific What is JVM? The Java interpreter along with the runtime environment required to run the Java application in called as Java virtual machine(JVM) .The Java Virtual Machine is a software that can be ported onto various hardware-based platforms. What are the different types of modifiers? There are access modifiers and there are other identifiers. Access modifiers are public, protected and private. Other is final and static. What are the access modifiers in Java? There are 3 access modifiers. Public, protected and private, and the default one if no identifier is specified is called friendly, but programmer cannot specify the friendly identifier explicitly. What is the use of bin and lib in JDK? Bin contains all tools such as javac, applet viewer, awt tool etc., whereas Lib contains all packages and variables. What is the difference between StringBuffer and StringBuilder classes? StringBuffer class is synchronized and StringBuilder is not. When the programmer wants to use several threads, he should use StringBuffer as it gives reliable results . If only one thread is used. StringBuilder is preferred, as it improves execution time. What is object oriented approach ? Object oriented programming approach is a programming methodology to design computer programs using classes and objects. What is the difference between a class and an object ? A class is a model for creating objects and does not exist physically. An object is any thing that exists physically.Both the classes and objects contain variables and methods. What is encapsulation ? Encapsulation is a mechanism where the data(varialbes) and the code(methods) that act on the data will bind together. For ex,if we take a class, we write the variables and methods inside the class. Thus, class is binding them together. So class is an example for encapsultion. What is abstraction ? Ans). Hiding the unnecessary data from the user and expose only needed data is of interest to the user. A good example for abstraction is a car. Any car will have some parts like engine, radiator, mechanical and electrical equipment etc. The user of the ca r (driver) should know how to drive the car and does not require any knowledge of these parts. For example driver is never bothered about how the engine is designed and the internal parts of the engine. This is why, the car manufacturers hide these parts from the driver in a separate panel, generally at the front. Example in java: Class Bank { Private int accno; Private String name; Private float balance; Private float profit; Private float loan;

Public void desplay_to _clerk() { System.out.println(Accno= +accno); System.out.println(Name= +name); System.out.println(Balance=+balance); } } What is Inheritance ? Ans). It creates new classes from existing classes, so that the new classes will acquire all the features of the existing classes is called inheritance. (or) Acquiring the all properties from base class to child class . What is Polymorphism ? Ans). The word Polymorphism came from two Greek words poly meaning many and morphs meaning forms . Thus, polymorphism represents the ability to assume several different forms. In programming, we can use a single variable to refer to objects of different types and thus, using that variable we can call the methods of the different objects. Thus a method call can perform different tasks depending on the type of the object. What is the difference between object oriented programming launguages and object based programming languages ? Ans). Object oriented programming languages follow all the features of Object Oriented Programming System(OOPS). Smalltalk, Simula-67,C++, Java are examples for OOPS languages. Object based programming languages follow all the features of OOPS except Inheritance. For example, JavaScript and VBScript will come under object based programming languages. What is hash code ? Ans). Hash code is unique identification number alloted to the objects by the JVM. This hash code number is also called reference number which is created based on the location of the object in memory, and is unique for all objects, except for String objects. How can you find the hash code of an object ? Ans). The hashCode( ) method of Object class in java.lang.package is useful to find the hash code of an object. Can you declare a class as private ? Ans). No, if we declare a class as private , then it is not available to java compiler and hence a compile time error occurs, But inner classes can be declared as private. In how many ways can you create an object in Java ? Ans). There are four ways of creating objects in Java: 1. Using new operator Employee obj = new Employee( ); Here , we are creating Employee class object obj using new operator. 2. Using factory methods: Number Format obj = NumberFormat. getNumberInstance( ); Here, we are creating NumberFormat object using the factory method getNumberInstance( ) 3. Using newInstance( ) method. Here we should follow tow steps, as: (a) First, store the class name Employee as a string into an object. For this purpose, factory metod forName( ) of the class Class will be useful: Class c = Class.forName(Employee); We should note that there is a class with the name Class in java.lang package. (b) Next, create another object to the class whose name is in the object c. For this purpose , we need newInstance( ) method of the class Class as:

Employee obj = ( Employee)c.newInstance( ); 4. By cloning an already available object, we can create another object. Creating exact copy of an existing object is called cloning. Employee obj1 = new Employee ( ); Employee obj2 = (Employee)obj1.clone( ); Earlier, we created obj2 by cloning the Employee object obj1.clone( ) method of Object class is used to clone object.We should note that there is a class by the name Object in java.lang package. What is object graph ? Ans). Object graph is a graph showing relationship between different objects in memory. What is anonymous inner class ? Ans). It is an inner class whose name is not written in the outer class and for which only one object is created. What is coercion ? Ans). Coercion is the automatic conversion between different data types done by the compiler. What is conversion ? Ans). Conversion is an explicit change in the data type specified by the operator. What is the difference between dynamic polymorphism and static polymorphism ? Ans). Dynamic polymorphism is the polymorphism existed at runtime. Here, Java compiler does not understand which method is called at compilation time. Only JVM decides which method is called at runtime. Method overloading and method overriding using instance methods are the examples for dynamic polymorphism. Static polymorphism is the polymorphism exhibited at compile time. Here, Java compiler knows which method is called. Method overloading and method overriding using static methods; method overriding using private or final methods are examples for static polymorphism. What is difference between primitive data types and advanced data types ? Ans). Primitive data types represent single values. Advanced data types represent a group of values. Also methods are not available to handle the primitive data types. In case of advanced data types, methods are available to perform various operations. What is generalization and specialization ? Ans). Generalization ia a phenomenon wher a sub class is prompted to a super class, and hence becomes more general. Generalization needs widening or up-casting. Specialization is phenomenon where a super class is narrowed down to a sub class. Specialization needs narrowing or down-casting. What is widening and narrowing ? Ans). Converting lower data type into a higher data type is called widening and converting a higher data type into a lower type is called narrowing. Widening is safe and hence even if the programmer does not use cast operator, the Java compiler does not flag any error. Narrowing is unsafe and hence the programmer should explicitly use cast operator in narrowing. Which method is used in cloning ? Ans). clone( ) method of Object class is used in cloning. What do you call the interface without any members ? Ans). An interface without any members is called marking interface or tagging interface. It marks the class objects for a special purpose. For example, Clonable(java.lang) and Serializable(java.io) are two marking interfaces. Clonable interface indicates that a particular class objects are cloneable while

Serializable interface indicates that a particular class objects are serializable. What is abstract method ? Ans). An abstract method is a method without method body. An abstract method is written when the same method has to perform difference tasks depending on the object calling it. What is abstract class ? Ans). An abstract class is a class that contains 0 or more abstract methods. How can you force your programmers to implement only the features of your class ? Ans). By writing an abstract class or an interface. Can you declare a class as abstract and final also ? Ans). No, abstract class needs sub classes. final key word represents sub classes which can not be created. So, both are quite contradictory and cannot be used for the same class. What is an interface ? Ans). An interface is a specification of method prototypes, All the methods of the interface are public and abstract. Why the methods of interface are public and abstract by default ? Ans). Interface methods are public since they should be available to third party vendors to provide implementation. They are abstract because their implementation is left for third party vendors. Can you implement one interface from another ? Ans). No, we cant implementing an interface means writing body for the methods. This can not be done again in an interface, since none of the methods of the interface can have body. Can you write a class within an interfae ? Ans). Yes, it is possible to write a class within an interface. Explain about interfaces ? Ans). * An interface is a specification of method prototypes, before we proceed furthur, written in the interface without mehtod bodies. *An interface will have 0 or more abstract methods which are all public and abstract by default. * An interface can have variables which are public static and final by default. This means all the variables of the interface are constants. How can you call the garbage collector ? Ans). We can call garbage collector of JVM to delete any unused variables and unreferenced objects from memory using gc( ) method. This gc( ) method appears in both Runtime and System classes of java.lang package. For example, we can call it as: System.gc( ); Runtime.getRuntime( ).gc( ); What is the difference between the following two statements. 1. import pack.Addition; 2. import pack.*; Ans) . In statement 1, only the Addition class of the package pack is imported into the program and in statement 2, all the classes and interfaces of the package pack are available to the program. If a programmer wants to import only one class of a package say BufferedReader of java.io package, we can write import java.io.BufferedReader;

What is the differentiate between .ear, .jar and .war files.? Ans). These files are simply zipped file using java jar tool. These files are created for different purposes. Here is the description of these files: .jar files: These files are with the .jar extenstion. The .jar files contains the libraries, resources and accessories files like property files. .war files: These files are with the .war extension. The war file contains the web application that can be deployed on the any servlet/jsp container. The .war file contains jsp, html, javascript and other files for necessary for the development of web applications. .ear files: The .ear file contains the EJB modules of the application. What is CLASSPATH ? Ans) . The CLASSPATH is an environment variable that tells the Java compiler where to look for class files to import. CLASSPATH is generally set to a directory or a JAR(Java Archive)file. What is a JAR file ? Ans) A Java Archive file (JAR) is a file that contains compressed version of several .class files, audio files, image files or directories. JAR file is useful to bundle up several files related to a project and use them easily. What is the scope of default acess specifier ? Ans). Default members are available within the same package, but not outside of the package. So their scope is package scope. What happens if main( ) method is written without String args[ ] ? Ans). The code compiles but JVM cannot run it, as it cannot see the main( ) method with String args[ ]. Why do we need wrapper classes ? 1. They convert primitive data types into objects and this is needed on Internet to mommunicate between two applications. 2. The classes in java.util package handle only objects and hence wrapper classes help in this case also. Which of the wrapper classes contains only one constructor ? (or) Which of the wrapper classes does not contain a constructor with String as parameter ? Ans). Character. What is unboxing ? Ans). Converting an object into its corresponding primitive datatype is called unboxing. What happens if a string like Hello is passed to parseInt ( ) method ? Ans). Ideally a string with an integer value should be passed to parseInt ( ) method. So, on parsing Hello, an exception called NumberFormatException occurs since the parseInt( ) method cannot convert the given string Hello into an integer value. What is HotJava? Ans).Hot Java is the first applet-enabled browser developed in Java to support running of applets. What is a generic type ? Ans). A generic type represents a class or an interface that is type-safe. It can act on any data type. What is erasure ? Ans). Creating non-generic version of a generic type by the Java compiler is called erasure. What is auto boxing ? Ans). Auto boxing refers to creating objects and storing primitive data types automatically by the

compiler. What is JDBC ? Ans). JDBC (Java Database Connectivity) is an API that is useful to write Java programs to connect to any database, retreive the data from the database and utilize the data in a Java program. What is a database driver ? Ans). A database driver is a set of classes and interfaces, written according to JDBC API to communicate with a database. How can you register a driver ? Ans). To register a database driver, we can follow one of the 4 options: - By creating an object to driver class - By sending driver class object to DriverManager.registerDriver( ) method - By sending the driver class name to Class.forName( ) method - By using System class getProperty( ) method. which containers use a border Layout as their default layout? The window, Frame and Dialog classes use a border layout as their default layout. Why do threads block on I/O? Threads block on i/o (that is enters the waiting state) so that other threads may execute while the i/o Operation is performed. How are Observer and Observable used? Objects that subclass the Observable class maintain a list of observers.When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects. What is synchronization and why is it important? With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors. Can a lock be acquired on a class? Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object. What's new with the stop(), suspend() and resume() methods in JDK 1.2? The stop(), suspend() and resume() methods have been deprecated in JDK 1.2. What is the preferred size of a component? The preferred size of a component is the minimum component size that will allow the component to display normally. What method is used to specify a container's layout? The setLayout() method is used to specify a container's layout. Which containers use a FlowLayout as their default layout? The Panel and Applet classes use the FlowLayout as their default layout. What modifiers may be used with an inner class that is a member of an outer class?

A (non-local) inner class may be declared as public, protected, private, static, final, or abstract. What is an Iterator interface? The Iterator interface is used to step through the elements of a Collection. What is the difference between the >> and >>> operators? The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out. Which method of the Component class is used to set the position and size of a component? setBounds() What is the difference between yielding and sleeping? When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state. Which java.util classes and interfaces support event handling? The EventObject class and the EventListener interface support event processing. Does garbage collection guarantee that a program will not run out of memory? Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection What restrictions are placed on the location of a package statement within a source code file? A package statement must appear as the first line in a source code file (excluding blank lines and comments). Can an object's finalize() method be invoked while it is reachable? An object's finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object's finalize() method may be invoked by other objects. What is the immediate superclass of the Applet class? Panel What is the difference between preemptive scheduling and time slicing? Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors. Name three Component subclasses that support painting. The Canvas, Frame, Panel, and Applet classes support painting. What value does readLine() return when it has reached the end of a file? The readLine() method returns null when it has reached the end of a file. What is the immediate superclass of the Dialog class? Window What is clipping? Clipping is the process of confining paint operations to a limited area or shape. Can a for statement loop indefinitely? Yes, a for statement can loop indefinitely. For example, consider the following: for(;;) ;

What are order of precedence and associativity, and how are they used? Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left When a thread blocks on I/O, what state does it enter? A thread enters the waiting state when it blocks on I/O. To what value is a variable of the String type automatically initialized? The default value of an String type is null. What is the catch or declare rule for method declarations? If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause. What is the difference between a MenuItem and a CheckboxMenuItem? The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be checked or unchecked. What is a task's priority and how is it used in scheduling? A task's priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks. What class is the top of the AWT event hierarchy? The java.awt.AWTEvent class is the highest-level class in the AWT event-class hierarchy. When a thread is created and started, what is its initial state? A thread is in the ready state after it has been created and started. Can an anonymous class be declared as implementing an interface and extending a class? An anonymous class may implement an interface or extend a superclass, but may not be declared to do both. What is the range of the short type? The range of the short type is -(2^15) to 2^15 - 1. What is the range of the char type? The range of the char type is 0 to 2^16 - 1. In which package are most of the AWT events that support the event-delegation model defined? Most of the AWT-related events of the event-delegation model are defined in the java.awt.event package. The AWTEvent class is defined in the java.awt package. What is the immediate superclass of Menu? MenuItem Which class is the immediate superclass of the MenuComponent class. Object What invokes a thread's run() method? After a thread is started, via its start() method or that of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed. What is the difference between the Boolean & operator and the && operator?

If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped. Name three subclasses of the Component class. Box.Filler, Button, Canvas, Checkbox, Choice, Container, Label, List, Scrollbar, or TextComponent What is the GregorianCalendar class? The GregorianCalendar provides support for traditional Western calendars. Which Container method is used to cause a container to be laid out and redisplayed? validate() What is the purpose of the Runtime class? The purpose of the Runtime class is to provide access to the Java runtime system. How many times may an object's finalize() method be invoked by the garbage collector? An object's finalize() method may only be invoked once by the garbage collector. What is the purpose of the finally clause of a try-catchfinally statement? The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught. What is the argument type of a program's main() method? A program's main() method takes an argument of the String[] type. Which Java operator is right associative? The = operator is right associative. What is the Locale class? The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region. Can a double value be cast to a byte? Yes, a double value can be cast to a byte. What is the difference between a break statement and a continue statement? A break statement results in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the loop statement. What must a class do to implement an interface? It must provide all of the methods in the interface and identify the interface in its implements clause. What method is invoked to cause an object to begin executing as a separate thread? The start() method of the Thread class is invoked to cause an object to begin executing as a separate thread. Name two subclasses of the TextComponent class. TextField and TextArea What is the advantage of the event-delegation model over the earlier event-inheritance model? The event-delegation model has two advantages over the eventinheritance model. First, it enables event handling to be handled by objects other than the ones that generate the events (or their containers). This

allows a clean separation between a component's design and its use. The other advantage of the eventdelegation model is that it performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly process unhandled events, as is the case of the event-inheritance model. Which containers may have a MenuBar? Frame How are commas used in the intialization and iteration parts of a for statement? Commas are used to separate multiple statements within the initialization and iteration parts of a for statement. What is the purpose of the wait(), notify(), and notifyAll() methods? The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to wait for a shared resource. When a thread executes an object's wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the object's notify() or notifyAll() methods. How are Java source code files named? A Java source code file takes the name of a public class or interface that is defined within the file. A source code file may contain at most one public class or interface. If a public class or interface is defined within a source code file, then the source code file must take the name of the public class or interface. If no public class or interface is defined within a source code file, then the file must take on a name that is different than its classes and interfaces. Source code files use the .java extension.

Exception Handling

What is an exception? An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.

What is error? An Error indicates that a non-recoverable condition has occurred that should not be caught. Error, a subclass of Throwable, is intended for drastic problems, such as OutOfMemoryError, which would be reported by the JVM itself. Which is superclass of Exception? "Throwable", the parent class of all exception related classes. What are the advantages of using exception handling? Exception handling provides the following advantages over "traditional" error management techniques: Separating Error Handling Code from "Regular" Code. Propagating Errors Up the Call Stack. Grouping Error Types and Error Differentiation. What are the types of Exceptions in Java There are two types of exceptions in Java, unchecked exceptions and checked exceptions. Checked exceptions: A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses. Each method must either handle all checked exceptions by supplying a catch clause or list each unhandled checked exception as a thrown exception. Unchecked exceptions: All Exceptions that extend the RuntimeException class are unchecked exceptions. Class Error and its subclasses also are unchecked. Why Errors are Not Checked? A unchecked exception classes which are the error classes (Error and its subclasses) are exempted from compile-time checking because they can occur at many points in the program and recovery from them is difficult or impossible. A program declaring such exceptions would be pointlessly.

What if there is a break or return statement in try block followed by finally block? If there is a return statement in the try block, the finally block executes right after the return statement encountered, and before the return executes. Can we have the try block without catch block? Yes, we can have the try block without catch block, but finally block should follow the try block. Note: It is not valid to use a try clause without either a catch clause or a finally clause. What is the difference throw and throws? throws: Used in a method's signature if a method is capable of causing an exception that it does not handle, so that callers of the method can guard themselves against that exception. If a method is declared as throwing a particular class of exceptions, then any other method that calls it must either have a try-catch clause to handle that exception or must be declared to throw that exception (or its superclass) itself. A method that does not handle an exception it throws has to announce this:
public void myfunc(int arg) throws MyException { }

throw: Used to trigger an exception. The exception will be caught by the nearest try-catch clause that can catch that type of exception. The flow of execution stops immediately after the throw statement; any subsequent statements are not executed.

To throw an user-defined exception within a block, we use the throw command:


throw new MyException("I always wanted to throw an exception!");

How to create custom exceptions? By extending the Exception class or one of its subclasses. Example:
class MyException extends Exception { public MyException() { super(); } public MyException(String s) { super(s); } }

What are the different ways to handle exceptions? There are two ways to handle exceptions: Wrapping the desired code in a try block followed by a catch block to catch the exceptions. List the desired exceptions in the throws clause of the method and let the caller of the method handle those exceptions. What is the purpose of the finally clause of a try-catch-finally statement? The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught. What classes of exceptions may be caught by a catch clause? A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types. What is the base class from which all exceptions are subclasses ? Ans: All exceptions are subclasses of a class called java.lang.Throwable How do you intercept and thereby control exceptions ? Ans: We can do this by using try/catch/finally blocks You place the normal processing code in try block You put the code to deal with exceptions that might arise in try block in catch block Code that must be executed no matter what happens must be place in finally block When do we say an exception is handled ? Ans: When an exception is thrown in a try block and is caught by a matching catch block, the exception is considered to have been handled When do we say an exception is not handled ? Ans: There is no catch block that names either the class of exception that has been thrown or a class of exception that is a parent class of the one that has been thrown, then the exception is considered to be unhandled, in such condition the execution leaves the method directly as if no try has been executed In what sequence does the finally block gets executed ? Ans: If you put finally after a try block without a matching catch block then it will be executed after the try block If it is placed after the catch block and there is no exception then also it will be executed after the try block If there is an exception and it is handled by the catch block then it will be executed after the catch block What can prevent the execution of the code in finally block ? Ans: - The death of thread - Use of system.exit()

- Turning off the power to CPU - An exception arising in the finally block itself What are the rules for catching multiple exceptions - A more specific catch block must precede a more general one in the source, else it gives compilation error - Only one catch block, that is first applicable one, will be executed What does throws statement declaration in a method indicate ? This indicates that the method throws some exception and the caller method should take care of handling it What are checked exception ? Checked exceptions are exceptions that arise in a correct program, typically due to user mistakes like entering wrong data or I/O problems What are runtime exceptions ? Runtime exceptions are due to programming bugs like out of bond arrays or null pointer exceptions. What is difference between Exception and errors ? Errors are usually compile time and exceptions can be runtime or checked How will you handle the checked exceptions ? You can provide a try/catch block to handle it. OR Make sure method declaration includes a throws clause that informs the calling method an exception might be thrown from this particular method When you extend a class and override a method, can this new method throw exceptions other than those that were declared by the original method No it cannot throw, except for the subclasses of those exceptions Is it legal for the extending class which overrides a method which throws an exception, not o throw in the overridden class ? Yes it is perfectly legal When a program does not want to handle exception, the ______class is used. Ans : Throws The main subclass of the Exception class is _______ class. Ans : RuntimeException Only subclasses of ______class may be caught or thrown. Ans : Throwable Any user-defined exception class is a subclass of the _____ class. Ans : Exception What are checked exceptions ? Ans). The exceptions that are checked at compilation-time by the Java compiler are called checked exceptions. The exceptions that are checked by the JVM are called unchecked exceptions. What is Throwable ? Ans). Throwable is a class that represents all errors and exceptions which may occur in Java. Which is the super class for all exceptions ? Ans). Exception is the super class of all exceptions in Java.

What is the difference between an exception and an error ? Ans). An exception is an error which can be handled. It means when an exception happens, the programmer can do something to avoid any harm. But an error is an error which cannot be handled, it happens and the programmer cannot do any thing. What is the difference between throws and throw ? Ans). throws clause is used when the programmer does not want to handle the exception and throw it out of a method. throw clause is used when the programmer wants to throw an exception explicitly and wants to handle it using catch block. Hence, throws and throw are contracictory. Is it possible to re-throw exceptions ? Ans). Yes, we can re-throw an exception from catch block to another class where it can be handled.

Multi Threading

What kind of thread is the Garbage collector thread? It is a daemon thread. What is a Thread?
Thread is a part of execution which functions independently to complete the process. Huge Java programs which runs without Multi Threading leads to dead lock problems.

Let`s say you have thread T1, T2 and T3, how will you ensure that thread T2 run after T1 and thread T3 run after T2?
It can be achieved using join method of Thread class.

What is the difference between wait() and sleep() in Java? wait() method takes integer value (time) to make the process wait. While sleep() is used to pause the execution. What is synchronization in Multi-threading? Synchronization is the capability to control the access of multiple threads to shared resources. If we are not using Synchronization it may arise to significant error. What is the difference between Thread.start() method and Thread.run() method?

Thread.strat() method is used to run the Thread.run() method in a thread. run() method is used to start the thread. What is the difference between sleep() and suspend()? Thread.sleep() sends the current thread into the Not Runnable state. suspend() is deprecated, A suspended thread keeps all its monitors and since this state is not interruptable it is deadlock prone. How to create a thread in Java? Java team graciously designed two ways of creating threads. One method is by implementing Runnable interface, in java program. Another is by extending Thread class, in java program. ImplementingRunnable interface is the easiest method. In Java Multi threading where I need to place the main()? It is recommended that main thread must be the last to finish running. In fact, for some older JVMs, if main thread finishes before a child thread, then Java run time system may hang. What is thread priority? To see that all threads in an application runs equally, programmers use priority concept to set thread priority. Example: final void setPriority(int level); Level should be replaced with MIN_PRIORITY and MAX_PRIORITY values. MIN_PRIORITY is 1 and MAX_PRIORITY is 10. How to know the thread priority? isAlive() it returns true when Thread is running join() these two methods are used to know thread priority. What is a thread? What are the advantages we derived by programming with thread? Threads allow programs to execute simultaneously. A thread is an independent path of execution in a program. These threads can be executed synchronously............ Explain how to create a thread and start it running. There are 2 ways in which a thread can be created. By extending the Thread class wherein the subclass needs to override the run method. Then just an instance of that class needs to be created and [classname].start() would start it running............. How does threads stop method work. Stop() method of thread stops the thread execution. The security manager, if present, checks if the current thread is trying to stop some other thread. The stop method to stop the thread is an unsafe option............. How do we specify pause times in my program? Using the sleep function in Java, the threads execution can be put on hold. During this pause session, the thread does not loose ownership of the monitors............. What is multithreaded program? What is the importance of thread synchronization? A multithreaded program involves multiple threads of control in a single program. Each thread has its own stack. Other resources of the process are shared by all threads and while trying to access them it should be synchronized............. When a thread is created and started, what is its initial state?

A thread is in Ready state after it has been created and started............. What are the high-level thread states? The thread can be in one of the following states: Running state: A thread which is in running state has an access to the CPU. This means that the thread is being executed............. What is the difference between preemptive scheduling and time slicing? Under Preemptive scheduling, the task with the highest priority is executed until it enters the waiting or dead states or some other high priority task cones into............ What is a task's priority and how is it used in scheduling? Every task is assigned a priority for execution. The task with the highest priority is executed first. The low priority task is executed after that. This task priority is a............ What is a monitor? The mechanism that Java uses to support synchronization is the monitor............. Explain the use of synchronization keyword. A method, declared as synchronized, first attains a lock over an object before beginning an execution. Once it has finished with the execution, whether............ Explain how do we allow one thread to wait while other to finish. The wait method, notify method, and notifyAll method provide an efficient transfer of control from one thread to another............. Explain the purpose of yield method. The yield method causes the currently executing thread object to temporarily pause and allow other threads to execute............. What is the difference between yielding and sleeping? The sleep() causes the thread to suspend its running only for a specified amount of time............. Explain how to create thread in Java. We can create Thread in 2 ways in Java. Explain the difference between runnable and extends in java. We can use Extend Thread class only when the class...... Explain the term thread safety and synchronization. The term Thread safety means each method in a multithreaded.....

Why would you use a synchronized block vs. synchronized method? Synchronized blocks place locks for shorter periods than synchronized methods. What's the difference between the methods sleep() and wait() The code sleep(1000); puts thread to sleep (Or prevent the thread from executing) for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.

There are two classes: A and B. The class B need to inform a class A when some important event has happened. What Java technique would you use to implement it? If these classes are threads I'd consider notify() or notifyAll(). For regular classes you can use the Observer interface. What is Runnable interface ? Are there any other ways to make a multithreaded java program? There are two ways to create new threads: - Define a new class that extends the Thread class - Define a new class that implements the Runnable interface, and pass an object of that class to a Thread's constructor. The advantage of the second approach is that the new class can be a subclass of any class, not just of the Thread class. How can I tell what state a thread is in ? Prior to Java 5, isAlive() was commonly used to test a threads state. If isAlive() returned false the thread was either new or terminated but there was simply no way to differentiate between the two. Starting with the release of Java Tiger (Java 5) you can now get what state a thread is in by using the getState() method which returns an Enum of Thread.States. A thread can only be in one of the following states at a given point in time. New, Runnable, Blocked, Waiting, Timed_waiting and Terminated What is the difference between notify and notify All methods ? A call to notify causes at most one thread waiting on the same object to be notified (i.e., the object that calls notify must be the same as the object that called wait). A call to notifyAll causes all threads waiting on the same object to be notified. If more than one thread is waiting on that object, there is no way to control which of them is notified by a call to notifyAll so, sometimes it is better to use notify than notifyAll. What is synchronized keyword? In what situations you will Use it? Synchronization is the act of serializing access to critical sections of code. We will use this keyword when we expect multiple threads to access/modify the same data. It helps prevent dirty read/write and helps keep thread execution clean and seperate. For more details on why we need Synchronization and how to use it, you can visit the article on Thread Synchronization as it is a large topic to be covered as an answer to a single question. Why do threads block on I/O? Threads block on i/o (i.e., Thread enters the waiting state) so that other threads may execute while the i/o Operation is performed. This is done to ensure that one thread does not hold on to resources while it is waiting for some user input - like entering a password. What is synchronization and why is it important? With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors. For more details on why we need Synchronization and how to use it, you can visit the article on Thread Synchronization as it is a large topic to be covered as an answer to a single question. Can a lock be acquired on a class?

Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object. What's new with the stop(), suspend() and resume() methods in JDK 1.2? Actually there is nothing new about these methods. The stop(), suspend() and resume() methods have been deprecated as of JDK 1.2. What state does a thread enter when it terminates its processing? When a thread terminates its processing, it enters the dead state. How do you make threads to wait for one another to complete execution as a group? We can use the join() method to make threads wait for one another What is the difference between yielding and sleeping? When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state. What is the difference between preemptive scheduling and time slicing? Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and many other factors. You can refer to articles on Operating Systems and processor scheduling for more details on the same. When a thread blocks on I/O, what state does it enter? A thread enters the waiting state when it blocks on I/O. What is a task's priority and how is it used in scheduling? A task's priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks. When a thread is created and started, what is its initial state? A thread is in the ready state after it has been created and started. What invokes a thread's run() method? After a thread is started, via its start() method, the JVM invokes the thread's run() method when the thread needs to be executed. What method is invoked to cause an object to begin executing as a separate thread? The start() method of the Thread class is invoked to cause an object to begin executing as a separate thread. What is the purpose of the wait(), notify(), and notifyAll() methods? The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to wait for a shared resource. When a thread executes an object's wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the object's notify() or notifyAll() methods. What are the high-level thread states? The high-level thread states are ready, running, waiting, and dead. What is an object's lock and which object's have locks? An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object.

What happens when a thread cannot acquire a lock on an object? If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available. How does multithreading take place on a computer with a single CPU? The operating system's task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially. What happens when you invoke a thread's interrupt method while it is sleeping or waiting? When a task's interrupt() method is executed, the task enters the ready state. The next time the task enters the running state, an InterruptedException is thrown. How can a dead thread be restarted? A dead thread cannot be restarted. Once a thread is dead, it stays dead and there is no way to revive it. What are three ways in which a thread can enter the waiting state? A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method. What method must be implemented by all threads? All tasks must implement the run() method, whether they are a subclass of Thread or implement the Runnable interface. Without a run() method, a thread cannot execute. What are synchronized methods and synchronized statements? Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement. A synchronized statement can be inside a regular method and vice versa. What are volatile variables It indicates that these variables can be modified asynchronously. i.e., there is no need for synchronzing these variables in a multi-threaded environment. Where does java thread support reside It resides in three distinct places The java.lang.Thread class (Most of the support resides here) The java.lang.Object class The java language and virtual machine What is the difference between Thread and a Process Threads run inside process and they share data. One process can have multiple threads, if the process is killed all the threads inside it are killed What happens when you call the start() method of the thread This registers the thread with a piece of system code called thread scheduler. The schedulers is the entity that determines which thread is actually running. When the start() method is invoked, the thread becomes ready for running and will be executed when the processor allots CPU time to execute it. Does calling start () method of the thread causes it to run

No it just makes the thread eligible to run. The thread still has to wait for the CPU time along with the other threads, then at some time in future, the scheduler will permit the thread to run When the thread gets to execute, what does it execute It executes all the code that is placed inside the run() method. How many methods are declared in the interface runnable The runnable method declares only one method : public void run(); Which way would you prefer to implement threading - by extending Thread class or implementing Runnable interface The preferred way will be to use Interface Runnable, because by subclassing the Thread class you have single inheritance i.e you wont be able to extend any other class in Java. What happens when the run() method returns When the run() method returns, the thread has finished its task and is considered dead. You can't restart a dead thread. What are the different states of the thread The different states of Threads are: New: Just created Thraed Running: The state that all threads want to be Various waiting states : Waiting, Sleeping, Suspended and Blocked Ready : Waiting only for the CPU Dead : Story Over What is Thread priority Every thread has a priority, the higher priority thread gets preference over the lower priority thread by the thread scheduler What is the range of priority integer that can be set for Threads? It is from 1 to 10. 10 beings the highest priority and 1 being the lowest What is the default priority of the thread The default priority is 5. It is also called the Normal Priority. What happens when you call Thread.yield() It causes the currently executing thread to move to the ready state if the scheduler is willing to run any other thread in place of the yielding thread. Yield is a static method of class Thread What is the advantage of yielding It allows a time consuming thread to permit other threads to execute What happens when you call Thread.sleep() It causes the thread to while away time without doing anything and without using the CPU. A call to sleep method requests the currently executing thread to cease executing for a specified amount of time as mentioned in the argument to the sleep method. Does the thread method start executing as soon as the sleep time is over No, after the specified time is over the thread enters into ready state and will only execute when the scheduler allows it to do so. There is no guarantee that the thread will start running as soon as its sleep time is over.

What do you mean by thread blocking If a method needs to wait an indeterminable amount of time until some I/O occurrence takes place, then a thread executing that method should graciously step out of the Running state. All java I/O methods behave this way. A thread that has graciously stepped out in this way is said to be blocked. What threading related methods are there in object class wait(), notify() and notifyAll() are all part of Object class and they have to be called from synchronized code only What is preemptive scheduling Preemptive scheduing is a scheduling mechanism wherein, the scheduler puts a lower priority thread on hold when a higher priority thread comes into the waiting queue. The arrival of a higher priority thread always preempts the execution of the lower priority threads. The problem with this system is - a low priority thread might remain waiting for ever. What is non-preemptive or Time sliced or round robin scheduling With time slicing the thread is allowd to execute for a limited amount of time. It is then moved to ready state, where it must wait along with all the other ready threads. This method ensures that all threads get some CPU time to execute. What are the two ways of synchronizing the code Synchronizing an entire method by putting the synchronized modifier in the methods declaration. To execute the method, a thread must acquire the lock of the object that owns the method. Synchronize a subset of a method by surrounding the desired lines of code with curly brackets and inserting the synchronized expression before the opening curly. This allows you to synchronize the block on the lock of any object at all, not necessarily the object that owns the code What happens when the wait() method is called The following things happen: The calling thread gives up CPU The calling thread gives up the lock The calling thread goes into the monitor's waiting pool What happens when the notify() method is called One thread gets moved out of monitors waiting pool and into the ready state and The thread that was notified must reacquire the monitors lock before it can proceed execution Using notify () method how you can specify which thread should be notified You cannot specify which thread is to be notified, hence it is always better to call notifyAll() method

What is a daemon thread? These are the threads which can run without user intervention. The JVM can exit when there are daemon thread by killing them abruptly. What are the different identifier states of a Thread? The different identifiers of a Thread are: R - Running or runnable thread, S - Suspended thread, CW Thread waiting on a condition variable, MW - Thread waiting on a monitor lock, MS - Thread suspended waiting on a monitor lock Why do threads block on I/O?

Threads block on i/o (that is enters the waiting state) so that other threads may execute while the I/O operation is performed. What is synchronization and why is it important? With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that objects value. This often leads to significant errors. What is an objects lock and which objects have locks? An objects lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the objects lock. All objects and classes have locks. A classs lock is acquired on the classs Class object. What is the difference between Process and Thread? A process is a self contained execution environment and it can be seen as a program or application whereas Thread is a single task of execution within the process. Java runtime environment runs as a single process which contains different classes and programs as processes. Thread can be called lightweight process. Thread requires less resources to create and exists in the process, thread shares the process resources. What are the benefits of multi-threaded programming? In Multi-Threaded programming, multiple threads are executing concurrently that improves the performance because CPU is not idle incase some thread is waiting to get some resources. Multiple threads share the heap memory, so its good to create multiple threads to execute some task rather than creating multiple processes. For example, Servlets are better in performance than CGI because Servlet support multithreading but CGI doesnt. What is difference between user Thread and daemon Thread? When we create a Thread in java program, its known as user thread. A daemon thread runs in background and doesnt prevent JVM from terminating. When there are no user threads running, JVM shutdown the program and quits. A child thread created from daemon thread is also a daemon thread. How can we create a Thread in Java? There are two ways to create Thread in Java first by implementing Runnable interface and then creating a Thread object from it and second is to extend the Thread Class. Read this post to learn more about creating threads in java. What are different states in lifecycle of Thread? When we create a Thread in java program, its state is New. Then we start the thread that change its state to Runnable. Thread Scheduler is responsible to allocate CPU to threads in Runnable thread pool and change their state to Running. Other Thread states are Waiting, Blocked and Dead. Read this post to learn more about life cycle of thread. Can we call run() method of a Thread class? Yes, we can call run() method of a Thread class but then it will behave like a normal method. To actually execute it in a Thread, we need to start it using Thread.start() method. How can we pause the execution of a Thread for specific time? We can use Thread class sleep() method to pause the execution of Thread for certain time. Note that this will not stop the processing of thread for specific time, once the thread awake from sleep, its state gets changed to runnable and based on thread scheduling, it gets executed. What do you understand about Thread Priority?

Every thread has a priority, usually higher priority thread gets precedence in execution but it depends on Thread Scheduler implementation that is OS dependent. We can specify the priority of thread but it doesnt guarantee that higher priority thread will get executed before lower priority thread. Thread priority is an int whose value varies from 1 to 10 where 1 is the lowest priority thread and 10 is the highest priority thread. What is Thread Scheduler and Time Slicing? Thread Scheduler is the Operating System service that allocates the CPU time to the available runnable threads. Once we create and start a thread, its execution depends on the implementation of Thread Scheduler. Time Slicing is the process to divide the available CPU time to the available runnable threads. Allocation of CPU time to threads can be based on thread priority or the thread waiting for longer time will get more priority in getting CPU time. Thread scheduling cant be controlled by java, so its always better to control it from application itself. What is context-switching in multi-threading? Context Switching is the process of storing and restoring of CPU state so that Thread execution can be resumed from the same point at a later point of time. Context Switching is the essential feature for multitasking operating system and support for multi-threaded environment. How can we make sure main() is the last thread to finish in Java Program? We can use Thread join() method to make sure all the threads created by the program is dead before finishing the main function. Here is an article about Thread join method. How does thread communicate with each other? When threads share resources, communication between Threads is important to coordinate their efforts. Object class wait(), notify() and notifyAll() methods allows threads to communicate about the lock status of a resource. Check this post to learn more about thread wait, notify and notifyAll. Why thread communication methods wait(), notify() and notifyAll() are in Object class? In Java every Object has a monitor and wait, notify methods are used to wait for the Object monitor or to notify other threads that Object monitor is free now. There is no monitor on threads in java and synchronization can be used with any Object, thats why its part of Object class so that every class in java has these essential methods for inter thread communication. Why wait(), notify() and notifyAll() methods have to be called from synchronized method or block? When a Thread calls wait() on any Object, it must have the monitor on the Object that it will leave and goes in wait state until any other thread call notify() on this Object. Similarly when a thread calls notify() on any Object, it leaves the monitor on the Object and other waiting threads can get the monitor on the Object. Since all these methods require Thread to have the Object monitor, that can be achieved only by synchronization, they need to be called from synchronized method or block. How can we achieve thread safety in Java? There are several ways to achieve thread safety in java synchronization, atomic concurrent classes, implementing concurrent Lock interface, using volatile keyword, using immutable classes and Thread safe classes. Learn more at thread safety tutorial. What is volatile keyword in Java When we use volatile keyword with a variable, all the threads read its value directly from the memory and dont cache it. This makes sure that the value read is the same as in the memory. Which is more preferred Synchronized method or Synchronized block? Synchronized block is more preferred way because it doesnt lock the Object, synchronized methods lock the Object and if there are multiple synchronization blocks in the class, even though they are not related, it will stop them from execution and put them in wait state to get the lock on Object.

How to create daemon thread in Java? Thread class setDaemon(true) can be used to create daemon thread in java. We need to call this method before calling start() method else it will throw IllegalThreadStateException. What is ThreadLocal? Java ThreadLocal is used to create thread-local variables. We know that all threads of an Object share its variables, so if the variable is not thread safe, we can use synchronization but if we want to avoid synchronization, we can use ThreadLocal variables. Every thread has its own ThreadLocal variable and they can use its get() and set() methods to get the default value or change its value local to Thread. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread. Check this post for small example program showing ThreadLocal Example. What is Thread Group? Why its advised not to use it? ThreadGroup is a class which was intended to provide information about a thread group. ThreadGroup API is weak and it doesnt have any functionality that is not provided by Thread. Two of the major feature it had are to get the list of active threads in a thread group and to set the uncaught exception handler for the thread. But Java 1.5 has added setUncaughtExceptionHandler(UncaughtExceptionHandler eh) method using which we can add uncaught exception handler to the thread. So ThreadGroup is obsolete and hence not advised to use anymore. What is Java Thread Dump, How can we get Java Thread dump of a Program? Thread dump is list of all the threads active in the JVM, thread dumps are very helpful in analyzing bottlenecks in the application and analyzing deadlock situations. There are many ways using which we can generate Thread dump Using Profiler, Kill -3 command, jstack tool etc. I prefer jstack tool to generate thread dump of a program because its easy to use and comes with JDK installation. Since its a terminal based tool, we can create script to generate thread dump at regular intervals to analyze it later on. Read this post to know more about generating thread dump in java. What is Deadlock? How to analyze and avoid deadlock situation? Deadlock is a programming situation where two or more threads are blocked forever, this situation arises with at least two threads and two or more resources. To analyze a deadlock, we need to look at the java thread dump of the application, we need to look out for the threads with state as BLOCKED and then the resources its waiting to lock, every resource has a unique ID using which we can find which thread is already holding the lock on the object. Avoid Nested Locks, Lock Only What is Required and Avoid waiting indefinitely are common ways to avoid deadlock situation, read this post to learn how to analyze deadlock in java with sample program. What is Java Timer Class? How to schedule a task to run after specific interval? java.util.Timer is a utility class that can be used to schedule a thread to be executed at certain time in future. Java Timer class can be used to schedule a task to be run one-time or to be run at regular intervals. java.util.TimerTask is an abstract class that implements Runnable interface and we need to extend this class to create our own TimerTask that can be scheduled using java Timer class. Check this post for java Timer example. What is Thread Pool? How can we create Thread Pool in Java? A thread pool manages the pool of worker threads, it contains a queue that keeps tasks waiting to get executed. A thread pool manages the collection of Runnable threads and worker threads execute Runnable from the queue. java.util.concurrent.Executors provide implementation of java.util.concurrent.Executor interface to create the thread pool in java. Thread Pool Example program shows how to create and use Thread Pool in java. Which thread always runs in a Java program by default ? Ans). main thread. A thread represents execution of statements. The way the statements are executed is of

two types: 1). Single tasking 2). Multi tasking. Why threads are called light-weight ? Ans). Threads are light-weight because they utilize minimum resources of the system. This means they take less memory and less processor time. What is the difference between single tasking and multitasking ? Ans). Executing only one job at a time is called single tasking. Executing several jobs at a time is called multi tasking. In single tasking, the processor time is wasted, but in multi tasking, we can utilize the processor time in an optimum way. How can you stop a thread in Java ? Ans). First of all , we should create a boolean type variable which stores false . When the user wants to stop the thread. We should store trueinto the variable. The status of the variable is checked in the run ( ) method and if it is true, the thread executes return statement and then stops. What is the difference between extends Thread and implements Runnable ? Which one is advatageous ? Ans). extends Thread and implements Runnable both are functionally same. But when we write extends Thread, there is no scope to extend another class, as multiple inheritance is not supported in Java. Class Myclass extends Thread, AnotherClass //invalid If we write implements Runnable, then still there is scope to extend another class. class Myclass extends AnotherClass implements Runnable //valid This is definitely advantageous when the programmer wants to use threads and also wants to access the features of another class. Which method is executed by the thread by default ? Ans). public void run( ) method. What is Thread synchronization ? Ans). When a thread is already acting on an object, preventing any other thread from acting on the same object is called Thread synchronization or Thread safe The object on which the threads are synchronized is called synchronized object. Thread synchronization is recommended when multiple threads are used on the same object(in multithreading). What is the difference between synchronized block and synchronized keyword ? Ans). Synchronized block is useful to synchronized a block of statements. Synchronized keyword is useful to synchronize an entire method. What is Thread deadlock ? Ans). When a thread has locked an object and waiting for another object to be released by another thread.and the other thread is also waiting for the first thread to release the first object, both the threads will continue waiting forever. This is called Thread deadlock. What is the difference between the sleep( ) and wait( ) methods ? Ans). Both the sleep( ) and wait( ) methods are used to suspend a thread execution for a specified time. When sleep( ) is executed inside a synchronized block, the object is still under lock. When wait( ) method is executed, it breaks the synchronized block, so that the object lock is removed and it is available. Generally, sleep( ) is used for making a thread to wait for some time. But wait( ) is used in connection with notify ( ) or notifyAll( ) mehtods in therad communication. What is the default priority of a thread ? Ans). When a thread is created, by default its priority will be 5.

What is demon thread ? Ans). A daemon thread is a thread is a thread that executes continuously. Daemon threads are service providers for other threads or objects. It generally provides a background procssing. What is thread life cycle ? Ans). A thread is created using new Thread( ) statement and is executed by start( ) method. The thread enters runnable state and when sleep( ) or wait( ) methods are used or when the thread is blocked on I/O, it then goes into not runnable state. From not runnable state, the thread comes back to the runnable state and continues running the statements. The thread dies when it comes out of run( ) mehtod . These state thransitions of a thread are called life cycle of a thread. What state does a thread enter when it terminates its processing? When a thread terminates its processing, it enters the dead state.

IO
What is Externalizable? Externalizable is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in) What value does read() return when it has reached the end of a file? The read() method returns -1 when it has reached the end of a file. What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy? The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented. What is meant by Stream and what are the types of Streams and classes of the Streams? A Stream is an abstraction that either produces or consumes information. There are two types of Streams. They are: Byte Streams : Byte Streams provide a convenient means for handling input and output of bytes. Character Streams : Character Streams provide a convenient means for handling input and output of characters. Byte Stream classes : Byte Streams are defined by using two abstract classes. They are: 1. InputStream 2.OutputStream. Character Stream classes : Character Streams are defined by using two abstract classes. They are : 1.Reader 2.Writer. What is the difference between String and StringBuffer classes? Ans). String class objects are immutable and hence their contents cannot be modified. StringBuffer class objects are mutable, so they can be modified. Moreover the methods that directly manipulate data of the

object are not available in String class. Such methods are available in StringBuffer class. What is the difference between Serializable and Externalizable interface in Java? This is most frequently asked question in Java serialization interview. Here is my version Externalizable provides us writeExternal() and readExternal() method which gives us flexibility to control java serialization mechanism instead of relying on Java's default serialization. Correct implementation of Externalizable interface can improve performance of application drastically. How many methods Serializable has? If no method then what is the purpose of Serializable interface? Serializable interface exists in java.io package and forms core of java serialization mechanism. It doesn't have any method and also called Marker Interface in Java. When your class implements java.io.Serializable interface it becomes Serializable in Java and gives compiler an indication that use Java Serialization mechanism to serialize this object. What is serialVersionUID? What would happen if you don't define this? One of my favorite question interview question on Java serialization. SerialVersionUID is an ID which is stamped on object when it get serialized usually hashcode of object, you can use tool serialver to see serialVersionUID of a serialized object . SerialVersionUID is used for version control of object. you can specify serialVersionUID in your class file also. Consequence of not specifying serialVersionUID is that when you add or modify any field in class then already serialized class will not be able to recover because serialVersionUID generated for new class and for old serialized object will be different. Java serialization process relies on correct serialVersionUID for recovering state of serialized object and throws java.io.InvalidClassException in case of serialVersionUID mismatch. While serializing you want some of the members not to serialize? How do you achieve it? Another frequently asked Serialization interview question. This is sometime also asked as what is the use of transient variable, does transient and static variable gets serialized or not etc. so if you don't want any field to be part of object's state then declare it either static or transient based on your need and it will not be included during Java serialization process. What will happen if one of the members in the class doesn't implement Serializable interface? One of the easy question about Serialization process in Java. If you try to serialize an object of a class which implements Serializable, but the object includes a reference to an non- Serializable class then a NotSerializableException will be thrown at runtime and this is why I always put a SerializableAlert (comment section in my code) , one of the code comment best practices, to instruct developer to remember this fact while adding a new field in a Serializable class. If a class is Serializable but its super class in not, what will be the state of the instance variables inherited from super class after deserialization? Java serialization process only continues in object hierarchy till the class is Serializable i.e. implements Serializable interface in Java and values of the instance variables inherited from super class will be initialized by calling constructor of Non-Serializable Super class during deserialization process. Once the constructor chaining will started it wouldn't be possible to stop that , hence even if classes higher in hierarchy implements Serializable interface , there constructor will be executed. As you see from the statement this Serialization interview question looks very tricky and tough but if you are familiar with key concepts its not that difficult. Can you Customize Serialization process or can you override default Serialization process in Java? The answer is yes you can. We all know that for serializing an object ObjectOutputStream.writeObject (saveThisobject) is invoked and for reading object ObjectInputStream.readObject() is invoked but there is one more thing which Java Virtual Machine provides you is to define these two method in your class. If you define these two methods in your class then JVM will invoke these two methods instead of applying default

serialization mechanism. You can customize behavior of object serialization and deserialization here by doing any kind of pre or post processing task. Important point to note is making these methods private to avoid being inherited, overridden or overloaded. Since only Java Virtual Machine can call private method integrity of your class will remain and Java Serialization will work as normal. In my opinion this is one of the best question one can ask in any Java Serialization interview, a good follow-up question is why should you provide custom serialized form for your object? Suppose super class of a new class implement Serializable interface, how can you avoid new class to being serialized? One of the tricky interview question in Serialization in Java. If Super Class of a Class already implements Serializable interface in Java then its already Serializable in Java, since you can not unimplemented an interface its not really possible to make it Non Serializable class but yes there is a way to avoid serialization of new class. To avoid java serialization you need to implement writeObject() and readObject() method in your Class and need to throw NotSerializableException from those method. This is another benefit of customizing java serialization process as described in above Serialization interview question and normally it asked as follow-up question as interview progresses. Which methods are used during Serialization and DeSerialization process in java? This is very common interview question in Serialization basically interviewer is trying to know; Whether you are familiar with usage of readObject(), writeObject(), readExternal() and writeExternal () or not. Java Serialization is done by java.io.ObjectOutputStream class. That class is a filter stream which is wrapped around a lower-level byte stream to handle the serialization mechanism. To store any object via serialization mechanism we call ObjectOutputStream.writeObject(saveThisobject) and to deserialize that object we call ObjectInputStream.readObject() method. Call to writeObject() method trigger serialization process in java. one important thing to note about readObject() method is that it is used to read bytes from the persistence and to create object from those bytes and its return an Object which needs to be casted on correct type. Suppose you have a class which you serialized it and stored in persistence and later modified that class to add a new field. What will happen if you deserialize the object already serialized? It depends on whether class has its own serialVersionUID or not. As we know from above question that if we don't provide serialVersionUID in our code java compiler will generate it and normally its equal to hashCode of object. by adding any new field there is chance that new serialVersionUID generated for that class version is not the same of already serialized object and in this case Java Serialization API will throw java.io.InvalidClassException and this is the reason its recommended to have your own serialVersionUID in code and make sure to keep it same always for a single class. What are the compatible changes and incompatible changes in Java Serialization Mechanism? The real challenge lies with change in class structure by adding any field, method or removing any field or method is that with already serialized object. As per Java Serialization specification adding any field or method comes under compatible change and changing class hierarchy or UN-implementing Serializable interfaces some under non compatible changes. For complete list of compatible and non compatible changes I would advise reading Java serialization specification. Can we transfer a Serialized object vie network? Yes you can transfer a Serialized object via network because java serialized object remains in form of bytes which can be transmitter via network. You can also store serialized object in Disk or database as Blob. Which kind of variables is not serialized during Java Serialization? This question asked sometime differently but the purpose is same whether Java developer knows specifics about static and transient variable or not. Since static variables belong to the class and not to an object they are not the part of the state of object so they are not saved during Java Serialization process. As Java Serialization only persist state of object and not object itself. Transient variables are also not included in java serialization process and are not the part of the objects serialized state. After this question sometime

interviewer ask a follow-up if you don't store values of these variables then what would be value of these variable once you deserialize and recreate those object? This is for you guys to think about :) What is the difference between System.out and System.err ? Ans). Both are used to display messages on the monitor. System.out is used to display normal messages As: System.out.println(This is nayanimuralidhar); System.err.println(This is an error); What is the advantage of stream concept..? Ans). Streams are mainly useful to move data from one place to another place. This concept can be used to receive data from an input device and send data to an output device. What is the default buffer size used by any buffered class ? Ans). 512 bytes. What is serialization ? Ans). Serialization is the process of storing object contents into a file. The class whose objects are stored in the file should implement serializable interface of java.io.package. What type of variables cannot be serialized ? Ans). Static and transient variables cannot be serialized. Once the objects are stored into a file, they can be later retrieved and used as and when needed.This is called de-serialization. What is IP address ? Ans). An IP address is a unique identification number allocated to every computer on a network or Internet. IP address contains some bytes which identify the network and the actual computer inside the network. What is DNS ? Ans). Domain Naming Service is a service on Internet that maps the IP address with corresponding website names. What is a socket ? Ans). A socket is a point of conneciton between a server and a client on a network. What is port number ? Ans). Port number ia a 2 byte number which is used to identify a socket uniquely.

Collection Framework
What is a collection ? A collection represents a group of elements like integer values or objects. Examples for collections are arrays and java.util_classes (stack, LinkedList, ;Vector, etc).

What is the significance of ListIterator? You can iterate back and forth. What is the major difference between LinkedList and ArrayList? LinkedList are meant for sequential accessing. ArrayList are meant for random accessing. What is the Collections API? The Collections API is a set of classes and interfaces that support operations on collections of objects. Which characters may be used as the second character of an identifier, but not as the first character of an identifier? The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier. What is the List interface? The List interface provides support for ordered collections of objects. How does Java handle integer overflows and underflows? It uses those low order bytes of the result that can fit into the size of the type allowed by the operation. What is the Vector class? The Vector class provides the capability to implement a growable array of objects Explain about Java Collections API? Java Collections Framework provides a set of interfaces and classes that support operations on a collections of objects. What is the Set interface? The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements. What is the List interface? The List interface provides support for ordered collections of objects. What is the difference between set and list? Set stores elements in an unordered way but does not contain duplicate elements, where as List stores elements in an ordered way but may contain duplicate elements. What is map interface in a java? Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. This Map permits null value What is the difference between Map and Hashmap? Map is Interface and Hashmap is class that implements that What is the difference between a HashMap and a Hashtable in Java? Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.

Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values. One of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for aLinkedHashMap. This wouldn't be as easy if you were using Hashtable.

What is a vector in Java? Vector implements a dynamic array. It is similar to ArrayList, but with two differences: Vector is synchronized, and it contains many legacy methods that are not part of the collections framework. What is ArrayList In java? ArrayList is a part of the Collection Framework. We can store any type of objects, and we can deal with only objects. It is growable. Difference between Vector and ArrayList? Vector & ArrayList both classes are implemented using dynamically resizable arrays, providing fast random access and fast traversal. ArrayList and Vector class both implement the List interface. Synchronization - ArrayList is not thread-safe whereas Vector is thread-safe. In Vector class each method like add(), get(int i) is surrounded with a synchronized block and thus making Vector class thread-safe. 2) Data growth - Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent. What is an Iterator interface? The Iterator is an interface, used to traverse through the elements of a Collection. It is not advisable to modify the collection itself while traversing an Iterator. what is Enumeration in java? An enumeration is an object that generates elements one at a time, used for passing through a collection, usually of unknown size. The traversing of elements can only be done once per creation. What is difference between Iterator and Enumeration? Both Iterator and Enumeration are used to traverse Collection objects, in a sequential fashion. Enumeration can be applied to Vector and HashTable. Iterator can be used with most of the Collection objects. The main difference between the two is that Iterator is fail-safe. i.e, If you are using an iterator to go through a collection you can be sure of no concurrent modifications in the underlying collection which may happen in multi-threaded environments. What is the Properties class? The properties class is a subclass of Hashtable that can be read from or written to a stream. It also provides the capability to specify a set of default values to be used. What is difference between HashMap and HashSet? HashSet : HashSet does not allow duplicate values. It provides add method rather put method. You also use its contain method to check whether the object is already available in HashSet. HashSet can be used where you want to maintain a unique list.

HashMap : It allows null for both key and value. It is unsynchronized. So come up with better performance What is the Difference between the Iterator and ListIterator? Iterator : Iterator takes the place of Enumeration in the Java collections framework. One can traverse throughr the the collection with the help of iterator in forward direction only and Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics ListIterator: An iterator for lists that allows one to traverse the list in either direction.modify the list during iteration, and obtain the iterator's current position in the list. A ListIterator has no current element. its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next(). In a list of length n, there are n+1 valid index values, from 0 to n, inclusive. What is TreeSet ? TreeSet - It is the implementation of SortedSet interface.This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains). The class is not synchronized. What is a collection framework ? Ans). A collection framework is a class library to handle groups of objects. Collection framework is implemented in java.util.package. Does a collection object store copies of other objects or their references ? Ans). A Collection object stores references of other objects. Can you store a primitive data type into a collection ? Ans). No, Collections store only objects. What is the difference between Iterator and ListIterator ? Ans). Both are useful to retreive elements from a collection. Iterator can retrieve the elements only in forward direction. But Listener can retrieve the elements in forward and backward direction also. So ListIterator is preferred to Iterator. What is the difference between Iterator and Enumeration ? Ans). Both are useful to retreive elements from a collection. Iterator has methods whose names are easy to follow and Enumeration methods are difficult to remember. Also Iterator has an option to remove elements from the collection which is not available in Enumeration. So, Iterator is preferred to Enumeration. What is the difference between a Stack and LinkedList ? Ans). 1. A Stack is generally used for the purpose of evaluation of expression. A LinkedList is used to store and retrieve data. 2. Insertion and deletion of elements only from the top of the Stack is possible. Insertion and deletion of elements from any where is possible in case of a LinkedList. What is the difference between ArrayList and Vector ? ArrayList Vector

ArrayList object is not synchronized by default

Vector object is synchronized by default.

Incase of a single thread, using ArrayList is In case of multiple threads, using Vector is advisable. With a faster than the Vector. single thread, Vector becomes slow. ArrayList increases its size every time by 50 Vector increases its size every time by doubling it. percent (half). Can you synchronize the ArrayList object ? Ans). Yes, we can use synchronizedList( ) method to synchronize the ArrayList, as: Collections.synchronizedList(new ArrayList( )); What is the load factor for a HashMap or Hashtable ? Ans). 0.75. What is the difference between HashMap and Hashtable ? Ans). HashMap HashMap object is not synchronized by default. In case of a single thread, using HashMap is faster than the Hashtable. HashMap allows null keys and null values to be stored.

Hashtable

Hashtable object is synchronized by default. In case of multiple threads, using Hashtable is advisable, with a single thread, Hashtable becomes slow. Hashtable does not allow null keys or values.

Enumeration for the Hashtable is not fail-fast. This Iterator in the HashMap is fail-fast. This means means even if concurrent updations are done to Iterator will produce exeception if concurrent updates Hashtable, there will not be any incorrect results are made to the HashMap. produced by the Enumeration.

Can you make HashMap synchronized ? Ans). Yes, we can make HashMap object synchronized using synchronizedMap( ) method as shown here: Collections.synchronizedMap(new HashMap( )); What is the difference between a Set and a List ? Set List

A set represents a collection of elements. Order A List represents ordered collection of elements.List of the elements may change in the set. preserves the order of elements in which they are entered. Set will not allow duplicate values to be stored. List will allow duplicate values. Accessing elements by their index (position number) is not possible in case of sets. Sets will not allow null elements. Accessing elements by index is possible in lists. Lists allow null elements to be stored.

You might also like