Java Interview Questions and Answers

Java Interview Questions: This Article is about Java Interview Questions all types of topics like the exception, Threads interview question and Answers are covered in this Article.

1) What is the most important feature of java?

A)Java is a platform independent language.

2) What do you mean by platform independent?

A) Platform independent means that we can write and compile the java code in one platform (example windows) and can execute the class in any other supported platform example (Linux, Solaris).

3) What is a JVM?

A) JVM is Java Virtual Machine which is a run time environment for the compiled java class files.

4) JVM is platform independent?

A) JVM is not platform independent. JVM is platform specific run time implementation provided by the vendor.

5) What is the difference between a JDK and a JVM?

A) JDK is Java Development Kit which is for development purpose and it includes execution environment also. But JVM is purely a run time environment and hence you will not be able to compile your source files using a JVM.

6) What is the latest version of Java?

A) Java SE 10.

7) What is a JIT compiler?

A) JIT compiler stands for a just-in-time compiler and is a part of JVM which increases the speed of execution of a java program.

8) What is the base class of all java classes?

A) java.lang.Object is the base class of all java classes.

9) Does Java support multiple inheritance?

A) Java doesn’t support multiple inheritances with classes.

10) Are arrays primitive data types?

A)   In Java, arrays are referenced types.

11) Is Java pure object-oriented?

A)   99.99% java is purely object-oriented.

12) What is the difference between Path and Classpath?

A)   Path and Classpath are operating system level environment variables. The path is used to define where the system can find the executable (.exe) files and Classpath is used to specify the location .class files.

13) What are the local variables?

A)   If we are defining any variable inside a method (or) block (or) constructor() then that variable is called as local variables. Before using the local variable must provide the initialization.

14) What are Instance variables?

A)    Instance variables are those which are defined at the class level. Instance variables need not to be initialized before using them are automatically initialized with their default values. JVM will provide the default initialization for Instance variables.

15) What is Bytecode?

A) Byte code is the compiled code of a Java program. Byte means the name of the format and codes means the group of statements.

                                     (or)

A) The group of statements representing a Java application in the middle level using byte format is known as Byte code.

16) Should a main() method be compulsory declared in all java classes?

A)    No, not required. The main() method should be defined only if the source class is a java application.

17) What is the return type of main() method?

  A)  The main () method doesn’t return anything hence declared as void.

18) Why is the main() method declared as static?

  A) Main() method is called by the JVM even before the instantiation of the class hence it is declared as static.

19) What is the argument of the main() method?

  A) main() method accepts an array of String Object as command line arguments.

20) Can a main() method be overloaded?

  A) Yes. We can define any number of main() methods with different method signature and implementation in the class.

21) What is an object?
A) An object is the instance of a class. An object represents data of a class.
                (or)
A) The memory space allocated for the member of the class (where all the members of a class would have been loaded) dynamically at run time is known as an object.
22) What is Reference variable?
A) Reference is a variable representing the address of the object.

23) Can a source file contain more than one class declaration?

A)    Yes, a single source file can contain any number of class declaration but only one of the classes can be declared as public.

24) What is “.class”?

A) “.class” would be the extension given to a file which contains byte code.

25)  Which package is imported by default?

A)  java.lang package is imported by default even an import statement.


26) Can a class declare as private be accessed outside of its package?

A) Not possible. But outer classes are not possible to declare with private, only inner classes are allowed to declare with private.


27) What are the methods in Object?

A) clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString,wait(),wait(long timeout),wait(long timeout,intnanos).


28) What is the default import statement in Java?

A) java.lang.*; is automatically imported into all Java programs.

29) What is the default of an object reference declared as an instance variable?

A) Null unless we define it explicitly.

30) Can a top level class be private or protected?

A) No, a top-level class is not private or protected. It can have either “public” or no modifier. If it does not have a modifier it is supposed to have default access. If a top-level class is declared as private the compilers will that “the modifier private is not allowed here”. This means that a top-level class cannot be private. Same is the case with protected.

31) What Type of parameter passing does Java support?

A) In Java, the arguments are always passed by value.


32) Primitive data types are passed by reference or by value?

A) Primitive data types are passed by value.


33) Objects are passed by value or by reference?

A) Java supports only pass by value. With Objects, the object reference itself is passed by value and so both the original reference and parameter copy refer to the same object.


34) Is Java a pure object oriented language?

A) Java is a pure object-oriented language. Except for the primitives, everything else objects in Java.


35) Is default a keyword?

A) Yes. The default is a keyword but it is associated with a switch statement and not with access specifiers.

36) What is the default value of the local variables?


 A) The local variables are not initialized to any default value. It is initialized to either primitives or object references.


37) What is the static variable?

 A) A static variable is used to refer to the common property of all objects. Static variable gets memory only once in the class area at the time of class loading.

38) What is the final variable?

A) If you make any variable as final, you cannot change the value of that variable.

39) What is a transient keyword?


A) If you define any data member as transient it will not be serialized.

40) What is the modifier not allowed for a method?

A) Except transient and volatile all other 9 modifiers are allowed.


41) What is static loading?

A) The concept of allocating the memory (in the Ram) and loading the functionalities & data to the RAM before the execution of the program starts or before the function call is made is known as static loading.

42) What is Dynamic loading?

A) The concept of allocating the memory and loading the functionalities to the RAM at the run time, dynamically when the function call is made (or) when the program is under execution is known as Dynamic loading.

43) What if I write static public void instead of public static void?

A) The program compiles and runs properly.


44) What if I do not provide the String array as the argument to the method?
 A) The program compiles but throws a runtime error “NoSuchMethodError”.

45) What is the first argument of the String array in the main method?

 A) The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name.


46) Can I have multiple main methods in the same class?

 A) No, the program fails to compile. The compiler says that the main method is already defined in the class.


47) Do I need to import java.lang package any time?

A) No. It is by default loaded internally by the JVM.


48) What is the difference between Static loading and Dynamic loading?

A)   
Static loading: 
1) Static loading increases the overhead on the operating system.
2) Structured programming language programs work on the concept of static loading.

Dynamic loading:
1) Dynamic loading reduces the overhead on the operating system.
2) Object-oriented language like java work on the concept of Dynamic loading.

49) What is the access scope of a protected method?

A) A protected method can be accessed by the classes with in the same package or by the subclasses of the class in any package.

50) What is the impact of declaring a method as final?

A) A method declared as final can’t be overridden. A sub-class can’t have the same method signature with a different implementation.


51) Can there be an abstract class with no abstract methods in it?

A) Yes.


52) Can we execute a program without a main() method?
A) Yes, one of the ways is static block but in the previous version of JDK not in jdk1.7 onwards
Class A


{


static
 {
System.out.println(“static block invoked”);
System.exit(0);
  }

53) Explain the processes performed by the Java virtual machine?

A) The javap is a standard .class file for printer or disassemble. This file converts the description of .class into the original source code.


54) What is the main difference between the Java platform and other platforms?

A) The Java platform differs from most other platforms by its software-based platform that runs on top of other hardware-based platforms. It has two components.
1. Runtime Environment
2. API (Application Program Interface)

55) What gives java it's written once and run anywhere nature?


A) The byte code .java is compiled as a byte code which acts as an intermediate language between source code and machine code. This byte code is not platform specific and hence can run in any platform.

56) What happens if I write static public void instead of public static void?

A) Programs compile and run properly.

57) What is the default value of the local variables?

A) The local variables are not initialized to any default value, neither primitives nor object references.


58) How to define a constant variable in Java?

A) The variable should be declared as static and final so only once the copy of the variables exists for all instances of the class and the value can’t be changed. Static final int a = 2; is an example for constant.


59)  What is a package?

A)  A package is a collection of related classes and interfaces. Package declaration should be the first statement in a java class.


60) What if the main method is declared as private?

A) The program compiles properly but at runtime, it will give a message “Main method not public”.


61) What if the static modifier is removed from the signature of the main method?

A) Program compiles. But at runtime throws an error “NoSuchMethodError”.


62)  What is a native method?

 A) A native method is a method that is implemented in a language other than Java.


63) Why we cannot see the executable code in java once the execution of the Java application is completed?

A) The executable code of any Java function would be persistent as long as the program is under execution. Once the execution of the program is completed automatically the execution of that functionalities would be destroyed. So at any given point of time, we can’t see the executable code in java.

64) Why Java is platform independent while JVM is platform independent?

A) Since compiled code of a Java application executed on any machine irrespective of the operating system under which the machine is working, we can say Java is platform Independent.

65) What is “rt.jar” file?

A) “rt.jar” file contains all the basic and fundamentals java libraries (like java.lang, java.io, java.utiletc) which are required for developing any Java application in general.

66)Can a main() method be overloaded?

A) Yes. We can define any number of main() methods with different method signature and implementation in the class.

67) Can a main() method be declared as final?


A)  Yes. Any inheriting class cannot have it’s own default main() method.

68) What is Reference variable?

A) Reference is a variable representing the address of the object.
69) What is the difference between Reference and Object?
A) Reference represents the only address of the object but object represents the data of a class.
70) What is the default initialization?
A) The concept of JVM automatically initializing uninitialized variables with default values is known as default initialization. Default initialization is applicable only to the instance and static variables.
71) When do we get a compilation error because of variables?
A) Using uninitialized variables leads for a compilation error in Java.
72) What is Typecasting?
A) The concept of converting the value of one data type into its equivalent & corresponding value of another data type is known as Typecasting.
73) What are different types of Typecasting?
A) There are "2" types of Typecasting:
1) Implicit Type Casting 2) Explicit Type Casting
74) What is Implicit Typecasting?
A) The concept of JVM automatically converting a value of one data type into its equivalent & corresponding value of another data type by itself that is without user concern is known as Implicit type casting.
75) What is Explicit Typecasting?
A) The concept of JVM converting a value of one data type into its equivalent & corresponding value of another data type explicitly according to user specifications is known as Explicit typecasting.
76) What is Hash code?
A) Hash code is nothing but the Index of the address of the object.
77) What is available to the static method?
A) To the static method, only static members of the same class are directly available and non-static members are not available directly. In order to access non-static members from the static functions, we need object without object we cannot access non-static members from the static functions.
78) What is available to the non-static method?
A) To the non-static method, both static and non-static members of the same class are directly available (because to the non-static method, the object is directly available and context would be available to the object). Thus from the non-static method, we can access both static & non-static members of the same class directly.
79) What is polymorphism?
A) The concept of defining multiple functionalities with the same name associated with the same object could be called as polymorphism.

80) What are two types of polymorphism?
A) The two types of polymorphism are:
1) Static polymorphism / Compile time polymorphism.
2) Dynamic polymorphism / Runtime polymorphism. 
81) What is Static polymorphism?
A) The concept of defining multiple functionalities with the same name within the same class by changing the data types of the parameters is known as static polymorphism.
82) What happens in static polymorphism at the time compilation?
A) In static polymorphism, out of multiple methods with the same name which method has to get executed would be decided at the time of compilation itself. Thus we call that has static (or) compile time polymorphism.
83) What happens in dynamic polymorphism?
A) In dynamic polymorphism, out of multiple methods with the same name & with same data types of the parameters which function (or) method has to get executed would be decided dynamically at the run-time based on the run-time conditions. Thus we call that kind of polymorphism has dynamic (or) run-time polymorphism.
84) What is a pointer and does Java support pointers?

A) The pointer is a reference to handle a memory location. Improper handling of pointers leads to memory leaks and reliability issues hence Java doesn’t support the usage of pointers.


85) Is Collection is an Interface or Class?

A) A collection is an Interface.

86) What is the difference between collection and collections?

A) Collection: Collection is an interface in java.util package used to represent a group of as a single entity.

Collections: Collections is a class in java.util package. This class consists exclusively of static methods that operate on or return Collections.

87) What are the Collections API?


A) The Collections API is a set of classes and interfaces that support operations on the collection of objects.

88) What is Cursor in Java?

A) If we want to receive objects one by one from the Collection then we should use Cursor in Java.

89) How many Cursors are there in Java?

A) There are three cursors available in Java. They are:
     1) Enumeration.
     2) Iterator.
   3) List Iterator.


90) What is an Iterator?

A) The Iterator interface is used to step through the elements of a Collection. Iterators let you process each element of a collection. Iterators are a generic way to go through all the elements of a collection no matter how it is organized. An iterator is an interface implemented a different way for every Collection.

91) How do you traverse through a collection using its Iterators?

 A) To use an Iterator to traverse through the contents of a collection, follow these step:
a) Obtain an Iterator to the start of the collection by calling the collection iterator() method.
b) Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext() returns true.
c) Within the loop, obtain each element by calling next().

92) How do you remove elements during Iterator?

A) Iterator also has a method remove() when remove is called, the current element in the iteration is deleted.

93) What is the List Iterator?

A) List Iterator is just like Iterator, except that it allows us to access the collection in either the forward or backward direction and lets us modify an element.

94) What is an Enumeration?
 A) The Enumeration interface defines the methods by which you can enumerate ( obtain one at a time ) the elements from legacy collection objects. We can create Enumeration object by using elements method.
Example: Enumeration e = v.elements();

95) What are the methods present in Enumeration Interface?

A) There are three methods in Enumeration Interface. They are:
    1) asIterator().
    2) hasMoreElements().
    3) nextElement().

96) What are the methods present in Iterator?
A)  There are four methods present in Iterator. They are:
    1) hasNext().
     2) next().
     3) remove().
     4) forEachRemaining( Consumer<? superE> action).

97) What are the methods present in List Iterator?
A) There are nine methods present in List Iterator. They are:
    1) add( E e).
    2) hasNext().
    3) hasPrevious().
    4) next().
    5) nextIndex().
    6) previous()
    7) previousIndex().
    8) remove().
    9) set( E e).

98) How Enumeration can be converted into an Iterator?

A) An Enumeration can be converted into an Iterator by using the Enumeration.asIterator() method.

99) What is the Comparable Interface?

A) Comparable Interface is used to order the Objects of user-defined Class. It provides only a single sorting sequence.

100) What is the Comparator?

A) A comparator is an interface present in java. util package. The comparator object reference can be used to define our own customized sorting order.

101) What is a Sorted Map?

A) Sorted Map is a subinterface of Map. If we want to represent a group of key-value pairs according to the sorting order of keys. In Sorted Map we can perform sorting only based on the keys but not values.

102) Which interface provides the capability to store objects using a key-value pair?

A) Java.util.map.

103) What is the use of descending keyset()?

A) The descending keyset() method returns a NavigableSet in which the order of the elements is reversed compared to the original key set.

104) What is the use of descendingMap()?

A) The descendingMap() method returns a NavigableMap which is a view of the original Map. The order of the elements in this view map is reverse of the order of the original map.  

105) What is the use of headMap()?

A) The headMap() method returns a view of the original NavigableMap which only contains elements that are less than the given element.

106) What is the difference between HashSet and LinkedHashSet?

A) HashSet does not maintain Insertion order of Objects. LinkedHashSet maintains Insertion order of objects.

107) What is the difference between the List and Set?

A) The list can contain duplicate elements whereas Set contains unique elements only.

108) What is Stack?

A) A stack is a child class of vector. If we want to represent object according to last in first out order then we should go far, Stack.

109) What is ceiling key?

A) The ceilingKey() method returns the least(smallest) key in the Map that is greater than or equal to the element passed as a parameter to the ceilingKey() method.

110) What is the PollFirstEntry?

A) The PollFirstEntry() method returns and removes the first entry (key + values) in the NavigableMap or null if the map is empty.

111) What is the use of PollLastEntry?

A) The PollLastEntry returns and removes the last element in the map or null if the map is empty.

112) What is the difference between HashMap and WeakHashMap?

A) HashMap: Object is not eligible for garbage collection if it is associated with Hashmap. Even though it does not have any external references.


WeakHashMap: If an Object is not having any external references then it is always eligible for garbage collector even though it is associated with WeakHashMap.

113) What is the List Interface?

A) The List interface provides support for ordered collections of objects. Lists may contain duplicate elements.

114) What is the main implementation of the List interface?

 A) The main implementation of the List interface are as follows:
       Array List: Resizable-array implementation of the List interface. The best all-around implementation of the List interface.
       Vector: Synchronized resizable-array implementation of the List interface with additional “Legacy methods”.
       Linked List: Doubly-linked list implementation of the List interface. May provide better performance than the Array list implementation if elements are frequently inserted or deleted within the list. Useful for queues and double-ended queues (deques ).

115) What is the advantage of Array List over arrays?

  A) Some of the advantages Array List has over arrays are:
       It can grow dynamically.
       It provides more powerful insertion and search mechanisms than arrays.

116) Difference between Array List and Vector?
 A)
Array List:
1) Array List is Not synchronized by default.
2) Array List can use the only Iterator to access the elements.
3) The Array List increases its array size by 50 percent if it runs out of the room.
4) Array List has no default size.

Vector:
1) Vector List is synchronized by default.
2) Vector list can use Iterator and Enumeration Interface to access the elements.
3) A Vector defaults to doubling the size of its array if it runs out of the room.
4) While vector has a default size of 10.

117) How to obtain Array from an Array List?

A) An array can be obtained from an Array List using toArray() method on Array List.
List a = new ArrayList();
a.add(a[]);
Object a[] = a.toArray();

118) How do you decide, when to use Array List and when to use Linked List?

A) If you need to support random access, without inserting or removing elements from any place other than the end, then Array List offers the optimal collection. If however, you need to frequently add and remove elements from the middle of the list and only access the list elements sequentially, then linked list offers the better implementation.


120) What is the Set Interface?

A) The Set Interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements. Contains no methods other than those inherited from the collection. It adds the restriction that duplicate elements are prohibited. Two Set objects are equal if they contain the same elements.


121) What are the main implementations of the Set Interface?

A) The main implementation of the Set interface is as follows:
       HashSet
       TreeSet
       Linked HashSet
       EnumSet

122) What is a HashSet?

A) A HashSet is an unsorted, unordered Set. It uses the hash code of the object being inserted (so the more efficient your hashcode() implementation, the better access performance you’ll get). Use this class when you want a collection with no duplicates and you don’t care about the order when you iterate through it.

123) What is a TreeSet?

A) TreeSet is a Set implementation that keeps the elements in sorted order. The elements are sorted according to the natural order of elements or by the comparator provided at creation time.

124) What is an EnumSet?

A) An EnumSet is a specialized set for use with enum types, all of the elements in the EnumSet type that is specified, explicitly or implicitly, when the set is created.

125) What is the difference between HashSet and TreeSet?
A) 
 HashSet: HashSet is under Set interface i.e. it does not guarantee for either sorted order or sequence order.

TreeSet: TreeSet is under Set i.e. it provides elements in sorted order(acceding order).

126) What is a Map?

A) A map is an object that stores associations between keys and values (key/value pairs). Given a key, you can find its value. Both keys and values are objects. The key must be unique, but the values may be duplicated. Some maps can accept a null key and null values, others cannot.


127) Whaisre the main Implementation of the Map Interface?
 

A) The main implementation of the List Interface is as follows:
       HashMap
       HashTable
       TreeMap
       EnumMap

128) What is the difference between HashMap and when to use TreeMap?
A) 
HashMap:
1) HashMap lets you have null values as well as one null key.
2) The iterator in the HashMap is fall-safe (If you change the map while iterating, you’ll know).
3) HashMap is unsynchronized.

HashTable:
1) Hashtable does not allow null values as key and value.
2) The enumerator for the HashTable is not fall-safe.
3) HashTable is synchronized.

129) How does a Hashtable internally maintain the key-value pairs?

A) TreeMap actually implements the SortedMap interface which extends the Map interface. In a Treemap, the data will be sorted in acceding order of keys according to the natural order for the key’s class, or by the comparator provided at creation time. Treemap is based on the Red-Black tree data structure.

130) What are the different collection views that Maps provide?

A) A map provides three Collection Views.
       Key Set – allow a map’s contents to be viewed as a set of keys.
       Values collection – allow a map’s contents to be viewed as a set of values.
       Entry Set – allow a map’s contents to be viewed as a set of key-value mappings.

131) What is a Keyset view?

A) The keyset is a set returned by the KeySet() method of the Map Interface, it is a set that contains all the keys present in the Map.

132) What is a values Collection Views?

A) Values Collection Views is a collection returned by the Values() method of the Map Interface, it contains all the objects present as values in the map.

133) What is an Entry Set View?

A) Entry Set View is a set that is returned by the entryset() method in the map and contains objects of type map. Entry, each of which has both Key and Value.

134) How do you sort an ArrayList (or any list) of user-defined objects?

A) Create an implementation of the java.lang.Comparable interface that knows how to order your objects and pass it to java.util.Collections.sort(List, comparator).


135) What is the difference between creating an object of string class using the new operator and using doubles quotes?
A) Using double quotes object of the string class representing a specific sequence of characters could be created only once. Whereas using new operator we can create any number of String class objects representing the same sequence of characters.

136) Explain about concatenation operator (+) in Java Strings?
A)  The functionality of the concatenation operator is to create a new String class object with the data present at the left-hand side and right-hand side.

137) What is String Buffer?
A) String Buffer is like a String but can be modified in the same memory location. Every method of the String Buffer class would be changing the data within the same object and returns the address of the same object.

138) What is the String Builder?
A) String Builder is a mutable sequence of characters. String Builder class is designed for use as a drop-in replacement for StringBuffer in places where the String buffer was being used by a single thread.

139) What is the default capacity of String?
A) Strings do not have default capacity. The passed String length is its capacity.

140) What is the default capacity of String Buffer?
A) String Buffer has default capacity as 16 buffers. It increases its capacity automatically when sizes reach maximum using its capacity formula ( ( current capacity * 2 ) + 2).

141) In how many ways we can concat String in Java?
A) Using String object, we can concat new string to the current in two ways.
1) using + operator.
2) using concat() method.

142) In how many ways we can concat String Builder in Java?
A) Using String Buffer we can perform concat operation only in one way.
1) using append() method.

143) What is toString() method?
A) If you want to represent an object as a string, toString() method is used.

144) What is the advantage of the toString() method?
A) By overriding the toString() method of the object class, we can returns the values of the object.

145) What is the use of the charAt() method?
A) CharAt() method returns the character at the specified location.
   Example:
  String name = “TutorialsWeb”
  Char ch name.charAt(7);

146) What are the interfaces String class Implements?
A) String class implements “3” interfaces in Java. They are:
    1) Serializable.
    2) charsequence.
     3) comparable<String>.

147) Is String class final in Java?
A) Yes. String class is declared as final in Java.

148) What is difference between equals() and “ == ” operator?

A) The equals() method compares the characters inside a String object. The “==” operator compares two object references to see whether they refer to the same instance.

149) Is String thread-safe in Java?
A) Since String is immutable, it is threaded safe and it can be shared between multiple threads without external synchronization.

150) Why java uses the concept of String literal?
A) To make Java more memory efficient, because no new objects are created if it exists already in string constant pool.

151) What is the String Constant pool (String literal pool)?
 A) String Constant pool is a separate block of memory where the string objects are held by JVM.



152) What is Stream?

A) A stream is a logical connection between a java program and a File.
                             (or)
A stream can be defined as a continuous flow of data between java program and persistence media.

153) How many types of Streams are there?

A) There are two types of Streams they are:
1) Input Stream.       
2) Output Stream.

154) What is Input Stream?

A) The Stream that allows data to come into Java application from the persistent media is called an Input Stream. Input Stream is used to read the data from a persistent media.

155) What is Output Stream?

A) The Stream that allows data to send out from the Java application to be stored into the persistent media is called as Output Stream. Output streams are used to write data in persistent media from a Java application.

156) How data is sent to Streams in Java?

A) In Java data is send to Streams in the format of Bytes or Characters.


157) Explain about Multitasking?

A) The concept of executing multiple functionalities simultaneously one with the other is known as Multitasking.

158) Explain the advantage of Multitasking?

A) The advantage of multitasking is shown below:
1) BY applying the concept of multitasking we can totally avoid the idle state of the CPU.
2) BY applying the concept of multitasking we can make the functionalities independent on each other.
3) Actually, the concept of multitasking was invented in order to overcome the idle state of CPU. But we apply the concept of multitasking to make the functionalities independent on each other.

159) What happens in Multitasking?

A) In Multitasking multiple functionalities would be executed part by part with a very small & negligible time gap. Because of which it looks multiple functionalities are getting executed simultaneously one with the other.

160) What are the two types of Multitasking?

A) The two types of Multitasking are:
1) Process-based Multitasking.
2) Thread-based Multitasking.

161) Explain about Process based Multitasking?

A) Executing multiple programs belonging to the different languages & technologies simultaneously one with the other is known as process-based Multitasking.

162) Explain about Thread based Multitasking?

A) Executing multiple functionalities (or) methods belonging to the same process (or) belonging to the same application simultaneously is known as Thread based Multitasking.

163) Why Java support Thread based Multitasking?

A) In thread-based multitasking, the control would be switching between the two different functionalities (or) methods belonging to the same application and process which would not increase any overhead on the system. Thus Java supports only thread based multitasking.

164) What is a Thread?

A) A thread is nothing but a functionality (or) method which could be executed simultaneously with the other part of the program.

165) What is the difference between Thread and Method?

A) Every Thread is a method. But every method cannot be a thread.

166) What is a Process?

A) Any program which is under execution is called a process.

167) Explain the relation between thread and process?

A) A thread is a part of the process.

168) Explain the steps using which we implement the concept of thread-based multitasking?

A)  The two steps using which we implement the concept of thread-based multitasking in Java:
1) Defining a functionality has a thread.
2) Executing the run method of Runnable Interface has a thread.

169)  Explain Start() method of thread class?

A) The functionality of the start method of thread class is only to handover the run method of Runnable Interface to the JVM for scheduling and request JVM to execute run method of the runnable interface has a thread.

170) What is Multithreading?

A) The concept of defining multiple functionalities has threads and executing multiple functionalities has threads simultaneously one with the other is known as Multithreading.

171) What is scheduling?

A) The concept of deciding, when the execution of a thread has to start (or) begin and deciding what part of a thread has to get executed and deciding which thread has to continue next is known as scheduling.

172) what is Rescheduling?

A) JVM bringing thread which is under wait state into Action is known as Rescheduling.

173) Explain about Priorities?

A) Priority means preference. Using priorities we can control the Rescheduling of threads.

174) Explain about Notify method?

A) Whenever notify method is called, it would be bringing a thread which is in the wait state back into action. Based on the priorities mention.

175) What is Deadlock?

A) It is the state of a thread application, where multiple threads belonging to the same application would enter into wait state simultaneously & multiple threads belonging to the same application would continue in the wait state forever, which is known as Deadlock.

176) How to avoid Deadlock?

A) We can avoid Deadlock using wait method of the object class.

177) How many types of Threads are there in Java?

A) There are two types of Threads in Java:
1) User Thread.
2) Daemon Thread.

178) What is User Thread?

A) The normal and usual child thread which is joined to the end of its parent is known as User Thread.

179) What is Daemon Thread?

A) Any child thread which is not joined to the end of its parent is known as Daemon Thread.

180) What is the Minimum priority of Thread?

A) “1” is the Minimum priority of Thread.

181) What is the Normal priority of Thread?

A) “5” is the Normal priority of Thread.

182) What is the Maximum priority of Thread?

A) “10” is the Maximum priority of Thread.

183) What are the methods used for preventing Thread execution?

A) We can prevent the Thread Execution by using the following methods of threads class.
1) yield.
2) join.
3) sleep.

184) Explain about the Yield() method?

A) This is used to pause the currently executing thread, for giving chance to remaining waiting threads of some priority. If there is no thread waiting or all the threads waiting have low priority, then the same thread is once again given a chance for the execution.

185) Explain about the Join() method?

A) If a thread wants to wait until completion of other thread, then we should go for join() method.

186) Explain about the Sleep() method?

A) If a thread doesn’t want to perform any operation for the particular amount of time when pausing is required, then we should go far sleep() method.

187) How to Interrupt a Thread?

A) A Thread can interrupt a sleeping or waiting thread by using interrupt() method of Thread class.

188) How to stop a Thread?

A) To stop a thread execution in the middle by using stop() method.

189) How to Suspend() and Resume() a Thread?

A) A Thread can Suspend another thread by using suspend() method.
And Resume a suspend thread by using resume() method.

190) Explain about the Synchronized?

A) Synchronized is the keyword applicable only for methods but not for variables and class.

191) What is the use of Synchronized Keyword?

A) If a method is declared as Synchronized, then at a time only one method is allowed to execute.


192) How locks are used in Synchronization?

A) Internally Synchronization concept is implemented by using lock concept. Whenever we use the synchronized keyword, then lock concept comes into existence.

193) Explain about the wish() method as Synchronized?

A) If we declare wish() method as synchronized then the threads will be executed one by one and hence we will get regular output.

194) Explain about the Inter-Thread Communication?

A) The process of executing threads in the sequence of a loop with communication is called Inter-Thread Communication.

195) What are the different states of a Thread?

A) The different states of Thread are:
1) New state.
2) Runnable state.
3) Running state.
4) Dead state.
5) Blocked state.

196) Explain about Time-sliced or Round-Robin Scheduling?

A) A running thread is allowed to execute for a fixed length of time, after which it moves to the ready to run state to wait for its turn to run again.

197) How many types of Java Streams are there in Java?

A) There are two types of Java Streams are there in Java. They are:
1) Binary Stream.
2) Character Stream.

198) What is Binary Stream?

A) The Stream which read and write data in the format of bytes is called as Binary Streams.

199) What is Character Stream?

A) The Streams which read and write data in the format of characters is called as Character Streams.

200) What is Sequence Input Stream?

A) This class is used to read data from multiple Input Streams Sequentially.

201) What is File InputStream?

A) File InputStream is a subclass of InputStream and Closeable, Autocloseable interfaces. File InputStream class is used to read data from a File.

202) What is File OutputStream?

A) File OutputStream is a subclass of OutputStream and Closeable, Flushable, AutoCloseable interfaces. File OutputStream is used to write data to a File.

203) What are the limitations for File InputStream and File OutputStream?

A) File InputStream and File OutputStream allow User to read and write data Only in the format of bytes. It is not possible to read (or) write data in the format of primitive data or objects.

204) What is Data InputStream?

A) Data InputStream is used to read data as primitive types.

205) What is Data OutputStream?

A) Data OutputStream is used to write data as primitive types.

206) What are the limitations of Data InputStream and Data OutputStream?

A) Using Data InputStream and Data OutputStream user cannot read and write objects from persistent media. They have the capability only to read data up to primitive data types.

207) What is Object InputStream?

A) Object InputStream is used to read data as Object.

208) What is Object OutputStream?

A) Object OutputStream is used to write data as Object.

209) What is Serialization?

A) Serialization is the process of converting objects into stream of bytes and sending them to OutputStream. Using Serialization we can store object state permanently in the destination.

210) What is Deserialization?

A) Deserialization is the process of converting a stream of bytes into the original location.

211) What is Marker Interface?

A) The Interface using which user can explicitly mention (or) Mark certain properties to an Object is known as Marker Interface.

212) Explain about Transient Keyword?

A) At the time of serialization if we don’t want to save the original value of a variable then it should be declared as Transient. Transient keyword is applicable to only for variables. 

213) Explain the difference between the following statements?
       String s = “Hello”;
       String s = new String(“Hello”);
A)  In first statement assignment operator is used to assign the string. In this case, JVM first checks the String pool whether the same value is already available in the String container or not, if available then it creates another reference to it, if not available then it creates the new one.
In the second case each and every time it creates a new object of string.

214) How to concat two different String?
A) We can concat two different Strings with the help of “+” assignment operator or concat() method of String class.

215) What do you mean by immutability?
A) Immutability means once an object is initialized we can’t change.

216) What is the String pool in Java?
A) String pool is a special storage area in java heap, mostly located on Bergen space, to store string literals like “ABC”. When Java program creates a new string using String literal, JVM checks for that string in the pool and, if string literal is already present in the pool then the same object is returned instead of creating a whole new object. String pool check is performed only when you create a string as literal, if you create String using the new() operator, a new String object will be created even if String with the same content is available in the pool.

217) How to make a class immutable in java?
A) 1) Make a class final or private.
     2) Remove constructor.
     3) Allow only the getter method in your class.

218) What is the difference between String and StringBuffer classes?
A)  
String:
1) String class object is immutable hence there contain cannot be modified.
2) The method that directly manipulates data of the object in String class.
3) Append(),reverse() method not available in String class.

StringBuffer:


1) StringBuffer object is mutable so they can be modified.
2) Such methods are available in String class.
3) Append(),reverse() method available in StringBuffer class.

219) There are any other classes in java that is immutable?
 A) All the wrapper classes in Java are immutable like Integer, Float, Double etc.

220) What is the String Tokenizer class?
A) String Tokenizer class is used to break the string in the form of tokens.

221) There is an alternative to string Tokenizer?
A) The String class is an alternative of string tokenizer, with the help of split() method of string.

222) What is the difference between StringBuffer and StringBuilder?
A) StringBuffer is synchronized and StringBuilder is not.

223) How to convert Integer to String?
A) With the help of toString() method of String class.

224) The string is Thread safe or not?
A) Yes, String is thread safe because string object is immutable that’s way string is thread safe.

225) What is difference between compareTo() and equals() method?
A) compareTo(): compareTo() method is provided by java.lang.String package that checks the difference string to the character by character if both the strings are same then return 0 otherwise it returns (-value) for each character.
Equals(): Equals() method is java.object package Object class method that checks the two different object and returns true or false.

226) How many types of errors are there in Java?

A) There are two types of errors are there in Java:
1) Compilation error.
2) Run-time error.

227) What is a compilation Error?

A) Any error that occurs at the time of compilation could be called as Compilation Error.

228) What is Run-time Error?

A) Any Error that occurs at the time of execution of the program could be called as Run-time Error.

229) What is logical Error?

A) Any wrong logic which leads for the wrong outputs could be called as a logical Error.

230) What is Abnormal Termination?

A) Terminating any program in the middle of its execution and controlling coming out of the application (or) program without executing the last statement of the main method is known as Abnormal Termination.

231) What is Exception?

A) Exceptions are the objects representing logical Errors and Run-time Errors.

232) What is Exception handling?

A) The concept of identifying an exception and catching that exception and assigning that exception to the reference of the corresponding exception class is known as Exception Handling.

234) What is Hard coding?

A) The concept of using values directly is called Hard coding.

235) What are two types of Logical Errors?

A) There are two types of Logical Errors. They are:
1) Simple Logical Errors.
2) Serious Logical Errors.

236) Explain simple logical Errors?

A) All the Logical Errors which could be neglect by the JVM are called Simple Logical Errors.

237) Explain about Serious Logical Errors?

A) All the logical Errors (or) the run-time errors which could not be neglect by the JVM is Known as Serious Logical Errors.

238) How many types Java Exceptions are divided?

A) All the Exceptions are divided into two types. They are:
1) Checked Exceptions.
2) Un-checked Exceptions.

239) Explain about Checked Exceptions?

A) All the Exceptions which are not the sub-class of Run-time Exceptions are known as Checked Exceptions.

240) Explain about Un-Checked Exceptions?

A) All the Exceptions which are the sub-class of Run-time Exceptions are known as Un-Checked Exceptions.

 241) What is the difference between “Throws” and “Throw”?

A) Using throws we can only Explicitly provide the information about the unhandled Exceptions to the Java compiler and JVM and end user. But whereas using throw we would be Explicitly raising an Exception representing the user-defined Run-time errors.

242) Explain about Try Keyword?

A) Try: Try establishes a block to write a code that causes exceptions and its related statements. Exception causing statement must be placed in a try block to be handled and catch that exception for stopping abnormal termination.

243) Explain about Catch Keyword?

A) The catch block is used to catch exceptions those are thrown from its corresponding try block. It has logic to take necessary action on that caught exception.

244) Explain about Final block?

A) Final establishes a block that definitely executes statements placed in it. Statements which are placed in this block are always executed irrespective of the way the control is coming out from the try block either by completing normally, by return statements or by throwing an exception, by catching or not catching.

245) What is Exception propagation?

A) The process of sending exception from called method to calling method is called as Exception propagation.

246) Explain the uses of Throws Keyword?

A) 1) Using throws keyword we provide the complete information about the unhandled Exceptions to the user and to the Java compiler.
2) Using throws keyword we can avoid try & catch blocks with respect to the statements proven to generate Checked Exceptions in a method.

247) Explain about Finally?

A) Finally, blocks can be executed compulsory with irrespective of Exceptions.

248) Explain the uses of the Finally block?

A) The two uses of Finally block are:
1) Using Finally block we can maintain proper separation between the statements belonging to the try, catch and the statements belonging to the function.
2) Using Finally blocks we can avoid catch blocks.

249) When it is mandatory to call a method inside try & catch blocks?

A) Whenever a method uses throws keyword and mentions the name of the checked Exception then it is mandatory to call that method inside the try-catch without which a compilation error occurs.


250) What is a Constructor?
A) Constructors are the functionalities which are going to get executed automatically at the time of creation of an object.
251) What is the difference between Constructor & Methods?
A)      
           Constructor
              Methods
1) With respect to one object, a constructor could be executed only once.
1) With respect to one object, a method could be executed any number of times.
2) Constructors are executed automatically at the time of creation of an object.
2) A method would be executed only it is explicitly called.
3) A constructor cannot have any return type not even void.
3) A method should and must have a return type at least void is compulsory.
4) Name of the constructor cannot be anything. Name of the constructor should and must be the name of the class.
4) Name of the method can be anything & the name of the method can also be the name of the class.

252) Can we define a method with the same name class name?
A) Yes, it is allowed to define a method with the same class name. No compile time error and no runtime error is raised, but it is not recommended as per coding standards.
253) How compiler and JVM can differentiate constructor and method definitions if both have the same class name?
A) By using return type, if there is a return type it is considered as method else it is considered as a constructor.
254) How Compiler and JVM can differentiate constructor and method invocations if both have the same class name?
A) By using the new keyword, if the new keyword is used in calling then the constructor is executed else method is executed.
255) Can we declare constructor as private?
A) Yes, we can declare constructor as private. All four accessibility modifiers are allowed for the constructor. We should declare constructor as private to not allow the user to create an object from outside of class. Basically, we will declare constructor as private to implement a singleton design pattern.
256) How many types of constructors are there in java?
A) Java supports "3" types of constructors:
1.  Default constructor.
2.  No-argument (or) Non-parameterized constructor.
3.  Parameterized constructor.
257) What is Default constructor?
A) The zero-argument constructor which is automatically provided to the class by the compiler (because the class doesn't one constructor) at the time of generating the byte code is known as Default constructor.
258) Why compiler generated constructor is called default constructor?
A) Because it obtains all its default properties from its class they are:
·       Its accessibility modifier is same as its class accessibility modifier.
·       Its name is same as its class name.
·       It does not have parameters and logic.
259) Can we consider both default and non-argument are same?
A) No, both are different. They seem to be the same but really not the same.
260) What are the differences between no-argument and default constructor?
A)
          Default constructor
 No-argument constructor
1)  It is generated by the compiler.
1)  It is defined by the developer.
2)  Its accessibility modifier is same as class accessibility modifier. So the only allowed accessibility modifiers are default or public.
2) It can have all four accessibility modifiers as it is defined by the developer, so the allowed accessibility modifiers are private, default, public, protected.
3)  It does not have logic except super() call.
3) It can have logic including super() call.

261) Is constructor definition mandatory in class?
A) No, it is optional. If we do not define constructor compiler defines the constructor.
Example:  Developer written code
Class Example
{
 public static void main(String[] args)
 {
System.out.println(“Constructor example”);
 }
}

Compiler changed code
Class Example
{
 Example()
 {
  Super();
 }
 public static void main(String[] args)
 {
System.out.println(“Constructor example”);
 }
}

262) What is Constructor Overloading?
A) Defining multiple constructors within the same class by changing the data types of the parameters & parameters is known as Constructor Overloading.
263) Why should we overload constructor?
A) To define different object initialization logic. To execute the same initialization logic by taking input values in a different type.
264) What is constructor chaining?
A) Calling one constructor from another constructor by using super() and this() is called constructor chaining.
265) Explain about "this" operator?
A) The functionality of "this" operator is to explicitly point the current object.
266) What is the current object?
A) The object because of which the method is currently under execution is known as the current object.
267) How to convert Integer to String?
A) There are many ways but two ways are shown below:
     1) String s = 7 + “ ”;
     2) String s = String.valueOf(7);

In the first case, JVM consumes a lot of space for memory. In the second case, JVM does not consume memory.                


Also read: java if else java print java println class and object in java liteblue java constructor bank of america routing number wells fargo routing number usps tracking usps hold mail prime number program in c java tutorial
Share:

No comments:

Post a Comment

Search This Blog

Powered by Blogger.

Blog Archive

Unordered List

Pages