Core Java Interview Questions -12

Core Java Interview Questions -12

1.What is a compilation unit?

A compilation unit is a Java source code file.

2. How can a dead thread be restarted?

A dead thread cannot be restarted.

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

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

5. What interface is extended by AWT event listeners?
All AWT event listeners extend the java.util.EventListener interface.

6. Can an abstract class be final?
An abstract class may not be declared as final.

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

8. Which arithmetic operations can result in the throwing of an ArithmeticException?
Integer / and % can result in the throwing of an ArithmeticException.

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

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

11. To what value is a variable of the boolean type automatically initialized?
The default value of the boolean type is false.

12. Can try statements be nested?
Try statements may be tested.

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

14. What is the purpose of a statement block?
A statement block is used to organize a sequence of statements as a single statement group.

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

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

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

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

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

20.what modifiers may be used with a top-level class?

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

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

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

23. What methods are used to get and set the text label displayed by a Button object?getLabel() and setLabel()

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

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

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

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


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

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

30. What happens when you add a double value to a String?
The result is a String object.

31. What is the List interface?
The List interface provides support for ordered collections of objects.

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

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

34.What are pass by reference and passby value?
Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed.

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

36.What is the Java Virtual Machine (JVM)?The Java Virtual Machine is software that can be ported onto various hardware-based platforms.

37.How could Java classes direct program messages to the system console, but error messages, say to a file?
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);

38.How would you create a button with rounded edges?

There’s 2 ways. The first thing is to know that a JButton’s edges are drawn by a Border. so you can override the Button’s paintComponent(Graphics) method and draw a circle or rounded rectangle (whatever), and turn off the border. Or you can create a custom border that draws a circle or rounded rectangle around any component and set the button’s border to it.

39. What’s the difference between constructors and normal methods?
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 and it can return a value or can be void.

40. Question: How you can force the garbage collection?
Garbage collection automatic process and can’t be forced. You could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.
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 can’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.

41.What is Java?
A high-level programming language developed by Sun Microsystems. Java was originally called OAK, and was designed for handheld devices and set-top boxes. Oak was unsuccessful so in 1995 Sun changed the name to Java and modified the language to take advantage of the burgeoning World Wide Web.

42.what are the main features of java?
The main features of java are
Compiled and Interpreted
Object oriented
Robust and secure
Type safe
High Performance.

42.Explain the usage of the keyword transient?

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

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

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

45.Explain the usage of Java packages.
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.

46.Why should the implementation of any Swing callback (like a listener) execute quickly?
Because callbacks are invoked by the event dispatch thread which will be blocked processing other events for as long as your method takes to execute.

47.What’s the difference between the methods sleep() and wait()

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.

48.What are some advantages and disadvantages of Java Sockets?
Some advantages of Java Sockets:
Sockets are flexible and sufficient. Efficient socket based programming can be easily implemented for general communications. Sockets cause low network traffic. Unlike HTML forms and CGI scripts that generate and transfer whole web pages for each new request, Java applets can send only necessary updated information.
Some disadvantages of Java Sockets:
Security restrictions are sometimes overbearing because a Java applet running in a Web browser is only able to establish connections to the machine where it came from, and to nowhere else on the network   Despite all of the useful and helpful Java features, Socket based communications allows only to send packets of raw data between applications. Both the client-side and server-side have to provide mechanisms to make the data useful in any way.

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

50.Which of the following are valid definitions of an application’s main( ) method?

a) public static void main();
b) public static void main( String args );
c) public static void main( String args[] );
d) public static void main( Graphics g );
e) public static boolean main( String args[] );

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

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

53.Why would you use a synchronized block vs. synchronized method?

Synchronized blocks place locks for shorter periods than synchronized methods.

54.What is variables and then types?
Variables is an identifier that denotes a storage location used to store a data values.unlike constants that remain unchanged during the execution of a program, a variable may takes different values at different times during the execution of the program.
Instance variables
Class variables
Local variable

55.what is dot operator?The dot operator(.) is used to access the instance variables and methods of class objects.It is also used to access classes and sub-packages from a package.
Examples :
Person1.age ———> Reference to the variable age

56.Define strings?
Strings represent a sequence of characters.The easiest way to represent a sequence of characters in java is by using a character array.

57.What is serialization?
Serialization is the process of converting a objects into a stream of bytes.

58.What are different types of access modifiers?
Access specifiers are keywords that determine the type of access to the member a class.

59.What is an abstract class?

Abstract class is a class which contain one or more abstract methods, which has to be implemented by sub classes. An abstract class can contain no abstract methods also i.e. abstract class may contain concrete methods.

60.what are class variables
Class variables are global to a class and belong to the entire set of objects that class creates. Only one memory location is created for each variable.

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

62.What must a class do to implement an interface?
The class must provide all of the methods in the interface and identify the interface in its implements clause.

63.What is the Collections API?
the Collections API is a set of classes and interfaces that support operations on collections of objects.

64.What is an array?
Array is a group of related data items that share a common name.For instance, we can define an array name salary to represent a set of salaries of a group of employees.
Examples : salary[10]

65.What is a list iterator?
The List and Set collections provide iterators, which are objects that allow going over all the elements of a collection in sequence. The java.util.Iterator interface provides for one-way traversal and java.util.ListIterator is an iterator for lists that allows the programmer to traverse the list in either direction (i.e. forward and or backward) and modify the list during iteration.

66.What is the main difference between a String and a StringBuffer class?
String is immutable : you can’t modify a string object but can replace it by creating a new instance. Creating a new instance is rather expensive.
StringBuffer is mutable : use StringBuffer or StringBuilder when you want to modify the contents. StringBuilder was added in Java 5 and it is identical in all respects to StringBuffer except that it is not synchronized,which makes it slightly faster at the cost of not being thread-safe.

67.When to use serialization?
A common use of serialization is to use it to send an object over the network or if the state of an object needs to be persisted to a flat file or a database.

68.What is the main difference between shallow cloning and deep cloning of objects?

Java supports shallow cloning of objects by default when a class implements the java.lang.Cloneable interface.
Deep cloning through serialization is faster to develop and easier to maintain but carries a performance overhead.

69.What are wrapper classes?
primitive data types may be converted into object types by using the wrapper classes contained in the java.lang package.
Exampes : int, float, long, char, double

70.What is the difference between an instance variable and a static variable?

Class variables are called static variables. There is only one occurrence of a class variable per JVM per class loader.When a class is loaded the class variables are initialized.
Instance variables are non-static and there is one occurrence of an instance variable in each class instance.Also known as a member variable or a field.

71.Where and how can you use a private constructor?
Private constructor is used if you do not want other classes to instantiate the object and to prevent subclassing.The instantiation is done by a public static method (i.e. a static factory method) within the same class.

72.What is type casting?

Type casting means treating a variable of one type as though it is another type.
Examples :
int m = 5;
byte n =i;

73.What is a user defined exception?
User defined exceptions may be implemented by defining a new exception class by extending the Exception class.

74.What is an instanceof operator?

Instanceof is an object reference operator and returns true if the object on the left-hand side is an instance of the glass given to the right hand side.This operator allows to determine whether the object belongs to a particular class or not.

75.What are runtime exceptions?
Run time exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time.

76.What is the difference between an interface and an abstract class?
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

77.what is a package?
A package is a namespace that organizes a set of related classes and interfaces.The classes contained in the packages of other programs can be easily reused.Packages, classes can be unique compared with classes in other packages.That is, two classes in two different packages can have the same name.

78.What is the base class of all classes?

79.What is the purpose of finalization?

The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.

80.What is the difference between a break statement and a continue statement?

Break statement results in the termination of the statement to which it applies (switch, for, do, or while).
A Continue statement is used to end the current loop iteration and return control to the loop statement.

81.What is Byte Code?
All Java programs are compiled into class files that contain bytecodes. These byte codes can be run in any platform and hence java is said to be platform independent.

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

83.What is the difference between method overriding and overloading?
Overriding is a method with the same name and arguments as in a parent, whereas overloading is the same method name but different arguments.

84.When is a method said to be overloaded and when is a method said to be overridden?

Overloading deals with multiple methods in the same class with the same name but different method signatures.
Overriding deals with two methods, one in the parent class and the other one in the child class and has the same name and signatures.

85.How is final different from finally and finalize()?
Final – constant declaration.
The finally block always executes when the try block exits, except System.exit(0) call.
finalize() is a method of Object class which will be executed by the JVM just before garbage collecting object to give a final chance for resource releasing activity.

86.What is the List interface?

The List interface provides support for ordered collections of objects.

87.What is the difference between an abstract class and an interface?
Abstract class Interface – Have executable methods and abstract methods.Can only subclass one abstract class
Interface – Have no implementation code. All methods are abstract.A class can implement any number of interfaces.

88.What if the main method is declared as private?When a method is declared as private, the program compiles properly but it will give runtime error Main method not “public„.

89.What is the Vector class?

The Vector class provides the capability to implement a growable array of objects.

90.What is singleton?

It is one of the design pattern. This falls in the creational pattern of the design pattern. There will be only one instance for that entire JVM. You can achieve this by having the private constructor in the class.

91.What is the difference between error and an exception?

Exception means When a method encounters an abnormal condition (an exception condition) that it can’t handle itself, it may throw an exception.
ssError mens system doesn’t handle.For example:Overflow,Out of memory.

92.What is the importance of static variable?

static variables are class level variables where all objects of the class refer to the same variable. If one object changes the value then the change gets reflected in all the objects.

93.What is the difference between a while statement and a do while statement?
A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do while statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do whilestatement will always execute the body of a loop at least once.

94.What do you mean by polymorphism?Polymorphism means the ability to take more than one form. fro example, an operation may exhibit behaviour in different instances. The behaviour depends upon the types of data used in the operatiom.

95.What type of parameter passing does Java support?
In Java the arguments are always passed by value.

96.What is the difference between constructors and normal methods?
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 and it can return a value or can be void.

97.What is Locale?
A Locale object represents a specific geographical, political, or cultural region.

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

99.What is the difference between java and c++?
Java is a true object – oriented language while c++ is basically c with object-oriented extension.
C++ supports multiple inheritence but Java provides interfaces in case of multiple inheritence.
Java does not support operator overloading.
Java does not have template classes as in c++.
java does not use pointers.

100.When should the method invokeLater()be used?

This method is used to ensure that Swing components are updated through the event-dispatching thread.

Also Read:




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