Java Interview Questions -13

Core Java Interview Questions -13

1.Explain the user defined Exceptions.

User Defined Exceptions are exceptions defined by the user for specific purposed. This allows custom exceptions to be generated and caught in the same way as normal exceptions. While defining a User Defined Exception, we need to take care of the following aspects:
It should be extend from Exception class.
Use toString() method to display information about the exception.

2.How are this() and super() used with constructors?

this() Constructors: is used to pointing the current class instance.
Can be used with variables or methods.
Used to call constructer of same class.
Private variable cannot be accessed using this().
super() Constructer: is used to call constructor of parent class.
Must be the first statement in the body of constructor.
Using this we can access private variables in the super class.

3.What are Access Specifiers available in Java?

Java offers four access specifiers, described below:
Public: public classes, methods, and fields can be accessed by every class.
Protected: protected methods and fields can only be accessed within the same class to which the methods and fields belong.
Default (no specifier): when we do not set access to specific level, then such a class, method, or field will be accessible from inside the same package to which the class, method, or field belongs.
Private: private methods and fields can only be accessed within the same class to which the methods and fields belong. Private methods and fields are not inherited by subclasses.

4.What is Polymorphism?

The Polymorphism can be referred as one name many forms. It is the ability of methods to behave differently, depending upon the object who is calling it. The key features of Polymorphism are:
Allows using one interface for multiple implementations.
Supports Method Overloading: Multiple methods with same name, but different formal argument.
Supports Method Overridden: Multiple methods have the same name, same return type, and same formal argument list.

5.Explain garbage collection.

The Java uses the garbage collection to free the memory. By cleaning those objects that is no longer reference by any of the program. Step involve in cleaning up the garbage collection:
Garbage Object Collection: first step is to collection and group all those object which are no more reference with any of the program. We can use the different methods to collect the garbage object like using runtime.gc() or system.gc().
Run Finalize method: To free up those object which is collected by the garbage collector java must execute the Finalize method to delete all those dynamically created object

6.What is an immutable object?

An immutable object is one that we cannot change once it is created. Steps involved in creation of an immutable object are:
Make all of its data fields private.
Methods which can perform changes in any of the data fields after the construction of object must be avoided.

7.What is Constructor?
A constructor is used to initialize a newly created object.
It is called just after the memory is allocated for the object.
It can be used to initialize the objects.
It is not mandatory to write a constructor for the class.
Name of constructor is same as the class name.
Cannot be inherited.
Constructor is invoked whenever an object of its associated class is created.

8.What are the List interface and its main implementation?
The List helps in collections of objects. Lists may contain duplicate elements. The main implementations of the List interface are as follows:
ArrayList: Resizable-array implementation of the List interface.
Vector: Synchronized resizable-array implementation of the List.
LinkedList: Doubly-linked list implementation of the List interface. Better performance than the ArrayList implementation when elements are inserted or deleted timely.

9.Describe life cycle of thread.

Threads follow the single flow of control. A thread is execution in a program. The life cycles of threads are listed below:
Newborn state: After the creations of Thread instance the thread is in this state but before the start() method invocation. Thread is considered not alive in this phase.
Runnable state: A thread starts its life from Runnable state. After the invoking of start() method thread enters Runnable state.
Running state: A thread first enters Runnable state.
Blocked state: A thread can enter in this state because of waiting the resources that are hold by another thread.
Dead state: A thread can be considered dead when its run() method completes. If any thread comes on this state that means it cannot ever run again.

10.What is a HashSet and TreeSet?

The HashSet is an unsorted, unordered Set.
It is Collection set that restrict duplicate elements and also repositioning of elements.
It implements the Set interface and extends AbstractSet.
Uses hash code of the object being inserted.
The TreeSet is a Set implemented when we want elements in a sorted order.
Sorting of element is done according to the natural order of elements or by the help of comparator provided at creation time.

11.How do you decide when to use HashMap and when to use TreeMap and what is difference between these two?

HashMap is used when we want to perform insertion, deletion, and locate elements in a Map.
TreeMap is used when we want to traverse the elements in a sorted order. Depending upon the size of collection, adding elements to HashMap is easy. For sorted elements traversal we can convert the HashMAp into TreeMap.
Lets us to have null values and also one null key
Iterator in the HashMap is Fail-Safe.
It is Unsynchronized.
It does not allow null value as key and value.
It is not synchronized.

12.What is an Applets?

Applets: These are small java programs.
They can send from one computer to another computer over the internet using the Applet Viewer that supports java.
Applets can runs in a Web browser as it is a java program. It can be a fully functional Java application because it has the entire Java API at its disposal.
Applets follow the security rules given by the Web browser.
Applet security is also known as sandbox security.

13.What is the Set interface?

A Set interface is collection of element which cannot be duplicated.
The Set interface contains methods inherited from collection.
It provides methods to access the elements of a finite mathematical set.
Two Set objects are equal if they contain the same elements.
It models the mathematical set abstraction.

14.Explain the Polymorphism principle.

The Polymorphism can be referred as one name many forms. It is the ability of methods to behave differently, depending upon the object who is calling it. Polymorphism exists in three distinct forms in Java:
Method overloading
Method overriding through inheritance
Method overriding through the Java interface

15.What are the difference between throw and throws?

The differences are between throw and throws are:
Throw is used to trigger an exception where as throws is used in declaration of exception.
Without throws, Checked exception cannot be handled where as checked exception can be propagated with throws.
Throw is used inside the method where as throws is used with the method signature.
Throw is followed by an instance but throws is followed by class.

16.What is the Comparable interface?

The Comparable interface is used to sort collections and arrays of objects using the collections.sort() and java.utils. The objects of the class implementing the Comparable interface can be ordered. All classes implementing the Comparable interface must implement the compareTo() method that has the return type as an integer. The signature of the compareTo() method is as follows:
int i = object1.compareTo(object2)
If object1 < object2: The value of i returned will be negative.
If object1 > object2: The value of i returned will be positive.
If object1 = object2: The value of i returned will be zero.

17.When should I use abstract classes and when should I use interfaces?

Use Interface, when:
Design changing frequently or when various implementations only share method signatures.
We need some classes to use some methods which we do not want to be included in the class.
Use Abstract Class, when:
Various implementations are of the same kind and use common behavior.
Enabling with generalized form of abstraction and leave the implementation task with the inheriting subclass.
creating planned inheritance hierarchies

18.How java becomes robust?

• Java provides multi-platformed environment.
• Java provides high reliability in the design.
• Java is a strictly typed language.
• Java checks the code at runtime.
• Java provides predictablity.
• java provides various keywords.

19.How a Java program compiles?

• First the source file name must be extended with .java extension. e.g.
• Execute the javac compiler.
• javac compiler creates a file called Myprog.class i.e. the bytecode version of
• The butecode is executed by the Java runtime-systems which is called Java Virtual Machine (JVM).
• JVM is platform dependent.

20.What is difference between preemptive scheduling and time slicing?

Differences between preemptive and time scheduling are:
In Preemptive scheduling the highest priority task executes until it enters the waiting or dead stated or a higher priority task comes into existence.
Time slicing, a task executes for a predefined time period and then the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factor.

21.Explain traversing through a collector using Iterator.

We can access each element in the Collection by using Iterators irrespective of how they are organized in the collector. Iterator can be implemented a different way for every Collection. To use an iterator to traverse through the contents of a collection we do:
Obtain an iterator by calling the collections iterator()method to the start of the collection.
Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext()returns true.
Within the loop, obtain each element by calling next().
remove() method is used to remove the current element in the iteration.

22.What are the principle concepts of OOPS?

There are four principle concepts upon which object oriented design and programming rest. They are:
Abstraction: Abstraction refers to the act of representing essential features without including the background details or explanations.
Polymorphism: is the ability to create a variable, a function, or an object that has more than one form.
Inheritance: Inheritance is the process by which objects of one class acquire the properties of objects of another class.
Encapsulation: Encapsulation is a technique used for hiding the properties and behaviors of an object and allowing outside access only as appropriate. It prevents other objects from directly altering or accessing the properties or methods of the encapsulated object.

23.What is JVM?

• JVM is the acronym stands for ‘Java virtual machine’.
• JVM provides the execution environment.
• JVM is not platform independent..
• JVM is the Java run-time system.
• JVM is an interpreter of bytecode.
• JVM also makes the sytem secured.

24.What is Java applet?

• Applet is a java program.
• It has been designed for transmitting the Java code over the internet.
• It is automatically executed by Java-enabled Web Browser.
• Applet can repnse to the user input.
• Applet is dynamically programmed.

25.What are the basic features of java?

The basic features of Java are given below :
• Java is simple.
• Java provides immense security.
• Java provides high portability.
• Java provides object oriented programming features
• Java provides robustness.
• Java is multuthreaded.
• Java provides architecture neutrality.
• Java is distributed
• Java is dynamic.

26.What is bytecode?

• Bytecode is an instruction set.
• Bytecode extends wiith .class.
• ‘javac’ compiler translates the .java file into .class.
• JVM interpretes bytecode.
• Bytecode facility makes Java platform-independent.
• It also confirms security tothe Java code.

27.How java becomes object oriented?

• Java follows the paradigm of OO programming.
• Java follows modular approach.
• Java follows the abstraction aspect.
• Java follows the OO principle encapsultaion.
• Java follows the OO principle polymorphism.
• Java follows the OO principle inheritance.

28.What is ‘public static void main ( String args[ ] ) ‘ signifies?

• the access specifier is the ‘public’ keyword .
• ‘static’ keyword allows main() to be called without instantiating a particular instance of a class.
• ‘void’ affirns the compiler that no value is returned by main().
• ‘main()’ mathod is called at the beginning of a Java program.
• ‘String args()’ tells a parameter named args,which is an instance array of class String

29.What ‘System.out.println()’ signifies?

• ‘System’ is a predefined class .
• System class givesacces to the system.
• ‘out’ is the output stream.
• ‘println’ is printing the line on the console.
• This is a console output statement.

30.What is a variable in Java program?

• It’s a memory location.
• The memory location is given some name.
• The memory location is being assigned some value.
• The value may change of the variable.
• The memory location size changes with the type of the variable.

31.Describe the principles of OOPS.

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

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

33. How does substring () inside String works?

Another good Java interview question, I think answer is not sufficient but here it is “Substring creates new object out of source string by taking a portion of original string”. see my post How SubString works in Java for detailed answer of this Java question.

34. Which two method you need to implement for key Object in HashMap ?

In order to use any object as Key in HashMap, it must implements equals and hashcode method in Java. Read How HashMap works in Java for detailed explanation on how equals and hashcode method is used to put and get object from HashMap. You can also see my post 5 tips to correctly override equals in Java to learn more about equals.

35. Does all property of immutable object needs to be final?

Not necessary as stated above you can achieve same functionality by making member as non final but private and not modifying them except in constructor.

36. How do you handle error condition while writing stored procedure or accessing stored procedure from java?

This is one of the tough Java interview question and its open for all, my friend didn’t know the answer so he didn’t mind telling me. my take is that stored procedure should return error code if some operation fails but if stored procedure itself fail than catching SQLException is only choice.

37. What is difference between Executor.submit() and Executer.execute() method ?

This Java interview question is from my list of Top 15 Java multi-threading question answers, Its getting popular day by day because of huge demand of Java developer with good concurrency skill. Answer of this Java interview question is that former returns an object of Future which can be used to find result from worker thread)

38. What is the difference between creating String as new() and literal?

When we create string with new() Operator, it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in PermGen area of heap.
String s = new String(“Test”);
does not  put the object in String pool , we need to call String.intern() method which is used to put  them into String pool explicitly. its only when you create String object as String literal e.g. String s = “Test” Java automatically put that into String pool.

39. Where does these  two method comes in picture during get operation?

This core Java interview question is follow-up of previous Java question and candidate should know that once you mention hashCode, people are most likely ask How its used in HashMap. See How HashMap works in Java for detailed explanation.

40. What is the difference when String is gets created using literal or new() operator ?

When we create string with new() its created in heap and not added into string pool while String created using literal are created in String pool itself which exists in Perm area of heap.

41. Does not overriding hashcode() method has any performance implication ?

This is a good question and open to all , as per my knowledge a poor hashcode function will result in frequent collision in HashMap which eventually increase time for adding an object into Hash Map.

42.When do you override hashcode and equals() ?

Whenever necessary especially if you want to do equality check or want to use your object as key in HashMap. check this for writing equals method correctly 5 tips on equals in Java

43. What will be the problem if you don’t override hashcode() method ?

You will not be able to recover your object from hash Map if that is used as key in HashMap.
See here  How HashMap works in Java for detailed explanation.

44. What is Singleton? is it better to make whole method synchronized or only critical section synchronized ?

Singleton in Java is a class with just one instance in whole Java application, for example java.lang.Runtime is a Singleton class. Creating Singleton was tricky prior Java 4 but once Java 5 introduced Enum its very easy. see my article How to create thread-safe Singleton in Java for more details on writing Singleton using enum and double checked locking which is purpose of this Java interview question.

45. Can you write critical section code for singleton?

This core Java question is followup of previous question and expecting candidate to write Java singleton using double checked locking. Remember to use volatile variable to make Singleton thread-safe. check 10 Interview questions on Singleton Pattern in Java for more details and questions answers

46. Is it better to synchronize critical section of getInstance() method or whole getInstance() method ?

critical section because if we lock whole method than every time some one call this method will have to wait even though we are not creating any object)

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

48. What are the two basic ways in which classes that can be run as threads may be defined?

A thread class may be declared as a subclass of Thread, or it may implement the Runnable interface.

49. Can you write code for iterating over hashmap in Java 4 and Java 5 ?
Tricky one but he managed to write using while and for loop.

50. Give a simplest way to find out the time a method takes for execution without using any profiling tool?

Read the system time just before the method is invoked and immediately after method returns. Take the time difference, which will give you the time taken by a method for execution.

51.Name the containers which uses Border Layout as their default layout?

Containers which uses Border Layout as their default are: window, Frame and Dialog classes.

52. What do you understand by Synchronization?

Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object’s value. Synchronization prevents such type of data corruption.

53.How to define an Abstract class?

A class containing abstract method is called Abstract class. An Abstract class can’t be instantiated.
Example of Abstract class:
abstract class testAbstractClass {
protected String myString;
public String getMyString() {
return myString;
public abstract string anyAbstractFunction();

54.How to define an Interface?

In Java Interface defines the methods but does not implement them. Interface can include constants. A class that implements the interfaces is bound to implement all the methods defined in Interface.
Emaple of Interface:

public interface sampleInterface {
public void functionOne();

public long CONSTANT_ONE = 1000;

55. 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
56. What is Collection API?

The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.

57.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:
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.

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

59. How you can force the garbage collection?

Garbage collection automatic process and can’t be forced.

60.What is OOPS?

OOP is the common abbreviation for Object-Oriented Programming.

61.Is Iterator a Class or Interface? What is its use?

Iterator is an interface which is used to step through the elements of a Collection.

62.What is similarities/difference between an Abstract class and Interface?

Differences are as follows:
Interfaces provide a form of multiple inheritance. A class can extend only one other class.
Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.
A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.
Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast.

63. Explain the Inheritance principle.

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

64.Describe the wrapper classes in Java.

Wrapper class is wrapper around a primitive data type. An instance of a wrapper class contains, or wraps, a primitive value of the corresponding type.
Following table lists the primitive types and the corresponding wrapper classes:

Primitive    Wrapper
boolean      java.lang.Boolean
byte      java.lang.Byte
char      java.lang.Character
double      java.lang.Double
float      java.lang.Float
int      java.lang.Integer
long      java.lang.Long
short      java.lang.Short
void      java.lang.Void

65.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”.

66. Read the following program:

public class test {
public static void main(String [] args) {
int x = 3;
int y = 1;
if (x = y)
System.out.println(“Not equal”);

67.what is the class variables ?

When we create a number of objects of the same class, then each object will share a common copy of variables. That means that there is only one copy per class, no matter how many objects are created from it. Class variables or static variables are declared with the static keyword in a class, but mind it that it should be declared outside outside a class. These variables are stored in static memory. Class variables are mostly used for constants, variable that never change its initial value. Static variables are always called by the class name. This variable is created when the program starts i.e. it is created before the instance is created of class by using new operator and gets destroyed when the programs stops. The scope of the class variable is same a instance variable. The class variable can be defined anywhere at class level with the keyword static. It initial value is same as instance variable. When the class variable is defined as int then it’s initial value is by default zero, when declared boolean its default value is false and null for object references. Class variables are associated with the class, rather than with any object.

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

69.What are Access Specifiers available in Java?

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

70. What is the difference between the instanceof and getclass, these two are same or not ?

instanceof is a operator, not a function while getClass is a method of java.lang.Object class. Consider a condition where we use
if(o.getClass().getName().equals(“java.lang.Math”)){ }
This method only checks if the classname we have passed is equal to java.lang.Math. The class java.lang.Math is loaded by the bootstrap ClassLoader. This class is an abstract class.This class loader is responsible for loading classes. Every Class object contains a reference to the ClassLoader that defines. getClass() method returns the runtime class of an object. It fetches the java instance of the given fully qualified type name. The code we have written is not necessary, because we should not compare getClass.getName(). The reason behind it is that if the two different class loaders load the same class but for the JVM, it will consider both classes as different classes so, we can’t compare their names. It can only gives the implementing class but can’t compare a interface, but instanceof operator can.
The instanceof operator compares an object to a specified type. We can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface. We should try to use instanceof operator in place of getClass() method. Remember instanceof opeator and getClass are not same. Try this example, it will help you to better understand the difference between the two.
Interface one{

Class Two implements one {
Class Three implements one {

public class Test {
public static void main(String args[]) {
one test1 = new Two();
one test2 = new Three();
System.out.println(test1 instanceof one); //true
System.out.println(test2 instanceof one); //true
System.out.println(Test.getClass().equals(test2.getClass())); //false

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

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

The result is a String object.

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

75. What is a compilation unit?

A compilation unit is a Java source code file.

76. What interface is extended by AWT event listeners?

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

77. 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 thrownby the overridden method.

78. How can a dead thread be restarted?

A dead thread cannot be restarted.

79. Which package is always imported by default?

The java.lang package is always imported by default.

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

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

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

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

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

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

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

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

87. What is a layout manager?

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

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

89. Can an abstract class be final?

An abstract class may not be declared as final.

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

The default value of the boolean type is false.

91. Can try statements be nested?

Try statements may be tested.

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

93. What is the purpose of a statement block?

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

94. What is the difference between a public and a nonpublic class?

A public class may be accessed outside of its package. A non-public class may not be accessed outside of its package.

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

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

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

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

98. What methods are used to get and set the text label displayed by a Button object?

getLabel() and setLabel()

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

100. What are the problems faced by Java programmers who don’t use layout managers?

Without layout managers, Java programmers are faced with determining how their GUI will be displayed across multiple windowing systems and finding a common sizing and positioning that will work within the constraints imposed by each windowing system.

101. When is an object subject to garbage collection?

An object is subject to garbage collection when it becomes unreachable to the program in which it is used.

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

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

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

The result is a String object.

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

106. Which Component subclass is used for drawing and painting?


107. What is the List interface?

the List interface provides support for ordered collections of objects.

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



This site uses Akismet to reduce spam. Learn how your comment data is processed.