Java Interview Questions -22

Java Interview Questions -22

1.How are the elements of a CardLayout organized?

The elements of a CardLayout are stacked, one on top of the other, like a deck of cards.

2.Is &&= a valid Java operator?
No, it is not.

3.Name the eight primitive Java types.

The eight primitive types are byte, char, short, int, long, float, double, and boolean.

4.For which statements does it make sense to use a label?
The only statements for which it makes sense to use a label are those statements that can enclose a break or continue statement.

5.What is the purpose of the System class?
The purpose of the System class is to provide access to system resources.

6.Which TextComponent method is used to set a TextComponent to the read-only state?


7.Is "abc" a primitive value?

The String literal "abc" is not a primitive value. It is a String object.

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

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

10.Which class should you use to obtain design information about an object?

The Class class is used to obtain information about an object's design.

11.What is the relationship between clipping and repainting?

When a window is repainted by the AWT painting thread, it sets the clipping regions to the area of the window that requires repainting.

12.What modifiers may be used with an interface declaration?

An interface may be declared as public or abstract.

13.How can a GUI component handle its own events?

A component can handle its own events by implementing the required event-listener interface and adding itself as its own event listener.

14.What is the difference between a while statement and a do statement?

A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.

15.How are the elements of a GridBagLayout organized?

The elements of a GridBagLayout are organized according to a grid. However, the elements are of different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes.

16.What advantage do Java's layout managers provide over traditional windowing systems?

Java uses layout managers to lay out components in a consistent manner across all windowing platforms. Since Java's layout managers aren't tied to absolute sizing and positioning, they are able to accommodate platform-specific differences among windowing systems.

17.Is a class a subclass of itself?

A class is a subclass of itself.

18.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 class hierarchy.

19.What event results from the clicking of a button?

The ActionEvent event is generated as the result of the clicking of a button.

20.What is the difference between the paint() and repaint() methods?

The paint() method supports painting via a Graphics object. The repaint() method is used to cause paint() to be invoked by the AWT painting thread.

21.What is the purpose of the File class?

The File class is used to create objects that provide access to the files and directories of a local file system.

22.Can an exception be rethrown?

Yes, an exception can be rethrown.

23.Which Math method is used to calculate the absolute value of a number?

The abs() method is used to calculate absolute values.

24.What is the Collection interface?

The Collection interface provides support for the implementation of a mathematical bag - an unordered collection of objects that may contain duplicates.

25.What modifiers can be used with a local inner class?

A local inner class may be final or abstract.

26.What is the difference between static and non-static variables?

A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.

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

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

29.When is the finally clause of a try-catch-finally statement executed?

The finally clause of the try-catch-finally statement is always executed unless the thread of execution terminates or an exception occurs within the execution of the finally clause.

30.Which class is the immediate superclass of the Container class?


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

32.How can the Checkbox class be used to create a radio button?

By associating Checkbox objects with a CheckboxGroup.

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

34.What restrictions are placed on method overloading?

Two methods may not have the same name and argument list but different return types.

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

36.What is the difference between a Choice and a List?

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

37.What class of exceptions are generated by the Java run-time system?

The Java runtime system generates RuntimeException and Error exceptions.

38What is the return type of a program's main() method?

A program's main() method has a void return type.

39.Name four Container classes.

Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane

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

41.What is the relationship between a method's throws clause and the exceptions that can be thrown during the method's execution?

A method's throws clause must declare any checked exceptions that are not caught within the body of the method.

42.What class allows you to read objects directly from a stream?

The ObjectInputStream class supports the reading of objects from input streams.

43.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 local to a method.

44.Under what conditions is an object's finalize() method invoked by the garbage collector?

The garbage collector invokes an object's finalize() method when it detects that the object has become unreachable.

45.What state is a thread in when it is executing?

An executing thread is in the running state.

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

47.What is the difference between the JDK 1.02 event model and the event-delegation model introduced with JDK 1.1?

The JDK 1.02 event model uses an event inheritance or bubbling approach. In this model, components are required to handle their own events. If they do not handle a particular event, the event is inherited by (or bubbled up to) the component's container. The container then either handles the event or it is bubbled up to its container and so on, until the highest-level container has been tried. In the event-delegation model, specific objects are designated as event handlers for GUI components. These objects implement event-listener interfaces. The event-delegation model is more efficient than the event-inheritance model because it eliminates the processing required to support the bubbling of unhandled events.

48.How is it possible for two String objects with identical values not to be equal under the == operator?

The == operator compares two objects to determine if they are the same object in memory. It is possible for two String objects to have the same value, but located indifferent areas of memory.

49.How are the elements of a GridLayout organized?

The elements of a GridBad layout are of equal size and are laid out using the squares of a grid.

50.What an I/O filter?

An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.

51.Why are the methods of the Math class static?

So they can be invoked as if they are a mathematical code library.

52.What Checkbox method allows you to tell if a Checkbox is checked?


53.if an object is garbage collected, can it become reachable again?

Once an object is garbage collected, it ceases to exist. It can no longer become reachable again.

54.What is a void return type?

A void return type indicates that a method does not return a value.

55.What are E and PI?

E is the base of the natural logarithm and PI is mathematical value pi.

56.Are true and false keywords?

The values true and false are not keywords.

57.What happens when you add a double value to a String?

The result is a String object.

58.What is your platform's default character encoding?

If you are running Java on English Windows platforms, it is probably Cp1252. If you are running Java on English Solaris platforms, it is most likely 8859_1..

59.What is the purpose of the enableEvents() method?

The enableEvents() method is used to enable an event for a particular object. Normally, an event is enabled when a listener is added to an object for a particular event. The enableEvents() method is used by objects that handle events by overriding their event-dispatch methods.

60.What is the difference between the File and RandomAccessFile classes?

The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.

61.What interface is extended by AWT event listeners?

All AWT event listeners extend the java.util.EventListener interface.

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

63.How can a dead thread be restarted?

A dead thread cannot be restarted.

64.How are this and super used?

this is used to refer to the current object instance. super is used to refer to the variables and methods of the superclass of the current object instance.

65.What is the purpose of garbage collection?

The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources may be reclaimed and reused.

66.Which package is always imported by default?

The java.lang package is always imported by default.

67.What interface must an object implement before it can be written to a stream as an object?

An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.

68.What is a compilation unit?

A compilation unit is a Java source code file.

69.What happens if an exception is not caught?

An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown.

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

71.To what value is a variable of the boolean type automatically initialized?

The default value of the boolean type is false.

72.Can try statements be nested?

Try statements may be tested.

73.What modifiers may be used with a top-level class?

A top-level class may be public, abstract, or final.

74.Which arithmetic operations can result in the throwing of an ArithmeticException?

Integer / and % can result in the throwing of an ArithmeticException

75.Can an abstract class be final?

An abstract class may not be declared as final.

76.What is the ResourceBundle class?

The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program's appearance to the particular locale in which it is being run.

77.What happens if a try-catch-finally statement does not have a catch clause to handle an exception that is thrown within the body of the try statement?

The exception propagates up to the next higher level try-catch statement (if any) or results in the program's termination.

78.What is numeric promotion?

Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-point operations may take place. In numerical promotion, byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required.

79.What is a layout manager?

A layout manager is an object that is used to organize components in a container.

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

81.What is the purpose of a statement block?

A statement block is used to organize a sequence of statements as a single statement group.

82.What is the difference between a Scrollbar and a ScrollPane?

A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling.

83.What are the Object and Class classes used for?

The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program.

84.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 exception is executed. The remaining catch clauses are ignored.

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

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

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

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

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

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

91.Why isn't there operator overloading?

Because C++ has proven by example that operator overloading makes code almost impossible to maintain. In fact there very nearly wasn't even method overloading in Java, but it was thought that this was too useful for some very basic methods like print(). Note that some of the classes like DataOutputStream have unoverloaded methods like writeInt() and writeByte().

92.What is the difference between notify() and notifyAll()?

notify() is used to unblock one waiting thread; notifyAll() is used to unblock all of them. Using notify() is preferable (for efficiency) when only one blocked thread can benefit from the change (for example, when freeing a buffer back into a pool). notifyAll() is necessary (for correctness) if multiple threads should resume (for example, when releasing a "writer" lock on a file might permit all "readers" to resume).

93.Why are there no global variables in Java?

Global variables are considered bad form for a variety of reasons: · Adding state variables breaks referential transparency (you no longer can understand a statement or expression on its own: you need to understand it in the context of the settings of the global variables).
· State variables lessen the cohesion of a program: you need to know more to understand how something works. A major point of Object-Oriented programming is to break up global state into more easily understood collections of local state.
· When you add one variable, you limit the use of your program to one instance. What you thought was global, someone else might think of as local: they may want to run two copies of your program at once.
For these reasons, Java decided to ban global variables.

94.Why can't I say just abs() or sin() instead of Math.abs() and Math.sin()?

The import statement does not bring methods into your local name space. It lets you abbreviate class names, but not get rid of them altogether. That's just the way it works, you'll get used to it. It's really a lot safer this way.
However, there is actually a little trick you can use in some cases that gets you what you want. If your top-level class doesn't need to inherit from anything else, make it inherit from java.lang.Math. That *does* bring all the methods into your local name space. But you can't use this trick in an applet, because you have to inherit from java.awt.Applet. And actually, you can't use it on java.lang.Math at all, because Math is a "final" class which means it can't be extended.

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

96.Is null a keyword?

The null value is not a keyword.

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

98.What does it mean that a class or member is final?

A final class can no longer be subclassed. Mostly this is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. Methods may be declared final as well. This means they may not be overridden in a subclass.
Fields can be declared final, too. However, this has a completely different meaning. A final field cannot be changed after it's initialized, and it must include an initializer statement where it's declared. For example,
public final double c = 2.998;
It's also possible to make a static field final to get the effect of C++'s const statement or some uses of C's #define, e.g. public static final double c = 2.998;

99.What does it mean that a method or class is abstract?

An abstract class cannot be instantiated. Only its subclasses can be instantiated. You indicate that a class is abstract with the abstract keyword like this:
public abstract class Container extends Component {
Abstract classes may contain abstract methods. A method declared abstract is not actually implemented in the current class. It exists only to be overridden in subclasses. It has no body. For example,
public abstract float price();
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 itself be declared abstract.

100.What is the main difference between Java platform and other platforms?

The Java platform differs from most other platforms in that it's a software-only platform that runs on top of other hardware-based platforms.
The Java platform has three elements:
Java programming language
The Java Virtual Machine (Java VM)
The Java Application Programming Interface (Java API)

101.What is the Java Virtual Machine?

The Java Virtual Machine is a software that can be ported onto various hardware-based platforms.

102.Explain the user defined Exceptions?

User defined Exceptions are the separate Exception classes defined by the user for specific purposed. An user defined can created by simply sub-classing it to the Exception class. This allows custom exceptions to be generated (using throw) and caught in the same way as normal exceptions.
class myCustomException extends Exception {
// The class simply has to exist to be an exception

103.Is Java code slower than native code?

Not really. As a platform-independent environment, the Java platform can be a bit slower than native code. However, smart compilers, well-tuned interpreters, and just-in-time bytecode compilers can bring performance close to that of native code without threatening portability.

104.Can main() method be overloaded?

Yes. the main() method is a special method for a program entry. You can overload main() method in any ways. But if you change the signature of the main method, the entry point for the program will be gone.

105.What is the serialization?

The serialization is a kind of mechanism that makes a class or a bean persistence by having its properties or fields and state information saved and restored to and from storage.

106.What is the Java API?

The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets.

107.What is the package?

The package is a Java namespace or part of Java libraries. The Java API is grouped into libraries of related classes and interfaces; these libraries are known as packages.

108.What is native code?

The native code is code that after you compile it, the compiled code runs on a specific hardware platform.

109.Explain the new Features of JDBC 2.0 Core API?

The JDBC 2.0 API includes the complete JDBC API, which includes both core and Optional Package API, and provides inductrial-strength database computing capabilities.
New Features in JDBC 2.0 Core API:

110.Scrollable result sets- using new methods in the ResultSet interface allows programmatically move the to particular row or to a position relative to its current position

JDBC 2.0 Core API provides the Batch Updates functionality to the java applications.
Java applications can now use the ResultSet.updateXXX methods.
New data types - interfaces mapping the SQL3 data types
Custom mapping of user-defined types (UTDs)
Miscellaneous features, including performance hints, the use of character streams, full precision for java.math.BigDecimal values, additional security, and support for time zones in date, time, and timestamp values.

111.How you can force the garbage collection?

Garbage collection automatic process and can't be forced.

112.Explain garbage collection?

Garbage collection is one of the most important feature of Java. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. User program cann't directly free the object from memory, instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use. I Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected.

113.Describe the principles of OOPS.

There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation.

114.Explain the Encapsulation principle.

Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper.

115.Explain the Inheritance principle.

Inheritance is the process by which one object acquires the properties of another object.

116.Explain the Polymorphism principle.

The meaning of Polymorphism is something like one name many forms. Polymorphism enables one entity to be used as as general category for different types of actions. The specific action is determined by the exact nature of the situation. The concept of polymorphism can be explained as "one interface, multiple methods".

117.Explain the different forms of Polymorphism.

From a practical programming viewpoint, polymorphism exists in three distinct forms in Java:
Method overloading
Method overriding through inheritance
Method overriding through the Java interface

118.What are Access Specifiers available in Java?

ccess specifiers are keywords that determines the type of access to the member of a class. These are:


Post a Comment