Flat Preloader Icon

Interview Questions Core Java

1. What is the difference between JDK, JRE, and JVM?

Answer: The JDK (Java Development Kit) is a software package that includes the tools necessary for Java development, such as the Java compiler and debugger. The JRE (Java Runtime Environment) is a subset of the JDK, containing only the runtime components required to run Java applications. JVM (Java Virtual Machine) is a part of the JRE that executes Java bytecode. It is responsible for translating bytecode into machine code.

2. Explain the main principles of Object-Oriented Programming (OOP) and how Java supports them.

Answer: OOP principles include encapsulation, inheritance, and polymorphism. Java supports these principles by providing classes and objects for encapsulation, allowing class extension for inheritance, and supporting method overriding for polymorphism.

3. What is the purpose of the static keyword in Java, and how does it affect class members and methods?

Answer: The static keyword is used to define class-level members and methods. It means they belong to the class rather than an instance of the class. You can access them without creating an object of the class. For example, static methods can be called as ClassName.methodName().

4. Explain the concept of multithreading in Java, and how can you create and synchronize threads?

Answer: Multithreading allows multiple threads to run concurrently. In Java, you can create threads by extending the Thread class or implementing the Runnable interface. To synchronize threads, you can use keywords like synchronized and classes from the java.util.concurrent package to prevent race conditions and ensure thread safety.

5. What is the Java Collections Framework, and what are some commonly used data structures in it?

Answer: The Java Collections Framework is a set of classes and interfaces in Java used to work with collections of objects. Common data structures in the framework include ArrayList, LinkedList, HashMap, HashSet, and others for storing and managing data efficiently.

6. Explain the difference between == and .equals() when comparing objects in Java.

Answer: The == operator compares object references, checking if they refer to the same memory location. The .equals() method is typically overridden in classes to compare the content or attributes of objects. So, == checks for reference equality, while .equals() checks for content equality.

7. How can you achieve method overloading and method overriding in Java, and what are the differences between them?

Answer: Method overloading is done by defining multiple methods in the same class with the same name but different parameter lists. Method overriding involves creating a new implementation of a method in a subclass that has the same name and parameters as the method in the superclass. The key difference is that method overloading occurs within the same class, while method overriding occurs in a subclass that extends a superclass.

8. What is the difference between final, finally, and finalize in Java?

Answer: final: final is a keyword used to declare a variable constant or a method as unchangeable. It means you can’t change the value of a final variable or override a final method.
finally: finally is a block used in exception handling. It’s guaranteed to execute, whether an exception is thrown or not, and is typically used for cleanup operations.
finalize: finalize is a method in the Object class. It’s called by the garbage collector when an object is about to be destroyed. You can override it to provide your own cleanup code.

9. Explain the differences between HashMap and HashTable in Java?

Answer: HashMap is not synchronized and is not thread-safe. It allows null values and one null key.
HashTable is synchronized and thread-safe but is considered legacy. It does not allow null values or keys.

10. Explain the difference between equals() and == in Java for comparing objects?

Answer: equals() is a method used to compare the content or values of two objects. It’s typically overridden in custom classes to provide meaningful comparison.
== is an operator used to compare object references, checking if they point to the same memory location. It tests for reference equality.

11. How does garbage collection work in Java, and what are the different generations in the Java heap?

Answer: Garbage collection is the process of automatically reclaiming memory from objects that are no longer reachable. In Java, the heap is divided into three generations: Young, Old, and Permanent. New objects are created in the Young generation and, if they survive multiple collections, are promoted to the Old generation.

12. What is the difference between ArrayList and LinkedList in Java, and when would you use each?

Answer: ArrayList is implemented as a dynamic array and is good for random access. Use it when you need fast retrieval but can tolerate slower insertions and deletions.
LinkedList is implemented as a doubly-linked list and is suitable for frequent insertions and deletions but slower for random access. Use it when you need fast insertions and deletions.

13. Explain the concept of method overloading and method overriding in Java.

Answer: Method overloading involves defining multiple methods in the same class with the same name but different parameters. The compiler determines which method to call based on the method’s signature.
Method overriding occurs in a subclass, where a method with the same name and parameters as the superclass method is provided. It allows you to provide a specialized implementation in the subclass.

14. What are the practical benefits, if any, of importing a specific class rather than an entire package (e.g. import java.net.* versus import java.net.Socket)?

Answer: It makes no difference in the generated class files since only the classes that are actually used are referenced by the generated class file. There is another practical benefit to importing single classes, and this arises when two (or more) packages have classes with the same name. Take java.util.Timer and javax.swing.Timer, for example. If I import java.util.* and javax.swing.* and then try to use “Timer”, I get an error while compiling (the class name is ambiguous between both packages). Let’s say what you really wanted was the javax.swing.Timer class, and the only classes you plan on using in java.util are Collection and HashMap. In this case, some people will prefer to import java.util.Collection and import java.util.HashMap instead of importing java.util.*. This will now allow them to use Timer, Collection, HashMap, and other javax.swing classes without using fully qualified class names in.

15. How is multithreading achieved in Java, and what are the differences between extending the Thread class and implementing the Runnable interface for creating threads?

Answer: Multithreading in Java is achieved by extending the Thread class or implementing the Runnable interface. Extending Thread limits the ability to extend other classes, while implementing Runnable allows for more flexibility and sharing between threads.

16. What is the purpose of the transient and volatile keywords in Java?

Answer:  Transient is used to indicate that a variable should not be serialized when an object is converted to a byte stream.
volatile is used to declare a variable as “volatile,” ensuring that multiple threads always read and write its value directly from and to main memory, rather than caching it locally.

17. What is the difference between an if statement and a switch statement?

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

18. What is the difference between == and .equals() in Java for comparing objects?

Answer:  == is used to compare object references, checking if they point to the same memory location.

.equals() is a method used to compare the content or values of two objects. It should be overridden in custom classes to provide meaningful content-based comparison.

19. What is the difference between the prefix and postfix forms of the ++ operator?

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

20. Which Java operator is right associative? 

Answer: The = operator is right associative.

21. Write a java class with the name Array, with instance variables lastindex to hold the index of last filled block of Array and ptr as a refernce to an array? 

Answer: Certainly, here’s the theoretical explanation of a Java class named Array with instance variables lastIndex and ptr: you can create a Java class named Array with instance variables lastIndex and ptr to represent an array. Below is the theoretical definition of the Array class:

  1. Array Class: This Java class is named Array. It serves as a blueprint for objects that represent an array structure.
  2.  lastIndex Instance Variable: lastIndex is an instance variable (field) that holds the index of the last filled block (element) in the array. It represents the position where the next element will be added.
  3.  ptr Instance Variable: ptr is an instance variable that serves as a reference to an integer array. This is where the actual elements of the array are stored. It can be considered as the underlying data structure that the Array class manages.

22. Define a constructor in Array class which takes size of an array as an argument and allocates memory for the array ?

Answer: Certainly, in the Array class, you can define a constructor that takes the size of the array as an argument and allocates memory for the array. Here’s the theoretical explanation of such a constructor:

  1. Array Class: This Java class is named Array and serves as a blueprint for objects representing an array structure.

  2. Constructor with a Size Argument: The constructor public Array(int size) is defined to accept an integer argument size. This argument represents the size of the array that the constructor should allocate memory for.

  3. Memory Allocation: Inside the constructor, memory for the array is allocated using the new operator. new int[size] allocates memory for an integer array with a size equal to the value of the size argument. This is how the array’s memory is created.

  4. lastIndex Initialization: The lastIndex instance variable is initialized to -1 within the constructor. This is typically done to indicate that the array is empty when it’s created. As elements are added to the array, lastIndex will be updated to point to the last filled block.

23. Define a method to append data in an array ?

Answer: To define a method for appending data to an array in Java, you can create a method within a class. Here’s the theoretical explanation of how to define such a method:

  1. MyArray Class: This is a custom class that represents an array. It contains instance variables data, size, and capacity. data is the array to store elements, size tracks the number of elements currently in the array, and capacity represents the maximum number of elements the array can hold.

  2. Constructor: The constructor takes a capacity parameter and initializes the data array with the specified capacity. It also sets the size to 0 since the array is initially empty.

  3. append Method: This method is defined to append (add) an integer value to the array. It checks if there is room in the array (i.e., size < capacity), and if so, it places the new value in the data array at the current size index and increments the size. If the array is full, you can handle this situation according to your specific needs, such as resizing the array or throwing an exception.

This is a basic example of how you can define a method to append data to an array in Java. You can further expand on this class by adding methods for retrieving, deleting, and performing other array operations as needed.

24. Define a method to insert data in an array ?

Answer: To define a method to insert data into an array in Java, you typically need to specify the index at which you want to insert the data, as well as the data you want to insert. Here’s the theory of defining such a method:

  1. insertData is the method name, which takes two parameters: index (the position at which you want to insert the data) and data (the value you want to insert).

  2. The method first checks if the index is within the valid range of the array. It should be between 0 and the length of the array minus one (ptr.length - 1).

  3. If the index is valid, the method shifts the existing elements to make space for the new data. It does this by iterating backward from the last index (lastIndex) to the specified index, moving each element one position to the right.

  4. After making space, it inserts the new data at the specified index, effectively “pushing” the existing data to the right.

  5. Finally, the lastIndex is updated to reflect the addition of the new element.

It’s essential to check the validity of the index to prevent out-of-bounds errors. This method allows you to insert data at a specific position in an array, effectively increasing the array’s size by one and shifting elements to accommodate the new data.

25. Define a method to edit array element of given index ?

Answer: To define a method in a Java class that edits an array element at a given index, you can add a method to your Array class. Here’s the theoretical explanation of how to define such a method:

  1. I added a new method named editElement to the Array class. This method takes two parameters: index and newValue. index specifies the index of the element you want to edit, and newValue is the new value you want to assign to that element.

  2. Inside the editElement method, it first checks if the index is within the valid range (between 0 and lastIndex). If the index is valid, it updates the element at that index with the new value newValue.

  3. If the index is not within the valid range, it prints a message indicating that the edit operation failed due to an invalid index.

You can use this editElement method to modify the value of an element in the array at a specific index.

26. Define a method to delete an element from the array at given index ?

Answer: To define a method in a Java class that deletes an element from an array at a given index, you can create a method within the Array class (as previously defined) like this:

deleteElement Method:

This method is designed to remove an element from the array at the given index.

  • int index: This method takes an index as a parameter, specifying the position of the element to be deleted.

  • Inside the method, it first checks whether the provided index is within bounds. If the index is less than 0 or greater than lastIndex (indicating an out-of-bounds index), it displays an error message.

  • If the provided index is valid, the method proceeds to remove the element at that index. It shifts the elements to the left, effectively overwriting the element at the specified index with the element in the next position and so on, until the last element is reached.

  • After the element is removed, it decrements the lastIndex to reflect the removal of one element from the array.

  • As a result, the element at the specified index is effectively deleted from the array.

You can call this method on an instance of the Array class to delete an element at a given index within the array.

27. Define a method get toatal number of elements present in the array ?

Answer: Certainly, let’s define a method called getTotalElements in a theoretical Java class named Array to calculate the total number of elements present in the array:

  1. We define a new method called getTotalElements within the Array class.

  2. Inside this method, we calculate the total number of elements in the array by adding 1 to lastIndex. This is because array indexing typically starts at 0, and lastIndex represents the index of the last filled element in the array.

  3. The method returns the calculated total, indicating how many elements are present in the array.

You can then call this method on an instance of the Array class to retrieve the total number of elements in the array.

28. Define a method to check whether an array is empty or not ?

Answer: To define a method in Java to check whether an array is empty or not, you can use the length property of the array. An array is considered empty when its length is equal to 0. Here’s the theoretical explanation of how to define such a method:

  1. Class Name: The method is defined within a class called ArrayUtils. You can place utility methods like this in a utility class to keep your code organized.

  2. Method Name: The method is named isEmptyArray.

  3. Method Signature: It takes an argument of type int[] named array, which is the array you want to check for emptiness.

  4. Method Implementation: Inside the method, it checks whether the length of the provided array (array.length) is equal to 0. If the length is 0, the array is considered empty, and the method returns true. Otherwise, it returns false.

29. Define a method to check whether an array is full or not ?

Answer: To define a method to check whether an array is full or not, you can create a method within a class that encapsulates an array. Below is the theoretical explanation of such a method:

  • The ArrayManager class contains an array field to represent the array, a lastIndex field to store the index of the last filled block, and a capacity field to define the maximum size of the array.
  • The constructor ArrayManager(int capacity) initializes the array with the specified capacity and sets lastIndex to -1, indicating an empty array.
  • The isFull() method checks if the lastIndex is equal to capacity - 1. If they are equal, it means that the array is full, and the method returns true. Otherwise, it returns false.

You can use this isFull method to determine whether the array has reached its maximum capacity or not, which can be handy when adding elements to an array to prevent overflow.

30. Define a method to get value stored at given index?

Answer:  To define a method to get the value stored at a given index in a Java class, you can add a method within the class that takes an index as a parameter and returns the value stored at that index. Here’s the theoretical explanation:

  1. getValueAtIndex Method: This is the method we are defining to get the value stored at a specific index. It takes an index as a parameter, which is the index you want to access in the array.

  2. Bounds Check: It checks if the index is within valid bounds. The index should be greater than or equal to 0 and less than or equal to the lastIndex, ensuring it’s within the range of the array’s elements.

  3. Return Value: If the index is within bounds, it returns the value stored at that index in the ptr array. This value is of type int in this example.

  4. Error Handling: If the index is out of bounds or the array is empty (indicated by lastIndex being -1), you can handle this situation by throwing an exception (in this case, an IllegalArgumentException is thrown). You can customize the error handling as needed.

By adding the getValueAtIndex method to your Array class, you enable the retrieval of values at specific positions in the array, making it a useful feature for working with array data.

31. Define a method to get capacity of the array ?

Answer: To define a method in a Java class named Array to get the capacity (maximum size) of the array, you can add a method like this:

getCapacity Method:

  • This method is added to the Array class to allow external code to retrieve the maximum capacity (size) of the array.
  • It returns an integer value representing the capacity of the array.
  • The capacity of the array is determined by the length of the ptr array, which is the reference to the underlying array structure.
  • The length property of the array in Java provides the number of elements it can hold, which is equivalent to the maximum capacity.

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

Answer:  A 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.

33. What is the ‘this’ keyword in Java ?

Answer: ‘this’ refers to the current instance of the class. It is a reference variable used to refer to the current object in methods and constructors.

34. Are JVM’s platform independent?

Answer: JVM’s are not platform independent. JVM’s are platform specific run time implementation provided by the vendor.

35. What is a pointer and does java support pointers?

Answer: Pointer is a reference handle to a memory location. Improper handling of pointers leads to memory leaks and reliability issues hence Java doesn’t support the usage of pointers.

36. What is difference between Path and Classpath?

Answer: Path and Classpath are operating system level environment variales. Path is used define where the system can find the executables(.exe) files and classpath is used to specify the location .class files.

37. What are local variables ?

Answer: Local varaiables are those which are declared within a block of code like methods. Local variables should be initialised before accessing them.

38. What are instance variables?

Answer: Instance variables are those which are defined at the class level. Instance variables need not be initialized before using them as they are automatically initialized to their default values.

39. How to define a constant variable in Java?

Answer: The variable should be declared as static and final. So only one copy of the variable exists for all instances of the class and the value can’t be changed also.

static final int MAX_LENGTH = 50; is an example for constant.

40. Should a main() method be compulsorily declared in all java classes?

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

41. What is the return type of the main() method?

Answer: Main() method doesn’t return anything hence declared void.

42. What is the arguement of main() method?

Answer: main() method accepts an array of String object as arguement.

43. Can a main() method be declared final?

Answer: Yes. Any inheriting class will not be able to have it’s own default main() method.

44. Does the order of public and static declaration matter in main() method?

Answer: No. It doesn’t matter but void should always come before main().

45. Can a source file contain more than one class declaration?

Answer: Yes a single source file can contain any number of Class declarations but only one of the class can be declared as public.

46. What is a package?
 

Answer: Package is a collection of related classes and interfaces. package declaration should be first statement in a java class.

47. Which package is imported by default?

Answer:  java.lang package is imported by default even without a package declaration. 

48. Can a class be declared as protected?

Answer: The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected.

49. Can a for statement loop indefinitely?

Answer: Yes, a for statement can loop indefinitely. For example, consider the following: for(;;);

50. What is the purpose of declaring a variable as final?

Answer:final variable’s value can’t be changed. final variables should be initialized before using them.

51. What is the impact of declaring a method as final?

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

52. I don’t want my class to be inherited by any other class. What should i do?

Answer: You should declared your class as final. But you can’t define your class as final , if it is an abstract class. A class declared as final can’t be extended by any other class.

53. I want to print “Hello” even before main() is executed. How will you acheive that?
 

Answer: Print the statement inside a static block of code. Static blocks get executed when the class gets loaded into the memory and even before the creation of an object. Hence it will be executed before the main() method. And it will be executed only once.

54. Can we declare a static variable inside a method?

Answer: Static varaibles are class level variables and they can’t be declared inside a method. If declared, the class will not compile.

55. What is an Abstract Class and what is it’s purpose ?

Answer: A Class which doesn’t provide complete implementation is defined as an abstract class. Abstract classes enforce abstraction.

56. Can a abstract class be declared final?

Answer: Not possible. An abstract class without being inherited is of no use and hence will result in compile time error.

57. What is use of a abstract variable ?

Answer: Variables can’t be declared as abstract. only classes and methods can be declared as abstract.

58. Can you create an object of an abstract class?

Answer: Not possible. Abstract classes can’t be instantiated.

59. Can a abstract class be defined without any abstract methods?

Answer: Yes it’s possible. This is basically to avoid instance creation of the class.

60. Class C implements Interface I containing method m1 and m2 declarations. Class C has provided implementation for method m2. Can i create an object of Class C?

Answer:  No not possible. Class C should provide implementation for all the methods in the Interface I. Since Class C didn’t provide implementation for m1 method, it has to be declared as abstract. Abstract classes can’t be instantiated.

61. Can a method inside a Interface be declared as final?

Answer: No not possible. Doing so will result in compilation error. public and abstract are the only applicable modifiers for method declaration in an interface.

62. Can an Interface implement another Interface?

Answer: Intefaces doesn’t provide implementation hence a interface cannot implement another interface.

63. Can an Interface extend another Interface?

Answer: Yes an Interface can inherit another Interface, for that matter an Interface can extend more than one Interface.

64. Can a Class extend more than one Class?

Answer: Not possible. A Class can extend only one class but can implement any number of Interfaces.

65. What is the difference between the >> and >>> operators?

Answer: The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out.

66. Is sizeof a keyword?

Answer: The sizeof operator is not a keyword.

67. What is a Marker Interface?
 

Answer:  An Interface which doesn’t have any declaration inside but still enforces a mechanism.

68. Why does Java not support operator overloading?

Answer: Operator overloading makes the code very difficult to read and maintain. To maintain code simplicity, Java doesn’t support operator overloading.

69. What is Externalizable?

Answer: Externalizable is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in)

70. What modifiers are allowed for methods in an Interface?

Answer: Only public and abstract modifiers are allowed for methods in interfaces.

71. What is a member and a class variable?

Answer:  Variables declared within the class i.e not within any methods are “member” variables (global variables).

Variables declared within the class i.e not within any methods and are defined as “static” are class variables.

72. What value does read() return when it has reached the end of a file?

Answer: The read() method returns -1 when it has reached the end of a file.

73. Can a Byte object be cast to a double value?

Answer: No, an object cannot be cast to a primitive value.

74. What is an object’s lock and which object’s have locks?
 

Answer: An object’s lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object’s lock. All objects and classes have locks. A class’s lock is acquired on the class’s Class object.

 

75. What is the % operator?

Answer: It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand by the second operand.

76. When can an object reference be cast to an interface reference?

Answer:  An object reference be cast to an interface reference when the object implements the referenced interface.

77. Which non-Unicode letter characters may be used as the first character of an identifier?

Answer: The non-Unicode letter characters $ and _ may appear as the first character of an identifier

78. What is casting?

Answer: There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.

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

Answer: this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.

80. If a variable is declared as private, where may the variable be accessed?

Answer: A private variable may only be accessed within the class in which it is declared.

81. What do you understand by private, protected and public?

Answer: These are accessibility modifiers. Private is the most restrictive, while public is the least restrictive. There is no real difference between protected and the default type (also known as package protected) within the context of the same package, however the protected keyword allows visibility to a derived class in a different package.

82. What is Downcasting ?

Answer: Downcasting is the casting from a general to a more specific type, i.e. casting down the hierarchy

83. What modifiers may be used with an inner class that is a member of an outer class?

Answer:  A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.

84. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?

Answer: Unicode requires 16 bits and ASCII require 7 bits Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits.

UTF-8 represents characters using 8, 16, and 18 bit patterns.

UTF-16 uses 16-bit and larger bit patterns.

85. What restrictions are placed on the location of a package statement within a source code file?

Answer: A package statement must appear as the first line in a source code file (excluding blank lines and comments).

86. Why is native method ?

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

87. What are order of precedence and associativity, and how are they used?

Answer: Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left.

88. Can an anonymous class be declared as implementing an interface and extending a class?
 

Answer: An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.

89. What is the range of the char type?

Answer: The range of the char type is 0 to 216 – 1 (i.e. 0 to 65535.)

90. What is the range of the short type?

Answer:  The range of the short type is -(215) to 215 – 1. (i.e. -32,768 to 32,767)

91. Is the ternary operator written x:y ? z or x ? y:z ?

Answer:  It is written x ? y : z.

 

92. If a class is declared without any access modifiers, where may the class be accessed?

Answer: A class that is declared without any access modifiers is said to have package access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package.

93. Does a class inherit the constructors of its superclass?

Answer:  A class does not inherit constructors from any of its superclasses.

94. Name the eight primitive Java types.

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

95. What restrictions are placed on the values of each case of a switch statement?
 

Answer:  During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value.

 

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

Answer: A local inner class may be final or abstract.

97. If a method is declared as protected, where may the method be accessed?

Answer:  A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.

98. What are the legal operands of the instanceof operator?
 

Answer:  The left operand is an object reference or null value and the right operand is a class, interface, or array type.

 

99. What is numeric promotion?

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

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

Answer:  The default value of the boolean type is false.

101. What is a Java Applet?

Answer: A Java Applet is a small Java program that runs within a web browser. It’s designed to be embedded in web pages and executed on the client-side.

102. How is a Java Applet different from a Java application?

Answer: AJava Applets run in a web browser, whereas Java applications are standalone programs executed on a local machine. Applets are subject to certain security restrictions imposed by browsers.

103. What are the primary components of a Java Applet?

Answer: Java Applets typically consist of three essential methods: init(), start(), and paint(). The init() method is used for initialization, start() for starting the applet, and paint() for rendering graphics.

104. What is the purpose of the init() method in an Applet?

Answer: The init() method is used for one-time initialization of an applet. It is called when the applet is first loaded into memory. This is where you typically set up initial variables and resources.

105. Explain the role of the start() method in an Applet?
 

Answer: The start() method is called after init() and is used to start or resume the execution of an applet. It is invoked every time the web page containing the applet is revisited.

106.What is the life cycle of a Java applet?

Answer: The life cycle of a Java applet involves methods like init(), start(), stop(), and destroy(). These methods are called at different stages of the applet’s execution.

107. What is the Java Applet Security Model?

Answer: The Java Applet Security Model restricts applets from performing potentially harmful operations like accessing the local file system or making network connections to domains other than the one the applet came from. Applets are also subject to digital signatures and permissions.

108. Why did Java applets decline in popularity?

Answer: Java applets declined due to several reasons, including security concerns, the need for the Java plugin in browsers, and the emergence of more modern web technologies like JavaScript and HTML5.

109. Can you still run Java applets in modern web browsers?

Answer: As of my last knowledge update in September 2021, many modern web browsers have deprecated or completely removed support for Java applets due to security concerns. It’s unlikely that you can run Java applets in most current browsers.

110. What is the future of Java applets, if any?
 

Answer: Java applets are largely considered a deprecated technology. It’s unlikely they will see a resurgence in the future, and developers are encouraged to use alternative web technologies for creating interactive content.

111.What is Java bytecode?

Answer: Java bytecode is an intermediate representation of a Java program that is generated by the Java compiler. It is a low-level platform-independent binary code that can be executed by the Java Virtual Machine (JVM).

112. Why is Java bytecode used in Java?

Answer: Java bytecode serves as an intermediary step between Java source code and machine code. It allows Java programs to be platform-independent, as the same bytecode can be executed on any platform that has a compatible JVM.

113. How is Java bytecode executed?

Answer: Java bytecode is executed by the Java Virtual Machine (JVM). The JVM loads the bytecode, interprets it, and executes the corresponding instructions on the host machine.

114. Can you decompile Java bytecode back into Java source code?

Answer: Yes, it is possible to decompile Java bytecode back into Java source code using tools like JD-GUI, JAD, or JADX. However, the decompiled code may not be identical to the original source code, and it may lose some high-level abstractions.

115. What is the file extension for compiled Java bytecode files?
 

Answer: The compiled Java bytecode files have a “.class” extension. For example, if you have a Java class named “MyClass,” the bytecode file will be “MyClass.class.”

116. What are the advantages of using bytecode in Java?

Answer: The advantages of bytecode in Java include platform independence, security (bytecode can be verified by the JVM before execution), and ease of distribution (you can distribute compiled bytecode instead of source code).

117. What is the Java Virtual Machine (JVM), and how does it relate to bytecode?

Answer: The JVM is the runtime environment that executes Java bytecode. It loads bytecode from .class files, verifies it, and runs the program. It abstracts the underlying hardware and provides platform independence.

118. How can you view the bytecode of a Java class file?

Answer: You can use tools like javap (Java Class File Disassembler) to view the bytecode of a Java class file. The javap command displays the bytecode instructions and other information contained in the .class file.

119. What are some common bytecode instructions used in Java?

Answer: Common bytecode instructions include aload, invokevirtual, ifne, return, and many others. Each bytecode instruction performs a specific operation, such as loading a variable, invoking a method, or branching in control flow.

120. How is Java bytecode different from machine code?
 

Answer: Machine code is specific to a particular hardware architecture, whereas Java bytecode is designed to be executed by the JVM, which is platform-independent. Machine code is binary and low-level, while Java bytecode is a human-readable, stack-based language.

121. What are the four main buzzwords associated with Java?

Answer: The four main buzzwords associated with Java are “Platform-Independent,” “Object-Oriented,” “Robust,” and “Secure.”

122. Explain the “Platform-Independent” buzzword in Java ?

Answer: Java is platform-independent because it uses the concept of “Write Once, Run Anywhere” (WORA). This means that Java code can be written on one platform and executed on any other platform without modification. Java achieves platform independence by compiling source code into an intermediate form called bytecode, which is executed by the Java Virtual Machine (JVM) on different platforms.

123. What does “Robust” mean in the context of Java?

Answer: “Robust” in Java means that the language is designed to be reliable and capable of handling errors gracefully. Java enforces strong type checking, automatic memory management (garbage collection), and exception handling, which reduces the likelihood of runtime errors and crashes. This robustness contributes to the stability of Java applications.

124. Explain the “Secure” aspect of Java ?

Answer: Java is considered a secure language because it includes multiple security features. Some of these features include a secure runtime environment provided by the JVM, a strong type system to prevent buffer overflow and other vulnerabilities, and a security manager that controls access to system resources. Java applets, for example, run in a restricted sandbox to prevent them from causing harm to the host system.

125. Can you name any other Java buzzwords besides the four main ones?
 

Answer: Yes, in addition to the four main buzzwords, there are other Java buzzwords like “Multithreaded,” “Distributed,” and “Dynamic.” Java supports multithreading for concurrent execution, it can be used to build distributed applications through technologies like RMI and CORBA, and it offers dynamic memory allocation through garbage collection.

126. Explain the Java Compiler ?

Answer: The Java Compiler, often referred to as javac, is a part of the JDK. Its primary function is to translate Java source code into bytecode. This bytecode is a platform-independent intermediate code that can be executed on any platform with a compatible JVM. The Java Compiler performs syntax checking and generates class files containing bytecode.

127. What is JIT compilation, and how does it work?

Answer: JIT (Just-In-Time) compilation is a technique used by the JVM to improve the performance of Java applications. Instead of interpreting bytecode line by line, the JVM can dynamically compile bytecode into native machine code at runtime. This compiled code is then executed directly by the CPU, which is much faster than interpreting bytecode. JIT compilation optimizes the performance of Java applications by identifying frequently executed code and compiling it for efficient execution.

128. What is the purpose of the java command?

Answer: The java command is used to launch Java applications. It takes the name of the main class (containing the public static void main(String[] args) method) as an argument and starts the JVM, which loads the bytecode of the specified class and begins execution.

129. How does the JVM manage memory?

Answer: The JVM manages memory using several components, including the heap, method area, stack, and native method stack. The heap is used for object allocation and garbage collection. The method area stores class structures and static fields. The stack holds method-specific data, while the native method stack is used for native method calls. Garbage collection is responsible for reclaiming memory from objects that are no longer in use.

130. What are the different types of class loaders in Java?
 

Answer: In Java, there are three types of class loaders:

  • Bootstrap Class Loader: This is responsible for loading core Java classes as part of the JRE.
  • Extension Class Loader: It loads classes from the extensions directory.
  • Application Class Loader: It loads classes from the application classpath.

131. What significant changes were introduced in Java 5 (Java 1.5)?

Answer: Java 5 introduced several important features, such as Generics, Metadata Annotations, Enumerations, the enhanced for loop, and the varargs (variable-length argument lists). Generics allowed for type-safe collections and improved code readability, while Annotations enabled developers to add metadata to their code for improved compile-time and runtime analysis.

132. What is the module system introduced in Java 9, and why was it important?

Answer: Java 9 introduced the Java Platform Module System (JPMS) to modularize the Java SE platform and applications. This system allowed developers to create modular applications, improving maintainability, security, and performance. It also addressed the “JAR hell” problem and made it easier to manage dependencies.

133. What were some notable features in Java 11?

Answer: Java 11, following the new release cadence, was a long-term support (LTS) release. Some key features and changes included:

  • Local-Variable Syntax for Lambda Parameters: Simplified lambda expressions by using the var keyword for parameters.
  • HTTP Client: A new HTTP client API was introduced for making HTTP requests.
  • Flight Recorder: The Flight Recorder tool was made available in the OpenJDK, providing enhanced performance monitoring and analysis.

134. What are the major versions of Java, and can you name a few of them?

Answer: Java has several major versions, including Java 1.0, Java 1.1, Java 1.2 (also known as Java 2), Java 1.3, Java 1.4, Java 5 (or Java 1.5), Java 6, Java 7, Java 8, Java 9, Java 10, Java 11, Java 12, Java 13, Java 14, Java 15, Java 16, and so on. Each version brought various improvements and new features.

135. What is the difference between Java 11 and Java 12 in terms of features and changes?
 

Answer: Java 12 brought incremental changes over Java 11. Some features included:

  • Switch Expressions: Enhanced switch statements to become expressions, allowing them to return a value.
  • Shenandoah Garbage Collector: Introduced as an experimental feature for low-pause-time garbage collection.
  • Preview Features: Java 12 included preview features like ‘Switch Expressions’ and ‘Raw String Literals,’ which were considered for future inclusion.

136. What does the “synchronized” keyword do in Java?

Answer:  The “synchronized” keyword is used to create synchronized blocks or methods, which help in achieving thread safety in a multithreaded environment. It ensures that only one thread can execute the synchronized code block or method at a time, preventing race conditions.

137. How do you install Java on your PC?

Answer:  To install Java on your PC, you can follow these steps:

  1. Download the JDK (Java Development Kit): Go to the Oracle website or the OpenJDK website (whichever version you prefer) and download the appropriate JDK for your operating system (Windows, macOS, or Linux).

  2. Run the Installer: Once the JDK installer is downloaded, run it by double-clicking on the executable file.

  3. Follow the Installation Wizard: The installer will guide you through the installation process. You may need to accept the license agreement and choose the installation directory. It’s a good practice to keep the default installation options, as they are usually set up correctly.

  4. Set Environment Variables (Optional): You can set environment variables like JAVA_HOME and add the bin directory of the JDK to your system’s PATH environment variable. This step is optional but can be useful for command-line development.

  5. Verify the Installation: Open a command prompt or terminal and type java -version to check if Java is installed correctly. It should display the version of Java that you installed.

  6. Install an Integrated Development Environment (IDE) (Optional): If you plan to develop Java applications, you may want to install an IDE like Eclipse, IntelliJ IDEA, or NetBeans to simplify the development process.

138. What is throw keyword ?

Answer: Throw keyword is used to throw the exception manually. It is mainly used when the program fails to satisfy the given condition and it wants to warn the application.The exception thrown should be subclass of Throwable.

139. What is a strictfp modifier ?

Answer: Strictfp is used with variable only . It is used to restrict floating point calculations ( fp ) to ensure portability ( platform Independent ). When this modifier is specified, the JVM adheres to the Java specifications ( IEEE-754 floating-point specification ) and returns the consistent value independent of the platform. That is, if you want the answers from your code (which uses floating point values) to be consistent in all platforms, then you need to specify the strictfp modifier.

140. Why static methods cannot access non static variables or methods ?
 

Answer:  A static method cannot access non static variables or methods because static methods can be accessed without instantiating the class, so if the class is not instantiated the variables are not intialized and thus cannot be accessed from a static method.

141. What is the purpose of the javac command?

Answer: The javac command is used to compile Java source code into bytecode. It checks the source code for syntax errors and produces a compiled .class file if the code is error-free.

142. Explain the difference between primitive data types and reference data types in Java.

Answer: 

  • Primitive data types store actual values, while reference data types store references (memory addresses) to objects.
  • Primitive data types are predefined in Java, while reference data types are created by the user (usually as objects).
  • Primitive data types are stored on the stack, while reference data types are stored on the heap.
  • Primitive data types have default values (e.g., 0 for int), while reference data types have a default value of “null.”

143. What is the size of the int data type in Java?

Answer: TThe int data type in Java is 4 bytes (32 bits).

144. How do you declare a character data type in Java, and what does it store?

Answer: You can declare a character data type in Java using the char keyword. It stores a single 16-bit Unicode character.

145. What is the difference between float and double data types in Java ?
 
Answer:
  • float is a 32-bit single-precision floating-point data type, while double is a 64-bit double-precision floating-point data type.
  • double provides higher precision and can represent a wider range of values compared to float.

146. What is the difference between int and Integer in Java?

Answer:  int is a primitive data type, whereas Integer is a wrapper class for the primitive type int. Integer class allows you to use int data in an object-oriented context. It also provides useful methods for performing operations on int values.

147. Explain the ‘char’ data type in Java.

Answer:  The char data type in Java is a 16-bit Unicode character. It represents a single character and is used to store characters such as letters, digits, and symbols. Char data type is denoted by a single quote, for example, ‘A’.

148. What is autoboxing and unboxing in Java?

Answer: Autoboxing is the process of converting a primitive data type to its corresponding wrapper class object (e.g., int to Integer). Unboxing is the reverse process, where the wrapper class object is converted back to its primitive data type. Java automatically performs these conversions.

149. Explain the ‘double’ data type in Java ? 

Answer: The double data type in Java is a 64-bit double-precision floating-point. It is used to store decimal numbers with higher precision than float. Double data type is useful when fractional precision calculation is required.

150. How do you convert a string to an int in Java ?
 

Answer: You can convert a string to an int in Java using the parseInt() method of the Integer