Java Interview Questions -17

Java Interview Questions -17

1. How does a try statement determine which catch clause should be used to handle an exception?
When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exceptionis executed. The remaining catch clauses are ignored.

2. 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.

3. 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.

4. Can an unreachable object become reachable again?
An unreachable object may become reachable again. This can happen when the object's finalize() method is invoked and the object performs an operation which causes it to become accessible to reachable objects.

5. Can a .java file contain more than one java classes?
Yes. A .java file contain more than one java classes, provided at the most one of them is a public class.

6.Is String a primitive data type in Java?
No. String is not a primitive data type in Java, even though it is one of the most extensively used object. Strings in Java are instances of String class defined in java.lang package.

7. 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 doesn't 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).

8. 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.

9. Is Empty .java file a valid source file?
Yes. An empty .java file is a perfectly valid source file.

10. Is main a keyword in Java?
No. main is not a keyword in Java.

11. What is daemon thread and which method is used to create the daemon thread?
Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system.setDaemon method is used to create a daemon thread.

12. Can applets communicate with each other?
At this point in time applets may communicate with other applets running in the same virtual machine. If the applets are of the same class, they can communicate via shared static variables. If the applets are of different classes, then each will need a reference to the same class with static variables. In any case the basic idea is to pass the information back and forth through a static variable.
An applet can also get references to all other applets on the same page using the getApplets() method of java.applet.AppletContext. Once you get the reference to an applet, you can communicate with it by using its public members.
It is conceivable to have applets in different virtual machines that talk to a server somewhere on the Internet and store any data that needs to be serialized there. Then, when another applet needs this data, it could connect to this same server. Implementing this is non-trivial.

13. What are the steps in the JDBC connection?
While making a JDBC connection we go through the following steps :
Step 1 : Register the database driver by using :
Class.forName(\" driver classs for that specific database\" );
Step 2 : Now create a database connection using :
Connection con = DriverManager.getConnection(url,username,password);
Step 3: Now Create a query using :
Statement stmt = Connection.Statement(\"select * from TABLE NAME\");
Step 4 : Exceute the query :

14. What is the default value of the local variables?
The local variables are not initialized to any default value, neither primitives nor object references. If you try to use these variables without initializing them explicitly, the java compiler will not compile the code. It will complain abt the local varaible not being initilized.

15. 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.

16. 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.

17. How many objects are created in the following piece of code?
MyClass c1, c2, c3;
c1 = new MyClass ();
c3 = new MyClass ();
Only 2 objects are created, c1 and c3. The reference c2 is only declared and not initialized.

18. Is next a keyword in Java?
No. next is not a keyword.

19. Is delete a keyword in Java?
No. delete is not a keyword in Java. Java does not make use of explicit destructors the way C++ does.

20. Is exit a keyword in Java?
No. To exit a program explicitly you use exit method in System object.

21. What happens if you dont initialize an instance variable of any of the primitive types in Java?
Java by default initializes it to the default value for that primitive type. Thus an int will be initialized to 0(zero), a boolean will be initialized to false.

22. 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. However in order to do anything useful with these references, you must set them to a valid object, else you will get NullPointerExceptions everywhere you try to use such default initialized references.

23. What are the different scopes for Java variables?
The scope of a Java variable is determined by the context in which the variable is declared. Thus a java variable can have one of the three scopes at any given point in time.
1. Instance : - These are typical object level variables, they are initialized to default values at the time of creation of object, and remain accessible as long as the object accessible.
2. Local : - These are the variables that are defined within a method. They remain accessbile only during the course of method excecution. When the method finishes execution, these variables fall out of scope.
3. Static: - These are the class level variables. They are initialized when the class is loaded in JVM for the first time and remain there as long as the class remains loaded. They are not tied to any particular object instance.

24. 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).

25. What modifiers are allowed for methods in an Interface?
Only public and abstract modifiers are allowed for methods in interfaces.

26. Can a public class MyClass be defined in a source file named
No. The source file name, if it contains a public class, must be the same as the public class name itself with a .java extension.

27. Can main() method be declared final?
Yes, the main() method can be declared final, in addition to being public static.

28. What is HashMap and Map?
Map is an Interface and Hashmap is the class that implements Map.

29. Can you write a Java class that could be used both as an applet as well as an application?
A. Yes. Add a main() method to the applet.

30. What's the difference between constructors and other methods?
A. Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times.

31. Difference between HashMap and HashTable?
The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow).
HashMap does not guarantee that the order of the map will remain constant over time. HashMap is unsynchronized and Hashtable is synchronized.

32. Difference between Vector and ArrayList?
Vector is synchronized whereas arraylist is not.

33. Difference between Swing and Awt?
AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works faster than AWT.

34. What will be the default values of all the elements of an array defined as an instance variable?
If the array is an array of primitive types, then all the elements of the array will be initialized to the default value corresponding to that primitive type.
Example: All the elements of an array of int will be initialized to 0(zero), while that of boolean type will be initialized to false. Whereas if the array is an array of references (of any type), all the elements will be initialized to null.

35.What are Class, Constructor and Primitive data types?
Class is a template for multiple objects with similar features and it is a blue print for objects. It defines a type of object according to the data the object can hold and the operations the object can perform. Constructor is a special kind of method that determines how an object is initialized when created. Primitive data types are 8 types and they are: byte, short, int, long, float, double, boolean, char.

36.What is an Object and how do you allocate memory to it?
Object is an instance of a class and it is a software unit that combines a structured set of data with a set of operations for inspecting and manipulating that data. When an object is created using new operator, memory is allocated to it.

37.What is the difference between constructor and method?
Constructor will be automatically invoked when an object is created whereas method has to be called explicitly.

38.What is the difference between procedural and object-oriented programs?-
 a) In procedural program, programming logic follows certain procedures and the instructions are executed one after another. In OOP program, unit of program is object, which is nothing but combination of data and code. b) In procedural program, data is exposed to the whole program whereas in OOPs program, it is accessible with in the object and which in turn assures the security of the code.

39.What are Encapsulation, Inheritance and Polymorphism?
Encapsulation is the mechanism that binds together code and data it manipulates and keeps both safe from outside interference and misuse. Inheritance is the process by which one object acquires the properties of another object. Polymorphism is the feature that allows one interface to be used for general class actions.

40.What is casting?- Casting is used to convert the value of one type to another.
How many ways can an argument be passed to a subroutine and explain them?- An argument can be passed in two ways. They are passing by value and passing by reference. Passing by value: This method copies the value of an argument into the formal parameter of the subroutine. Passing by reference: In this method, a reference to an argument (not the value of the argument) is passed to the parameter.

41.What is the difference between an argument and a parameter?
While defining method, variables passed in the method are called parameters. While using those methods, values passed to those variables are called arguments.

42.What are different types of access modifiers?
public: Any thing declared as public can be accessed from anywhere. private: Any thing declared as private can’t be seen outside of its class. protected: Any thing declared as protected can be accessed by classes in the same package and subclasses in the other packages. default modifier : Can be accessed only to classes in the same package.

43.What is final, finalize() and finally?
final : final keyword can be used for class, method and variables. A final class cannot be subclassed and it prevents other programmers from subclassing a secure class to invoke insecure methods. A final method can’t be overridden. A final variable can’t change from its initialized value. finalize() : finalize() method is used just before an object is destroyed and can be called just prior to garbage collection. finally : finally, a key word used in exception handling, creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. The finally block will execute whether or not an exception is thrown. For example, if a method opens a file upon exit, then you will not want the code that closes the file to be bypassed by the exception-handling mechanism. This finally keyword is designed to address this contingency.

44.What is UNICODE?
Unicode is used for internal representation of characters and strings and it uses 16 bits to represent each other.

45.What are Transient and Volatile Modifiers?
Transient: The transient modifier applies to variables only and it is not stored as part of its object’s Persistent state. Transient variables are not serialized. Volatile: Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.

46.What is the difference between Assignment and Initialization?
Assignment can be done as many times as desired whereas initialization can be done only once.

47.What is Garbage Collection and how to call it explicitly?
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. System. gc() method may be used to call it explicitly.

48.What is finalize() method?
finalize () method is used just before an object is destroyed and can be called just prior to garbage collection.

49.What is OOPs?
Object oriented programming organizes a program around its data, i. e. , objects and a set of well defined interfaces to that data. An object-oriented program can be characterized as data controlling access to code.

50.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.

51.What is the use of bin and lib in JDK?
Bin contains all tools such as javac, appletviewer, awt tool, etc., whereas lib contains API and all packages.

52.What is method overloading and method overriding?
Method overloading: When a method in a class having the same method name with different arguments is said to be method overloading. Method overriding : When a method in a class having the same method name with same arguments is said to be method overriding.

53.What is difference between overloading and overriding?
a) In overloading, there is a relationship between methods available in the same class whereas in overriding, there is relationship between a superclass method and subclass method. b) Overloading does not block inheritance from the superclass whereas overriding blocks inheritance from the superclass. c) In overloading, separate methods share the same name whereas in overriding, subclass method replaces the superclass. d) Overloading must have different method signatures whereas overriding must have same signature.

54.What is meant by Inheritance and what are its advantages?
Inheritance is the process of inheriting all the features from a class. The advantages of inheritance are reusability of code and accessibility of variables and methods of the super class by subclasses.

55.What are inner class and anonymous class?
Inner class : classes defined in other classes, including those defined in methods are called inner classes. An inner class can have any accessibility including private. Anonymous class : Anonymous class is a class defined inside a method without a name and is instantiated and declared in the same place and cannot have explicit constructors.

56.What is a package?
A package is a collection of classes and interfaces that provides a high-level layer of access protection and name space management.

57.What is the difference between this() and super()?
this() can be used to invoke a constructor of the same class whereas super() can be used to invoke a super class constructor.

58.What is the difference between superclass and subclass?
A super class is a class that is inherited whereas sub class is a class that does the inheriting.

59.What modifiers may be used with top-level class?
public, abstract and final can be used for top-level class.

60.What is a reflection package?
java. lang. reflect package has the ability to analyze itself in runtime.

61.What is interface and its use?
Interface is similar to a class which may contain method’s signature only but not bodies and it is a formal set of method and constant declarations that must be defined by the class that implements it. Interfaces are useful for: a)Declaring methods that one or more classes are expected to implement b)Capturing similarities between unrelated classes without forcing a class relationship. c)Determining an object’s programming interface without revealing the actual body of the class.

62.Can you have an inner class inside a method and what variables can you access?
Yes, we can have an inner class inside a method and final variables can be accessed.

63.What is the difference between String and String Buffer?
a) String objects are constants and immutable whereas StringBuffer objects are not. b) String class supports constant strings whereas StringBuffer class supports growable and modifiable strings.

64.What is the difference between Array and vector?
Array is a set of related data type and static whereas vector is a growable array of objects and dynamic.

65.What is an abstract class?
An abstract class is a class designed with implementation gaps for subclasses to fill in and is deliberately incomplete.

66.What is the difference between exception and error?
The exception class defines mild error conditions that your program encounters. Exceptions can occur when trying to open the file, which does not exist, the network connection is disrupted, operands being manipulated are out of prescribed ranges, the class file you are interested in loading is missing. The error class defines serious error conditions that you should not attempt to recover from. In most cases it is advisable to let the program terminate when such an error is encountered.

67.What is the difference between process and thread?
Process is a program in execution whereas thread is a separate path of execution in a program.

68.What is multithreading and what are the methods for inter-thread communication and what is the class in which these methods are defined?
Multithreading is the mechanism in which more than one thread run independent of each other within the process. wait (), notify () and notifyAll() methods can be used for inter-thread communication and these methods are in Object class. wait() : When a thread executes a call to wait() method, it surrenders the object lock and enters into a waiting state. notify() or notifyAll() : To remove a thread from the waiting state, some other thread must make a call to notify() or notifyAll() method on the same object.

69.What is an event and what are the models available for event handling?
An event is an event object that describes a state of change in a source. In other words, event occurs when an action is generated, like pressing button, clicking mouse, selecting a list, etc. There are two types of models for handling events and they are: a) event-inheritance model and b) event-delegation model

70.What are the advantages of the model over the event-inheritance model?
The event-delegation model has two advantages over the event-inheritance model. They are: a)It enables event handling by objects other than the ones that generate the events. This allows a clean separation between a component’s design and its use. b)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 be repeatedly process unhandled events as is the case of the event-inheritance.

71.What is the class and interface in java to create thread and which is the most advantageous method?
Thread class and Runnable interface can be used to create threads and using Runnable interface is the most advantageous method to create threads because we need not extend thread class here.

72.What is the difference between abstract class and interface?
a) All the methods declared inside an interface are abstract whereas abstract class must have at least one abstract method and others may be concrete or abstract. b) In abstract class, key word abstract must be used for the methods whereas interface we need not use that keyword for the methods. c) Abstract class must have subclasses whereas interface can’t have subclasses.

73.What is synchronization?
Synchronization is the mechanism that ensures that only one thread is accessed the resources at a time.

74.Are there any global variables in Java, which can be accessed by other part of your program?
No, it is not the main method in which you define variables. Global variables is not possible because concept of encapsulation is eliminated here.

75.What is an applet?
Applet is a dynamic and interactive program that runs inside a web page displayed by a java capable browser.

76.What is the difference between applications and applets?
a)Application must be run on local machine whereas applet needs no explicit installation on local machine. b)Application must be run explicitly within a java-compatible virtual machine whereas applet loads and runs itself automatically in a java-enabled browser. d)Application starts execution with its main method whereas applet starts execution with its init method. e)Application can run with or without graphical user interface whereas applet must run within a graphical user interface.

77.How does applet recognize the height and width?
Using getParameters() method.

78.When you will synchronize a piece of your code?
When you expect your code will be accessed by different threads and these threads may change a particular data causing data corruption.

79.What is deadlock?
When two threads are waiting each other and can’t precede the program is said to be deadlock.

80.What is daemon thread and which method is used to create the daemon thread?
Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. setDaemon method is used to create a daemon thread.

81.When do you use codebase in applet?
When the applet class file is not in the same directory, codebase is used.

82.What is the lifecycle of an applet?
init() method - Can be called when an applet is first loaded start() method - Can be called each time an applet is started. paint() method - Can be called when the applet is minimized or maximized. stop() method - Can be used when the browser moves off the applet’s page. destroy() method - Can be called when the browser is finished with the applet.

83.How do you set security in applets?
using setSecurityManager() method

84.What are the states associated in the thread?
Thread contains ready, running, waiting and dead states.

85.What is the difference between Integer and int?
a) Integer is a class defined in the java. lang package, whereas int is a primitive data type defined in the Java language itself. Java does not automatically convert from one to the other. b) Integer can be used as an argument for a method that requires an object, whereas int can be used for calculations.

86.What is a cloneable interface and how many methods does it contain?
It is not having any method because it is a TAGGED or MARKER interface.

87.What is source and listener?
source : A source is an object that generates an event. This occurs when the internal state of that object changes in some way. listener : A listener is an object that is notified when an event occurs. It has two major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and process these notifications.

88.What is adapter class?
An adapter class provides an empty implementation of all methods in an event listener interface. Adapter classes are useful when you want to receive and process only some of the events that are handled by a particular event listener interface. You can define a new class to act listener by extending one of the adapter classes and implementing only those events in which you are interested. For example, the MouseMotionAdapter class has two methods, mouseDragged()and mouseMoved(). The signatures of these empty are exactly as defined in the MouseMotionListener interface. If you are interested in only mouse drag events, then you could simply extend MouseMotionAdapter and implement mouseDragged() .

89.What is meant by controls and what are different types of controls in AWT?
Controls are components that allow a user to interact with your application and the AWT supports the following types of controls: Labels, Push Buttons, Check Boxes, Choice Lists, Lists, Scrollbars, Text Components. These controls are subclasses of Component.

90.What is the difference between choice and list?
A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices and only one item may be selected from a choice. A List may be displayed in such a way that several list items are visible and it supports the selection of one or more list items.

91.What is the difference between scrollbar and scrollpane?
A Scrollbar is a Component, but not a Container whereas Scrollpane is a Conatiner and handles its own events and perform its own scrolling.

92.What is a layout manager and what are different types of layout managers available in java AWT?
A layout manager is an object that is used to organize components in a container. The different layouts are available are FlowLayout, BorderLayout, CardLayout, GridLayout and GridBagLayout.

93.How are the elements of different layouts organized?
FlowLayout: The elements of a FlowLayout are organized in a top to bottom, left to right fashion. BorderLayout: The elements of a BorderLayout are organized at the borders (North, South, East and West) and the center of a container. CardLayout: The elements of a CardLayout are stacked, on top of the other, like a deck of cards. GridLayout: The elements of a GridLayout are of equal size and are laid out using the square of a grid. GridBagLayout: The elements of a GridBagLayout are organized according to a grid. However, the elements are of different size and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes.

94. What's the difference between J2SDK 1.5 and J2SDK 5.0?
A.There's no difference, Sun Microsystems just re-branded this version.

95. What's the difference between the methods sleep() and wait()
A. The code sleep(1000); puts thread aside 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.

96. Can you call one constructor from another if a class has multiple constructors
A. Yes. Use this() syntax.

97. Explain the usage of Java packages.
A. This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes.

98. Explain the usage of the keyword transient?
A. This keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).

99. How can you force garbage collection?
A. You can't force GC, but could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.

100. If a class is located in a package, what do you need to change in the OS environment to be able to use it?
A. You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable. Let's say a class Employee belongs to a package; and is located in the file c:\dev\com\xyz\hr\ In this case, you'd need to add c:\dev to the variable CLASSPATH. If this class contains the method main(), you could test it from a command prompt window as follows:

101. 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?
A. If these classes are threads I'd consider notify() or notifyAll(). For regular classes you can use the Observer interface.

102.What access level do you need to specify in the class declaration to ensure that only classes from the same directory can access it?
A. You do not need to specify any access level, and Java will use a default package access level.

103. Can an inner class declared inside of a method access local variables of this method?
A. It's possible if these variables are final.

104. What comes to mind when you hear about a young generation in Java?
A. Garbage collection.

105. What would you use to compare two String variables - the operator == or the method equals()?
A. I'd use the method equals() to compare the values of the Strings and the == to check if two variables point at the same instance of a String object.

106. Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?
A. Yes, it does. The FileNoFoundException is inherited from the IOException. Exception's subclasses have to be caught first.

107. How can you minimize the need of garbage collection and make the memory use more effective?
A. Use object pooling and weak object references.

108. What can go wrong if you replace && with & in the following code:
String a=null; if (a!=null && a.length()>10) {...}
A. A single ampersand here would lead to a NullPointerException.

109. What's the main difference between a Vector and an ArrayList
A. Java Vector class is internally synchronized and ArrayList is not.

110. When should the method invokeLater()be used?
A. This method is used to ensure that Swing components are updated through the event-dispatching thread.

111. What's the difference between a queue and a stack?
A. Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule

112. You can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. So can you use abstract classes instead of interfaces?
A. Sometimes. But your class may be a descendent of another class and in this case the interface is your only option.

113. How can a subclass call a method or a constructor defined in a superclass?
A. Use the following syntax: super.myMethod(); To call a constructor of the superclass, just write super(); in the first line of the subclass's constructor.

114. What comes to mind when someone mentions a shallow copy in Java?
A. Object cloning.

115. If you're overriding the method equals() of an object, which other method you might also consider?
A. hashCode()

116. How could Java classes direct program messages to the system console, but error messages, say to a file?
A. The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:
Stream st = new Stream(new FileOutputStream("output.txt")); System.setErr(st); System.setOut(st);

117. What's the difference between an interface and an abstract class?
A. An abstract class may contain code in method bodies, which is not allowed in an interface. With abstract classes, you have to inherit your class from it and Java does not allow multiple inheritance. On the other hand, you can implement multiple interfaces in your class.

118. You are planning to do an indexed search in a list of objects. Which of the two Java collections should you use:
ArrayList or LinkedList?
A. ArrayList

119. Why would you use a synchronized block vs. synchronized method?
A. Synchronized blocks place locks for shorter periods than synchronized methods.

120. How would you make a copy of an entire Java object with its state?
A. Have this class implement Cloneable interface and call its method clone().

Also Read:


Post a Comment