Java Interview Questions

Java Interview Questions

  1. How can you change the array length in Java?

    • Answer: You need to create a new array with the desired length and copy the elements from the old array to the new array.
  2. Write a function to find the length of a string without using an inbuilt function.

    • Answer: You can convert the string into a character array and count the number of elements in the array.
  3. What is the difference between StringBuilder and StringBuffer?

    • Answer: StringBuilder is not thread-safe, while StringBuffer is thread-safe. StringBuilder is more efficient for single-threaded environments.
  4. How do you convert a string to an integer in Java?

    • Answer: You can use the Integer.parseInt() method or the Integer.valueOf() method to convert a string to an integer.
  5. What is autoboxing and unboxing in Java?

    • Answer: Autoboxing is the automatic conversion of a primitive type to its corresponding wrapper class, while unboxing is the opposite conversion.
  6. How can you reverse a string in Java?

    • Answer: You can convert the string to a character array, swap the characters from both ends, and convert it back to a string.
  7. What is the difference between equals() and == in Java?

    • Answer: equals() compares the values of objects, while == compares the references of objects.
  8. How do you find the maximum and minimum values in an integer array?

    • Answer: You can iterate through the array and keep track of the maximum and minimum values.
  9. Explain the difference between ArrayList and LinkedList in Java.

    • Answer: ArrayList is implemented as a dynamic array, while LinkedList is implemented as a doubly-linked list. ArrayList provides better performance for random access, while LinkedList is better for frequent insertion and deletion.
  10. How can you remove duplicates from an ArrayList in Java?

    • Answer: You can iterate through the ArrayList and add elements to a new ArrayList only if they are not already present.
  11. What is the difference between String, StringBuilder, and StringBuffer in Java?

    • Answer: String is immutable, while StringBuilder and StringBuffer are mutable. StringBuilder is not thread-safe, while StringBuffer is thread-safe.
  12. How can you sort an array in Java?

    • Answer: You can use the Arrays.sort() method to sort an array in Java.
  13. Explain the difference between a shallow copy and a deep copy.

    • Answer: A shallow copy creates a new object that references the same memory as the original object. A deep copy creates a new object with its own memory, and it copies the values of the original object's fields.
  14. How do you find the second-largest element in an array?

    • Answer: You can iterate through the array and keep track of the largest and second-largest elements.
  15. Explain the concept of wrapper classes in Java.

    • Answer: Wrapper classes are used to convert primitive data types into objects. They provide utility methods and allow primitive types to be used in collections and with other APIs that require objects.
  16. What is the difference between HashMap and HashTable in Java?

    • Answer: HashMap is not synchronized and allows null values, while HashTable is synchronized and does not allow null values.
  17. How can you check if a string contains only digits?

    • Answer: You can use the matches() method with a regular expression like str.matches("\\d+") to check if a string contains only digits.
  18. Explain the difference between the Comparable and Comparator interfaces. - Answer: The Comparable interface is implemented by a class to define its natural ordering. The Comparator interface is used to define custom ordering for classes that you cannot modify or when multiple ordering options are needed.

  19. How can you convert an ArrayList to an array in Java?

    • Answer: You can use the toArray() method to convert an ArrayList to an array.
  20. What is the purpose of the finalize() method in Java?

    • Answer: The finalize() method is called by the garbage collector before an object is garbage collected. It allows an object to clean up any resources it holds before being destroyed.
  21. Explain the difference between stack and heap memory in Java.

    • Answer: Stack memory is used for storing method frames, local variables, and method calls, while heap memory is used for storing objects.
  22. How can you check if two strings are anagrams?

    • Answer: You can compare the sorted versions of the two strings to check if they contain the same characters.
  23. Explain the difference between StringBuffer and StringBuilder in terms of performance.

    • Answer: StringBuilder provides better performance than StringBuffer in single-threaded environments because it is not synchronized.
  24. What is the difference between a deep clone and a shallow clone?

    • Answer: A deep clone creates a new object with its own memory and recursively clones all objects referenced by the original object. A shallow clone creates a new object that references the same memory as the original object.
  25. How can you convert an integer to a string in Java?

    • Answer: You can use the String.valueOf() method or concatenate the integer with an empty string to convert it to a string.
  26. Explain the difference between ArrayList and Vector in Java.

    • Answer: ArrayList is not synchronized and provides better performance, while Vector is synchronized and provides thread-safety.
  27. How do you find the common elements between two arrays?

    • Answer: You can iterate through one array and check if each element is present in the other array.
  28. What is the difference between compareTo() and equals() methods in Java?

    • Answer: compareTo() compares two objects based on their natural ordering, while equals() compares the equality of two objects.
  29. How can you convert a string to a character array in Java?

    • Answer: You can use the toCharArray() method to convert a string to a character array.
  30. What is the difference between int and Integer in Java?

    • Answer: int is a primitive data type, while Integer is a wrapper class that wraps the int primitive.
  31. Explain the concept of method overloading in Java.

    • Answer: Method overloading allows a class to have multiple methods with the same name but different parameters.
  32. How do you find the sum of all elements in an array?

    • Answer: You can iterate through the array and add each element to a sum variable.
  33. What is the difference between a static method and an instance method in Java?

    • Answer: A static method belongs to the class itself and can be called without creating an instance of the class. An instance method belongs to an instance of the class and can only be called on an object.
  34. How can you find the largest and smallest numbers in an ArrayList?

    • Answer: You can iterate through the ArrayList and keep track of the largest and smallest numbers.
  35. Explain the concept of method overriding in Java.

    • Answer: Method overriding allows a subclass to provide a specific implementation of a method that is

already defined in its superclass.

  1. How do you find the middle element of a singly linked list in one pass?

    • Answer: You can use two pointers, one moving at twice the speed of the other. When the faster pointer reaches the end, the slower pointer will be at the middle.
  2. What is the difference between Arrays.asList() and ArrayList in Java?

    • Answer: Arrays.asList() returns a fixed-size list backed by an array, while ArrayList is a dynamically resizable array-based implementation of the List interface.
  3. How can you remove an element from an ArrayList in Java?

    • Answer: You can use the remove() method and specify the index or object to be removed.
  4. Explain the difference between checked and unchecked exceptions in Java.

    • Answer: Checked exceptions are checked at compile-time and must be declared or caught, while unchecked exceptions do not require such handling.
  5. How do you find the first non-repeated character in a string?

    • Answer: You can iterate through the string, use a map to count the occurrences of each character, and find the first character with a count of 1.
  6. What is the difference between the List and Set interfaces in Java?

    • Answer: List is an ordered collection that allows duplicate elements, while Set is an unordered collection that does not allow duplicate elements.
  7. How can you convert a string to uppercase or lowercase in Java?

    • Answer: You can use the toUpperCase() method or toLowerCase() method to convert a string to uppercase or lowercase, respectively.
  8. Explain the difference between poll() and remove() methods in Java PriorityQueue.

    • Answer: Both methods remove the head of the PriorityQueue. However, poll() returns null if the queue is empty, while remove() throws an exception.
  9. How do you find the frequency of each element in an array?

    • Answer: You can use a map to store the elements as keys and their frequencies as values while iterating through the array.
  10. Explain the concept of inner classes in Java.

    • Answer: Inner classes are classes defined within other classes. They have access to the enclosing class's members and can be used to logically group related classes together.
  11. How can you convert a string to an integer without using the built-in methods?

    • Answer: You can iterate through the characters of the string, convert each character to its numeric value, and calculate the final integer.
  12. What is the difference between the LinkedList and ArrayList classes in Java?

    • Answer: LinkedList is implemented as a doubly-linked list, while ArrayList is implemented as a dynamic array. LinkedList provides better performance for frequent insertion and deletion, while ArrayList provides better performance for random access.
  13. How do you remove a specific element from an array?

    • Answer: You can iterate through the array, find the index of the element to be removed, and shift the subsequent elements to fill the gap.
  14. Explain the concept of method chaining in Java.

    • Answer: Method chaining is a technique where multiple methods are called on the same object in a single statement, with each method returning the modified object.
  15. How can you find the duplicate elements in an array?

    • Answer: You can use a set to keep track of unique elements while iterating through the array. If an element is already present in the set, it is a duplicate.
  1. What is the difference between Stack and Queue in Java?

    • Answer: Stack is a Last-In-First-Out (LIFO) data structure, while Queue is a First-In-First-Out (FIFO) data structure.
  2. How do you reverse an integer in Java?

    • Answer: You can convert the integer to a string, reverse the characters of the string, and convert it back to an integer.
  3. What is the difference between HashSet and TreeSet in Java?

    • Answer: HashSet is an unordered collection that does not allow duplicate elements, while TreeSet is a sorted collection that does not allow duplicate elements.
  4. Explain the concept of method hiding in Java.

    • Answer: Method hiding occurs when a subclass defines a static method with the same signature as a static method in its superclass. The subclass method is invoked instead of the superclass method.
  5. How can you find the middle element of a linked list in Java?

    • Answer: You can use two pointers, one moving at twice the speed of the other, until the faster pointer reaches the end. The slower pointer will be at the middle element.
  6. What is the difference between a deep copy and a shallow copy of an object?

    • Answer: A deep copy creates a new object with its own memory and recursively copies all objects referenced by the original object. A shallow copy creates a new object that references the same memory as the original object.
  7. How do you check if a string is a palindrome in Java?

    • Answer: You can compare the characters from both ends of the string and check if they are equal. If all characters match, the string is a palindrome.
  8. Explain the concept of method reference in Java.

    • Answer: Method reference is a shorthand syntax for lambda expressions that allows you to refer to an existing method by name instead of providing a lambda body.
  9. How can you find the maximum and minimum values in a collection using the Stream API in Java?

    • Answer: You can use the max() and min() methods of the Stream class, along with appropriate comparators, to find the maximum and minimum values in a collection.
  10. What is the difference between the Comparator and Comparable interfaces in Java?

    • Answer: The Comparator interface is used to define custom sorting order for objects that you cannot modify. The Comparable interface is implemented by a class to define its natural ordering.
  11. How do you convert a string to a date in Java?

    • Answer: You can use the SimpleDateFormat class to parse a string into a Date object, based on a specified date format.
  12. Explain the concept of anonymous inner classes in Java.

    • Answer: Anonymous inner classes are inner classes without a name, typically used when you need to create a class instance only once and don't want to define a separate class.
  13. How can you find the intersection of two arrays in Java?

    • Answer: You can convert the arrays to Set objects, then use the retainAll() method to retain only the common elements.
  14. What is the difference between Arrays and Collections in Java?

    • Answer: Arrays is a utility class that provides methods for manipulating arrays, while Collections is a utility class that provides methods for manipulating collections.
  15. How do you find the second-smallest element in an array?

    • Answer: You can iterate through the array and keep track of the smallest and second-smallest elements.
  16. Explain the concept of thread synchronization in Java.

    • Answer: Thread synchronization is the mechanism used to control the access of multiple threads to shared resources to avoid race conditions and ensure data integrity.
  17. How can you sort a collection in reverse order using the Comparator interface in Java?

    • Answer: You can use the Collections.reverseOrder() method in conjunction with the Comparator interface to sort a collection in reverse order.
  18. What is the difference between a HashSet and a LinkedHashSet in Java?

    • Answer: HashSet is an unordered collection that does not allow duplicate elements, while LinkedHashSet maintains the insertion order of elements.
  19. Explain the concept of varargs in Java.

    • Answer: Varargs (variable arguments) allow a method to accept a variable number of arguments of the same type. They are represented using an ellipsis (...) in the method declaration.
  20. How can you calculate the factorial of a number recursively in Java?

    • Answer: You can write a recursive method that multiplies a number by the factorial of its preceding number until reaching the base case of 1.
  21. What is the difference between Iterator and ListIterator in Java?

    • Answer: Iterator allows forward traversal and removal of elements from a collection, while ListIterator extends Iterator to allow bidirectional traversal and modification of elements.
  22. How do you remove duplicates from an array in Java without using additional data structures?

    • Answer: You can sort the array and then iterate through it, removing duplicates by comparing adjacent elements.
  23. Explain the concept of polymorphism in Java.

    • Answer: Polymorphism allows an object to take on different forms and behaviors. It enables you to write code that can work with objects of multiple types through inheritance and method overriding.
  24. How can you find the kth smallest element in an unsorted array in Java?

    • Answer: You can use various algorithms such as QuickSelect or HeapSelect to efficiently find the kth smallest element in an unsorted array.
  25. What is the difference between the Math.random() method and the Random class in Java?

    • Answer: The Math.random() method returns a random double value between 0.0 and 1.0, while the Random class provides more flexibility to generate random numbers of different types and ranges.
  26. How do you check if a number is a prime number in Java?

    • Answer: You can iterate from 2 to the square root of the number and check if any number divides it evenly. If not, it is a prime number.
  27. Explain the concept of exception handling in Java.

    • Answer: Exception handling allows you to handle and recover from runtime errors or exceptional conditions in a structured and controlled manner using try-catch-finally blocks.
  28. How can you remove all occurrences of a specific element from an ArrayList in Java?

    • Answer: You can use a loop to iterate through the ArrayList and remove any occurrence of the specified element.
  29. What is the difference between the super keyword and the this keyword in Java?

    • Answer: The super keyword refers to the superclass of the current object, while the this keyword refers to the current object itself.
  30. How do you find the most frequent element in an array in Java?

    • Answer: You can use a HashMap to store the frequency of each element while iterating through the array and find the element with the highest frequency.
  31. Explain the concept of method overloading versus method overriding in Java.

    • Answer: Method overloading allows a class to have multiple methods with the same name but different parameters. Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass.
  32. How can you create and start a new thread in Java?

    • Answer: You can create a new thread by extending the Thread class or implementing the Runnable interface, and then call the start() method to start the thread.
  33. What is the difference between the compareTo() and equals() methods in Java?

    • Answer: The compareTo() method is used for ordering objects based on their natural ordering, while the equals() method is used to compare the equality of two objects.
  34. How do you find the GCD (Greatest Common Divisor) of two numbers in Java?

    • Answer: You can use the Euclidean algorithm to repeatedly divide the larger number by the smaller number until the remainder is zero. The last non-zero remainder is the GCD.
  35. What is the difference between the File class and the Path class in Java?

    • Answer: The File class represents a file or directory path in the file system, while the Path class provides more flexible and platform-independent operations on file paths.
  36. How can you convert a string to a double in Java?

    • Answer: You can use the Double.parseDouble() method to convert a string to a double.
  37. Explain the concept of anonymous classes in Java.

    • Answer: Anonymous classes are inner classes without a name that are defined and instantiated at the same time. They are often used for one-time use when implementing interfaces or extending abstract classes.
  38. How do you find the maximum occurring character in a string in Java?

    • Answer: You can use a HashMap to store the frequency of each character while iterating through the string and find the character with the highest frequency.
  39. What is the difference between the wait() and sleep() methods in Java?

    • Answer: The wait() method is called on an object and releases the lock on the object until another thread calls notify() or notifyAll(). The sleep() method is called on the Thread class and pauses the execution of the current thread for a specified amount of time.
  40. How can you reverse a string in Java?

    • Answer: You can convert the string to a StringBuilder or StringBuffer object and use the reverse() method to reverse the characters.
  41. Explain the concept of static variables and methods in Java.

    • Answer: Static variables belong to the class rather than instances of the class, and their values are shared among all instances. Static methods belong to the class and can be called without creating an instance of the class.
  42. How do you find the missing number in an array of consecutive integers in Java?

    • Answer: You can calculate the sum of the consecutive integers using the formula (n * (n + 1)) / 2, where n is the expected length of the array. Subtract the sum of the array elements from the expected sum to find the missing number.
  43. What is the difference between the transient and volatile keywords in Java?

    • Answer: The transient keyword is used to indicate that a variable should not be serialized when an object is converted to a byte stream. The volatile keyword is used to indicate that a variable can be modified by multiple threads and its value should always be read from the main memory.
  44. How can you compare two objects for equality in Java?

    • Answer: You can override the equals() method in the class and provide your own implementation to compare the equality of the objects based on specific attributes or criteria.
  45. Explain the concept of garbage collection in Java.

  • Answer: Garbage collection is the process of automatically reclaiming memory occupied by objects that are no longer in use, freeing the programmer from manual memory management.

    1. How do you find the second-largest element in an array in Java?
  • Answer: You can iterate through the array, keep track of the largest and second-largest elements, and update them as you find larger elements.
  1. What is the difference between the StringBuilder and StringBuffer classes in Java?
  • Answer: StringBuilder is not thread-safe and has better performance, while StringBuffer is thread-safe but may be slower due to synchronization.
  1. How can you check if a string contains only numeric characters in Java?
  • Answer: You can use regular expressions or the Character.isDigit() method to check if each character in the string is a digit.
  1. Explain the concept of autoboxing and unboxing in Java.
  • Answer: Autoboxing is the automatic conversion of primitive types to their corresponding wrapper classes, and unboxing is the automatic conversion of wrapper classes to their corresponding primitive types.
  1. How can you find the length of a string without using the built-in length() method?
  • Answer: You can convert the string to a character array and iterate through it, counting the number of characters until reaching the end.
  1. Explain the concept of method overriding in Java.

    • Answer: Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass, allowing the subclass to override the behavior of the superclass method.
  2. How can you check if a string is empty or null in Java?

    • Answer: You can use the isEmpty() method to check if a string is empty, and the null check (str == null) to check if a string is null.
  3. What is the difference between the finally block and the finalize() method in Java?

    • Answer: The finally block is used in exception handling to execute code regardless of whether an exception is thrown or not. The finalize() method is called by the garbage collector before an object is garbage collected to perform any necessary cleanup actions.
  4. How do you remove leading and trailing whitespace from a string in Java?

    • Answer: You can use the trim() method to remove leading and trailing whitespace from a string.
  5. Explain the concept of composition in Java.

    • Answer: Composition is a way of combining objects by including one object inside another object, allowing the combined object to have properties and behavior from both objects.
  6. How can you check if a number is a power of two in Java?

    • Answer: You can use the bitwise AND operation (num & (num - 1) == 0) to check if a number is a power of two. If the result is zero, the number is a power of two.
  7. What is the difference between the continue and break statements in Java?

    • Answer: The continue statement is used to skip the remaining code in the current iteration of a loop and continue with the next iteration. The break statement is used to exit a loop or switch statement completely.
  8. How do you remove an element from an ArrayList in Java?

    • Answer: You can use the remove() method of the ArrayList and pass the index of the element you want to remove.
  9. Explain the concept of method chaining in Java.

    • Answer: Method chaining is a programming technique where multiple methods are called on the same object in a single line, allowing the output of one method to be used as the input for another method.
  10. What is the difference between checked and unchecked exceptions in Java?

    • Answer: Checked exceptions are checked at compile time and must be declared in the method signature or handled using try-catch blocks. Unchecked exceptions are not checked at compile time and do not require explicit handling.
  11. How can you convert a string to an integer in Java?

    • Answer: You can use the Integer.parseInt() method to convert a string to an integer.
  12. Explain the concept of method visibility modifiers in Java.

    • Answer: Method visibility modifiers (public, protected, private, and default) control the accessibility of methods in Java. They determine which classes or methods can access a particular method.
  13. How do you find the common elements between two arrays in Java?

    • Answer: You can iterate through one array and use the contains() method of the Arrays class to check if each element exists in the other array.
  14. What is the difference between the Comparable and Comparator interfaces in Java?

    • Answer: The Comparable interface is implemented by a class to define its natural ordering, while the Comparator interface is used to define custom sorting order for objects that you cannot modify.
  15. Explain the concept of method references in Java.

    • Answer: Method references are a compact way to pass a reference to a method as a functional interface, allowing you to treat a method as a lambda expression.
  16. How do you convert an ArrayList to an array in Java?

    • Answer: You can use the toArray() method of the ArrayList to convert it to an array.
  17. What is the difference between the == operator and the equals() method in Java?

    • Answer: The == operator compares the memory addresses of objects, while the equals() method compares the content or values of objects.
  18. How can you concatenate two strings in Java?

    • Answer: You can use the + operator or the concat() method to concatenate two strings.
  19. Explain the concept of method overloading in Java.

    • Answer: Method overloading allows a class to have multiple methods with the same name but different parameters, enabling methods to perform similar operations on different inputs.
  20. How do you convert a string to uppercase or lowercase in Java?

    • Answer: You can use the toUpperCase() method to convert a string to uppercase and the toLowerCase() method to convert a string to lowercase.
  21. What is the difference between the Stack class and the Queue interface in Java?

    • Answer: The Stack class represents a last-in-first-out (LIFO) data structure, while the Queue interface represents a first-in-first-out (FIFO) data structure.
  22. How can you convert an integer to a string in Java?

    • Answer: You can use the Integer.toString() method or concatenate the integer with an empty string to convert it to a string.
  23. Explain the concept of constructor overloading in Java.

    • Answer: Constructor overloading allows a class to have multiple constructors with different parameters, providing flexibility in creating objects with different initialization options.
  24. How do you find the maximum and minimum values in an array in Java?

    • Answer: You can iterate through the array and keep track of the maximum and minimum values by comparing them with each element.
  25. What is the difference between the throw and throws keywords in Java?

    • Answer: The throw keyword is used to throw an exception explicitly, while the throws keyword is used in a method signature to indicate that the method may throw one or more specified exceptions.
  26. How can you convert a char to an int in Java?

    • Answer: You can use a typecast (int) or subtract the character '0' to convert a char to an int.
  27. Explain the concept of anonymous arrays in Java.

    • Answer: Anonymous arrays are arrays that are created without explicitly specifying a variable name. They are usually used for one-time use or as arguments to methods.
  28. How do you find the index of an element in an array in Java?

    • Answer: You can use a loop to iterate through the array and compare each element with the target element to find its index.
  29. What is the difference between the System.out.println() and System.out.print() methods in Java?

    • Answer: The println() method prints the output and moves the cursor to the next line, while the print() method prints the output without moving the cursor to the next line.
  30. How can you convert a string to a character array in Java?

    • Answer: You can use the toCharArray() method to convert a string to a character array.
  31. Explain the concept of wrapper classes in Java.

    • Answer: Wrapper classes provide a way to use primitive types as objects. They wrap the primitive values and provide useful methods and functionality not available for primitive types.
  32. How do you reverse the order of elements in an array in Java? - Answer: You can use two pointers, one starting from the beginning and the other from the end, and swap the elements until the pointers meet in the middle.

  33. What is the difference between the super keyword and the this keyword in Java?

    • Answer: The super keyword refers to the superclass of a class and is used to call superclass methods or access superclass variables. The this keyword refers to the current instance of a class and is used to access instance variables or call instance methods.
  34. How can you convert a decimal to a binary number in Java?

    • Answer: You can use the Integer.toBinaryString() method to convert a decimal number to its binary representation.
  35. Explain the concept of method recursion in Java.

    • Answer: Method recursion is a programming technique where a method calls itself to solve a problem by breaking it down into smaller subproblems.
  36. How do you check if an array contains a specific value in Java?

    • Answer: You can iterate through the array and compare each element with the target value using the equals() method or the == operator.
  37. What is the difference between the private, protected, public`, and default access modifiers in Java?

    • Answer: The private access modifier restricts access to only within the same class, the protected access modifier allows access within the same package and subclasses, the public access modifier allows access from any class, and the default access modifier allows access within the same package.
  38. How can you sort an array in ascending order in Java?

    • Answer: You can use the Arrays.sort() method to sort an array in ascending order.
  39. Explain the concept of method recursion in Java.

    • Answer: Method recursion is a programming technique where a method calls itself to solve a problem by breaking it down into smaller subproblems.
  40. How do you check if an array contains a specific value in Java?

    • Answer: You can iterate through the array and compare each element with the target value using the equals() method or the == operator.
  41. What is the difference between the private, protected, public`, and default access modifiers in Java?

    • Answer: The private access modifier restricts access to only within the same class, the protected access modifier allows access within the same package and subclasses, the public access modifier allows access from any class, and the default access modifier allows access within the same package.
  42. How can you sort an array in ascending order in Java?

    • Answer: You can use the Arrays.sort() method to sort an array in ascending order.
  43. Explain the concept of encapsulation in Java.

    • Answer: Encapsulation is a principle of object-oriented programming that combines data and methods into a single unit (class), allowing control over access to the data by making it private and providing public methods to manipulate and access the data.
  44. How do you check if two arrays are equal in Java?

    • Answer: You can use the Arrays.equals() method to check if two arrays are equal.
  45. What is the difference between the HashMap and Hashtable classes in Java?

    • Answer: The HashMap class is not synchronized and allows null keys and values, while the Hashtable class is synchronized and does not allow null keys or values.
  46. How can you convert a string to a date in Java?

    • Answer: You can use the SimpleDateFormat class and its parse() method to convert a string to a date.
  47. Explain the concept of polymorphism in Java.

    • Answer: Polymorphism is the ability of an object to take on many forms. In Java, polymorphism allows objects of different classes to be treated as objects of the same superclass, enabling methods to be overridden and invoked dynamically at runtime.
  48. How do you find the factorial of a number using recursion in Java?

    • Answer: You can create a recursive method that calls itself to calculate the factorial by multiplying the number with the factorial of the number minus one.
  49. What is the difference between an interface and an abstract class in Java?

    • Answer: An interface is a contract that defines a set of methods that a class must implement, while an abstract class is a class that cannot be instantiated and can contain both method declarations and implementations.
  50. How can you read input from the user in Java?

    • Answer: You can use the Scanner class to read input from the user using methods like nextLine(), nextInt(), etc.