Core Java Interview Questions -5

Core Java Interview Questions -5

1. Strings are immutable. But String s=”Hello”; String s1=s+”World” returns HelloWorld how?

Here actually a new object is created with the value of HelloWorl

2. What is method overloading?
Method overloading is the process of creating a new method with the same name and different signature.

3. What is internationalization?
Internationalization is the process of designing an application so that it can be adapted to various languages and regions without changes.

4. What is multi-threading?
Multi-threading is the scenario where more than one threads are running.

5.What is deadlock?
Deadlock is a situation when two threads are waiting on each other to release a resource. Each thread waiting for a resource which is held by the other waiting thread.

6.What is java byte code?
Byte code is an sort of intermediate code. The byte code is processed by virtual machine.

7.What are the two important TCP Socket classes?

S
erverSocket and Socket. ServerSocket is useful for two-way socket communication. Socket class help us to read and write through the sockets. getInputStream() and getOutputStream() are the two methods available in Socket class.

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

9.What is method overriding?
Method overriding is the process of giving a new definition for an existing method in its child class.

10.What is finalize() ?
Finalize is a protected method in java. When the garbage collector is executes , it will first call finalize( ), and on the next garbage-collection it reclaim the objects memory. So finalize( ), gives you the chance to perform some cleanup operation at the time of garbage collection.

11.What is classpath?
Classpath is the path where Java looks for loading class at run time and compile time.

12.What is the difference between URL and URLConnection?
A URL represents the location of a resource, and a URLConnection represents a link for accessing or communicating with the resource at the location.

13.What is anonymous class ?
An anonymous class is a type of inner class that don’t have any name.

14.What is the difference between Iterator and Enumeration?
Iterator differ from enumeration in two ways Iterator allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics. And , method names have been improved.

15.What is path?
It is an the location where the OS will look for finding out the executable files and commands.

16.What is finalize() ?
Finalize is a protected method in java. When the garbage collector is executes , it will first call finalize( ), and on the next garbage-collection it reclaim the objects memory. So finalize( ), gives you the chance to perform some cleanup operation at the time of garbage collection.

17.What is path?
It is an the location where the OS will look for finding out the executable files and commands.

18.What is internationalization?
Internationalization is the process of designing an application so that it can be adapted to various languages and regions without changes.

19.What is multi-threading?
Multi-threading is the scenario where more than one threads are running.

20.Can we compile a java program without main?
Yes, we can. In order to compile a java program, we don’t require any main method. But to execute a java program we must have a main in it (unless it is an applet or servlet). Because main is the starting point of a java program.

21.What are the two important TCP Socket classes?
ServerSocket and Socket. ServerSocket is useful for two-way socket communication. Socket class help us to read and write through the sockets. getInputStream() and getOutputStream() are the two methods available in Socket class.

22.What is deadlock?
Deadlock is a situation when two threads are waiting on each other to release a resource. Each thread waiting for a resource which is held by the other waiting thread.

23.What is anonymous class ?


An anonymous class is a type of inner class that don’t have any name.

24.What is the difference between URL and URLConnection?
A URL represents the location of a resource, and a URLConnection represents a link for accessing or communicating with the resource at the location.

25.Strings are immutable. But String s=”Hello”; String s1=s+”World” returns HelloWorld how ?

Here actually a new object is created with the value of HelloWorld

26.What is the difference between Iterator and Enumeration?
Iterator differ from enumeration in two ways Iterator allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics. And , method names have been improved.

27.What is classpath?
Classpath is the path where Java looks for loading class at run time and compile time.

28.What are the restrictions when overriding a method ?
Overridden methods must have the same name, argument list, and return type (i.e., they must have the exact signature of the method we are going to override, including return type.) The overriding method cannot be less visible than the method it overrides( i.e., a public method cannot be override to private). The overriding method may not throw any exceptions that may not be thrown by the overridden method

29.What are the different ways in which a thread can enter into waiting state?
There are three ways for a thread to enter into 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.

30.What is the Locale class?

A Locale object represents a specific geographical, political, or cultural region

31.What is java collections?
Java collections is a set of classes, that allows operations on a collection of classes.

32.What are the the different ways for creating a thread?
A thread can be created by sub classing Thread, or by implementing the Runnable interface.

33.How parameters are passed to methods in java program ?
All java method parameters in java are passed by value only. Obviously primitives are passed by value. In case of objects a copy of the reference is passed and so all the changes made in the method will persist.

34.What is a java compilation unit.
A compilation unit is a java source file.

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

36. If a class doesn’t have any constructors, what will happen?
If a class doesn’t have a constructor, the JVM will provide a default constructor for the class.

37.What is static initializer block? What is its use?
A static initializer block is a block of code that declares with the static keyword. It normally contains the block of code that must execute at the time of class loading. The static initializer block will execute only once at the time of loading the class only.

38.How does multithreading occurring on a computer with a single CPU?
The task scheduler of OS allocates an execution time for multiple tasks. By switching between different executing tasks, it creates the impression that tasks execute sequentially. But actually there is only one task is executed at a time.

39.What will happen if a thread cannot acquire a lock on an object?
It enters to the waiting state until lock becomes available.

40.What will happen if you are invoking a thread’s interrupt method while the thread is waiting or sleeping?
When the task enters to the running state, it will throw an InterruptedException.

41.What is the difference between creating a thread by extending Thread class and by implementing Runnable interface? Which one should prefer?
When creating a thread by extending the Thread class, it is not mandatory to override the run method (If we are not overriding the run method , it is useless), because Thread class have already given a default implementation for run method. But if we are implementing Runnable , it is mandatory to override the run method. The preferred way to create a thread is by implementing Runnable interface, because it give loose coupling.

42.What is coupling?
Coupling is the dependency between different components of a system

43. What are the differences between JIT and HotSpot?
The Hotspot VM is a collection of techniques, the most important of which is called adaptive optimization. The original JVMs interpreted byte codes one at a time. Second-generation JVMs added a JIT compiler, which compiles each method to native code upon first execution, then executes the native code. Thereafter, whenever the method is called, the native code is executed. The adaptive optimization technique used by Hotspot is a hybrid approach, one that combines byte code interpretation and run-time compilation to native code. Hotspot, unlike a regular JIT compiling VM, doesn’t do “premature optimization”

44. Why ArrayList is faster than Vector?
Because Vector is synchronized. Synchronization reduces the performance.

45. What is phantom memory?
Phantom memory is the memory that does not exist in reality.

46. What is the difference between Comparable and Comparator ?
The Comparable is for natural ordering and Comparator is for custom ordering. But we can override the compareTo method of comparable interface to give a custom ordering.

47. What are the advantages and disadvantages of reference counting in garbage collection?
An advantage of this scheme is that it can run in small chunks of time closely linked with the execution of the program. These characteristic makes it particularly suitable for real-time environments where the program can’t be interrupted for very long time. A disadvantage of reference counting is that it does not detect cycles. A cycle is two or more objects that refer to one another. Another disadvantage is the overhead of incrementing and decrement the reference count each time. Because of these disadvantages, reference counting currently is out of favor.

48. What is the security mechanism used in java?
Java uses sand box security model.

49. What is reflection?
Reflection is the process of finding out the different features of a class dynamically.

50. Why Java is not 100% pure object oriented language?
Because java uses primitives.

51. What is meant by Open Source ?
In general, open source refers to any program whose source code is made available for use or modification as users or other developers see fit. Open source software is usually developed as a public collaboration and made freely available.

52. What is the difference between throw and throws clause?
throw is used to throw an exception manually, where as throws is used in the case of checked exceptions, to tell the compiler that we haven’t handled the exception, so that the exception will be handled by the calling function.

53. What is sandbox?
A sandbox is a security mechanism for safely running programs. The sandbox typically provides a tightly-controlled set of resources for guest programs to run in, such as scratch space on disk and memory.

54. What is the difference between List, Set and Map?
A Set is a collection that has no duplicate elements. A List is a collection that has an order associated with its elements. A map is a way of storing key/value pairs. The way of storing a Map is similar to two-column table.

55. What is a classloader?
A class loader is an object that is responsible for loading classes.

56. What is JAR file?
A JAR file (short for Java Archive) is a ZIP file used to distribute a set of Java classes. It is used to store compiled Java classes and associated meta data that can constitute a program

57. What is the difference between Exception and Error ?

Error is unrecoverable.

58. How would you implement a thread pool?
The ThreadPool class is a generic implementation of a thread pool, which takes the following input Size of the pool to be constructed and name of the class which implements Runnable (which has a visible default constructor) and constructs a thread pool with active threads that are waiting for activation. once the threads have finished processing they come back and wait once again in the pool.

59. How do you send data from an applet to Servlet ? What are the steps involved in it ?

You can use the java.net.URLConnection and java.net.URL classes to open a standard HTTP connection to the web server. The server then passes this information to the servlet in the normal way.

Basically, the applet pretends to be a web browser, and the servlet doesn’t know the difference. As far as the servlet is concerned, the applet is just another HTTP client.

60. How will you invoke any external process in Java?
By using Runtime.getRuntime().exec(….)

61. What is Member classes?

A class declared inside a class without static modifier is called member class. Member classes are just like any other member methods or member variables.

62. What is composition?
Holding the reference of the other class within some other class is known as composition

63. What is a class, member and local variable?
Variables declared within a method are local variables. Variables declared within the class are member variables. Variables declared within the class with static modifier are class variables

64. What is the use of assert keyword
Assert keyword validates certain expressions. It replaces the if block effectively and throws an AssertionError on failure. The assert keyword should be used only for critical arguments (means without that the method does nothing).

65. How do I convert a numeric IP address like 66.29.36.130 into a hostname like www.javacertificate.net
String hostname = InetAddress.getByName("66.29.36.130").getHostName();

66. What is Local inner classes ?
Local inner classes are class declared inside a block of code. They are visible only within the block of their declaration.

67. What is the difference between a constructor and a method?
A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator. We cannot invoke a constructor directly. A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.

68. What is polymorphism?
It is the ability of an object to behave differently on different situations for the same message.

69. Can a top level class be private or protected?
No. A top level class can not be private or protected. It can have either “public” or no modifier.

70. What is Nested top-level classes?
A class declared within a class with static modifier is called nested top level class. Any class outside the declaring class can access the nested top level class with the declaring class dot nested top level class. Top-level inner classes have access to static variables only .

71. What are the different inner classes types?
There are mainly four types available. They are Member classes, Nested top-level classes, Local classes, Anonymous classes

71. What is a package?
To group set of classes into a single unit is known as packaging. Packages provides wide name space visibility.

72. If aaaa is an array then why aaaa.length why not aaaa.length()?
Because length is a property not a method.

73. What are the different methods available in Object?
clone, equals, wait, finalize, getClass, hashCode, notify, notifyAll, toString

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

75. Does the code in finally block get executed if there is an exception and a return statement in a catch block?
If an exception occurs and there is a return statement in catch block, the finally block is still executed. The finally block will not be executed when the System.exit(1) statement is executed earlier or the system shut down earlier or the memory is used up earlier before the thread goes to finally block.

76. What is the difference between static synchronized and synchronized methods?

Both are synchronized methods. One is instance method, the other is class method. Method with static modifier is a class method. That means the method belongs to class itself and can be accessed directly with class name and is also called Singleton design. The method without static modifier is an instance method. That means the instance method belongs to its object. Every instance of the class gets its own copy of its instance method.

77. What is the relationship between synchronized and volatile keyword?
The JVM is guaranteed to treat reads and writes of data of 32 bits or less as atomic. For long or double variable, programmers should take care in multi-threading environment. Either put these variables in a synchronized method or block, or declare them volatile.

78. What is aggregation?
It is a special type of composition. If you expose all the methods of a composite class and route the method call to the composite method through its reference, then it is called aggregation

79. What is HashMap and Map?

Map is Interface and HashMap is class that implements that.

80. What is the purpose of the Runtime class?
The purpose of the Runtime class is to provide access to the Java runtime system.

81. What is dynamic typing?
Dynamic typing means type errors are detected at run time by checking the actual data types of the values against the required data types

82. What are the drawbacks of inheritance?
Since inheritance inherits everything from the super class and interface, it may make the subclass too clustering and sometimes error-prone when dynamic overriding or dynamic overloading in some situation. In addition, the inheritance may make peers hardly understand your code if they don’t know how your super-class acts.

83. What factors are used to decide using synchronized or volatile?
You can make a variable synchronized or volatile under the following cases: 1) if you are not updating many variables often in a multithread environment, consider using volatile. 2) If you are updating many variables, consider using synchronized, because using volatile might be slower.

84. Considering notepad/IE or any other thing as process, What will happen if you start notepad or IE 3 times? Where 3 processes are started or 3 threads are started ?

3 processes will start.

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

86. What is static typing?

Static typing means type errors are detected at compile time by checking the inferred data type is a subtype of the required type

87. What are the restrictions placed on the values of each case of a switch statement?
At compile time, each case values of switch statement must evaluate to a an int value.

88. What is adapter class?
An adapter class provides a default implementation of all methods in an event listener interface. Adapter classes are useful when you want to process only some of the events that are handled by a particular event listener interface. You can define a new class by extending one of the adapter classes and implementing only those events relevant to us.

89. What is serialVersionUID ?
The serialVersionUID is a universal version identifier for a Serializable class. Deserialization uses this identifier number to ensure that a loaded class corresponds to a serialized object.

90. What is Inter-Thread communication?.
Exchange of information between two threads.

91. What is a thread group?
A thread group is a data structure that controls the state of collection of thread as a whole managed by the particular runtime environment.

92. What is abstraction?
An abstraction is an idea, concept, or word which defines the phenomena which make up the concrete events or things which the abstraction refers to, the referents.

93. How can I get the serialVersionUID of a class?
By running the serialver tool with the name of the class as the command line argument, as shown in the example that follows: serialver java.lang.String

94. What is a stream and what are the types of Streams and classes of the Streams?
A stream is a flow of data from one direction to another. . There are two types of Streams Byte Streams: Provide a convenient means for handling input and output of bytes. And Character Streams: Provide a convenient means for handling input & output of characters.

95. Why is OutOfMemoryError thrown after writing a large number of objects into an ObjectOutputStream?

The ObjectOutputStream maintains a table mapping objects written into the stream to a handle. The first time an object is written to a stream, its contents are written into the stream; subsequent writes of the object result in a handle to the object being written into the stream. This table maintains references to objects that might otherwise be unreachable by an application, thus, resulting in an unexpected situation of running out of memory. A call to the ObjectOutputStream.reset() method resets the object/handle table to its initial state, allowing all previously written objects to be eligible for garbage collection.

96. What is encapsulation?

Encapsulation describes the ability of an object to hide its data and methods from the rest of the world

97. What is a policy?.

It’s an abstract class for representing the system security policy for a Java application environment (specifying which permissions are available for code from various sources). Java security properties file resides in /lib/security/java.security directory.

98. What is the difference between TCP/IP and UDP?
TCP/IP is a two-way communication between the client and the server and it is a reliable and there is a confirmation regarding reaching the message to the destination. UDP is a one-way communication only between the client and the server and it is not a reliable and there is no confirmation regarding reaching the message to the destination.

99. Why is UTFDataFormatException thrown by DataOutputStream.writeUTF() when serializing a String?

DataOutputStream.writeUTF() does not support writing out strings larger than 64K. The first two bytes of a UTF string in the stream are the length of the string. If a java.lang.String is larger than 64K, it needs to be stored in the stream by an alternative method rather than depending on the default method of storing a String in the stream, writeUTF.

100. What is inheritance?

Inheritance is the ability to create new classes based on existing classes. It is useful to reuse existing code.

-----------------
Also Read:

0 comments:

Post a Comment