Java Interview Questions: The Sequel

Collections

  1. What are collections?
    • A Collection is a group of individual objects represented as a single unit. Java provides Collection Framework which defines several classes and interfaces to represent a group of objects as a single unit.
  2. What are the different types of Sets?
    • The general implementations of Set are HashSet, LinkedHashSet and TreeSet.
  3. Difference between a List and a Set?
    • List is an ordered sequence of elements; a Set is a distinct list of elements which do not maintain any order. Order in List maintains the elements insertion order.
    • List allows for duplicate elements while Set doesn’t allow for duplicate elements. If you try to insert a duplicate element in Set it will just replace the existing value instead of creating a new one.
    • List permits any number of null values, but Set will permit only one null value.
    • List can be inserted in either forward direction or backward direction while the Set can be traversed only in the forward direction.
    • List should be used for storing non-unique objects in insertion order while Set should be used to store unique objects where order is not important.
  4. How do you create an ArrayList?
    • ArrayList<String> arlist = new ArrayList<String>( );
    • Initializes an ArrayList which will accept elements of type String. You can then use the .add method to add elements to the arraylist object.
  5. How to sort an ArrayList?
    • To sort the ArrayList, you can call the Collections.sort() method passing the ArrayList object which will sort the elements alphabetically in ascending order.
  6. What is the difference between Array and ArrayList? 
    • Arrays can contain both primitives and objects where as ArrayLists can contain only object elements.
    • Arrays cannot use generics where as ArrayList allows for the use of generics to ensure type safety.
    • Array uses the assignment operator to store elements where as ArrayList uses add() to insert elements.
    • The implementation of an Array is a simple array with a fixed size, but ArrayList is implemented in the form of a dynamic sized array.
    • You can use the length variable to calculate the length of an array, but you use the size() method to calculate the size of an ArrayList.
  7. How do you create a LinkedList?
    • LinkedList<String> list=new LinkedList<String>();
    • Like with ArrayList, you can use the .add method to add elements or other methods such as .addFirst to add a element to the beginning of the LinkedList and .addLast to add an element to the end of the LinkedList.
  8. What are the differences between ArrayList and LinkedList?
    • ArrayList class can act as a list only because it implements List alone. LinkedList class can act as both a list and Queue because it implments both the List and Deque interfaces.
    • ArrayList uses a dynamic array to store elements whereas LinkedList internally uses a doubly linked list to store elements.
    • Manipulation using the ArrayList is slow because of the Array used to store the elements. If an element gets removed from the array, all of the bits have to be shifted in memory in response. Manipulation is much faster with the LinkedList because of the doubly linked list used, so no bit shifting is required in memory.
  9. When do you go for an ArrayList and when do you go for a LinkedList?
    • ArrayList is better to use when you want to store and access data but LinkedList is preferred when you want to actually alter or manipulate data.
  10. How do you create a HashMap?
    • HashMap<String, String> mapName= new HashMap<String, String>();
    • Initializes a HashMap with the key-value pair that is a string-string
    • Add keys and values with the .put method
  11. What is the difference between a LinkedList and a HashMap?
    • LinkedList maintains order because it is an implementation of the List interface whereas maintaining order of insertion is not guaranteed when using a HashMap.
    • LinkedList can have duplicates whereas HashMap cannot have duplicate Keys but can have duplicate Values
    • Different purely in purpose: LinkedList represent a sequential ordering of elements whereas HashMap represents a collection of key/value pairs.
    • When accessing elements, it’s more efficient to find a particular element in a HashMap than to do the same in a LinkedList.
  12. Does LinkedList preserve insertion order?
    • Yes due to it being an implementation of the List interface.
  13. What is the difference between HashMap and ArrayList?
    • ArrayList is based on an index which is backed by an array while the HashMap is a map data structure which retrieves stored values
    • HashMap is the implementation of the HashTable where ArrayList is a dynamic array which can resize itself
  14. What is the difference between HashMap and HashTable? 
    • HashMap will allow for one null key and multiple null values but HashTable won’t allow a null key or null value.
    • HashMap is non synchronized meaning it’s not thread safe so it cannot be shared between multiple threads without proper synchronization code while the HashTable is synchronized so it’s thread safe and can be shared between many threads.
    • HashMap is largely preferred over HashTable if thread synchronization is not needed.
  15. What is the difference between HashMap and TreeMap?
    • HashMap uses the HashTable as an underlying data structure where as the TreeMap uses the Red-Black Tree as an underlying data structure.
    • HashMap does not preserve the insertion order whereas the TreeMap does preserve insertion order.
  16. What is the difference between HashSet and TreeSet ?
    • HashSet doesn’t maintain an order of elements wheras elements in a TreeSet are sorted in ascending order by default.
    • HashSet gives better performance and is faster than TreeSet for operations.
    • HashSet allows null object but the TreeSet does not, it will throw a NullPointerException.
    • To compare two objects in the set and detect duplicates, a HashSet will use the equals() method where a TreeSet will use the compareTo() method to do the same.
  17. How do you convert a HashMap into a List?
    • The .values() method of the HashMap class returns a Collection of the values. You can also use .keys() for that matter. The ArrayList() class accepts a Collection as one of its constructors.
      • HashMap<Integer, String> map = new HashMap<Integer, String>();
      • map.put (1, “Matt”);
      • map.put (2, “Rebecca”);
      • List<String> list = new ArrayList<String>(map.values());
      • for (String s : list) { System.out.println(s); }
  18. What would happen if I had two elements with the same keys in a HashMap?
    • This is impossible as HashMap doesn’t allow duplicate keys; when you attempt to add the key again with a different value, it won’t create this duplicate it will instead replace the value of the original key instance.
  19. How do you return all the keys in HashMap?
    • You can get a set object with all key values of the HashMap by calling the keySet() method on your HashMap object.

Exceptions

  1. What are the kinds of exceptions?
    • Checked and Unchecked
  2. What are their differences?
    • Checked exceptions are checked at compile time and Unchecked which are not checked at compile time. Instead an unchecked exception is a direct sub-class of the RuntimeException class and often occurs due to bad user input, making it up to the programmer to decide how to handle these exceptions.
  3. What type of exception is the FileNotFound exception?
    • Checked
  4. Is exception a class or an interface?
    • Class
  5. How do you create a custom exception class?
    • To create a custom exception, we have to extend the java.lang.Exception class.
    • We then provide/call the parent class constructor that takes a String as error message.
  6. How to handle an exception besides a try catch block?
    • You can also handle an exception using the Throws keyword.
  7. Who handles the exception if it uses throws?
    • We can use throws keyword to delegate the responsibility of exception handling to the caller (It may be a method or JVM) then caller method is responsible to handle that exception.
  8. Who handles the exception if no one handles it?
    • If no one handles the exception, the exception won’t be caught and the program will crash as a result.
  9. When do you use throw and when do you throws?
    • Throw keyword is used to implicitly throw an exception from a method or any block of code such as a try block; mainly used to throw custom exceptions
    • Throws keyword is used in the declaration of a method to indicate that the method may throw one of the listed type exceptions.
  10. What is the top most class of an Exception?
    • Throwable superclass

File Reading/Streams

  1. How do you read a file in java?
    1. Import java.io* (we need FileReader, and BufferedReader )
    2. Declare file name / path as a string
    3. Create FileReader object & pass in fileName
    4. Instantiate BufferedReader & pass in FileReader
    5. Iterate through the lines using bufferReader & pass in FileReader
    6. Close the buffer reader . 
  2. What methods would you use?
    • FileReader and BufferedReader.
  3. How do you read a binary file?
    • You initialize a File object with the path of the specified file. You then use the static method readAllBytes() from the Files class and use the toPath() method of the File object as the parameter to this static method.
      • File f = new File(path);
      • byte[] byteArr = Files.readAllBytes(f.toPath());
  4. How would you read a file character by character?
    • FileReader reads in one character at a time without any buffering
  5. How do you check for the end of a file?
    • If you’re using the BufferedReader, it has a method called .nextLine() which will return null if there is no more to be read from the file. Using this you can use conditions based around it to finish reading from the file; for example, you could use a while loop which continues to print characters from the file only as long as .nextLine() method is not null.
  6. What happens if the file is not found?
    • The program will throw a FileNotFound exception.
  7. How do you reverse a file in Java?
    • Step 1: Use the above method to read to byte [ ];
    • Step 2: make byte [ ] to String, then StringBuilder, and use .reverse()
    • Step 3: Convert reversed String builder back to byte [ ] or whatever datatype required.
      • StringBuilder reverseFile = new StringBuilder(new String(fileBeingRead)).reverse();
      • byte [] reverseFileBytes = reverseFile.toString().getBytes();
  8. What if the file is big, how would you reverse it?
    • You can still use BufferedReader and FileReader to reverse big files.
  9. What do you return from the read method in java?
    • This method returns the next byte of data, or -1 if the end of the stream is reached.
  10. What does (-1) signify when adding it into a loop while reading a file?
    • It checks for the end of the file.

Threads

  1. How do you create a thread in Java?
    • You create a thread by either extending the Thread class or by implementing the Runnable interface.
  2. How do you decide when to use the Runnable interface over the Thread class?
    • Simply choose you use the Runnable interface when you don’t want to lose a chance for extending other classes, when you don’t need to override methods of Thread class and when memory consumption is a constraint during multiple threads creation.
  3. How do you create 10000 threads?
    • You could set up a for loop which would create a new thread on every iteration until the count reaches 10000.
  4. What is the difference between wait() and sleep()?
    • The major difference is that wait() releases the lock or monitor while sleep() doesn’t releases the lock or monitor while waiting. wait() is used for inter-thread communication while sleep() is used to introduce pause on execution, generally.
  5. What is a deadlock?
    • Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. Deadlock occurs when multiple threads need the same locks but obtain them in different order. A Java multithreaded program may suffer from the deadlock condition because the synchronized keyword causes the executing thread to block while waiting for the lock, or monitor, associated with the specified object.
  6. How to prevent a deadlock situation?
    • Any of the following will prevent Deadlock:
      • Change the order of the locks
      • Don’t use multiple threads
      • Don’t execute foreign code while holding a lock
      • Use uninterruptible locks
  7. Is deadlock a synchronized or unsynchronized concept?
    • Deadlock is an unsynchronized concept; you avoid it by making so your threads are synchronized.

Strings

  1. How do you reverse a string? 
    • To reverse a string you can use the reverse method of StringBuffer, or more preferably use the StringBuilder’s reverse method.
  2. How to check if a string is a palindrome?
    • Step 1: Get the length of the string and store it in a variable n.
    • Step 2: Create a for loop and set the max number of loops to n/2.
    • Step 3: Compare the individual characters of the string using the charAt
    • Step 4: Once a pair of characters don’t match, break the loop
  3. Have you heard of string pool?

JDBC and Database Connection

  1. How to connect to a database using JDBC ?
    1. You add the SQL connection jar to the classpath 
    2. Load and register the JDBC driver 
    3. Connect to the database using the DriverManager class. 
    4. You pass in the URL, USERNAME and PASSWORD to access the database. 
  2. How would you load and register JDBC?
    • Registering the driver is a process where the Oracle driver’s class file is loaded into memory so it can be utilized as an implementation of JDBC interfaces. You only need to register a driver once using one of two methods: either use the Class.ForName() approach to dynamically load the driver’s class file into memory or use the  DriverManager.registerDriver() approach to register the driver.
  3. How to retrieve data from the database using Java? 
    • You can execute a SELECT query by passing it into executeQuery() method to fetch data from the database.
  4. How do you create a query in JDBC?
    • Pass a query(such as one to create a table) into the executeUpdate() method of statement object to submit a query to the database.

Other Topics

  1. What is serialization in Java? 
    • Serialization is a way of converting the state of an object into a byte stream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory.
  2. Can you override a method within the same class?
    • No, you can only override a method within a subclass which extends the class the method is in.
  3. What is immutable?
    • Immutable objects are objects whose state (the object’s data) cannot change after construction. For one example, String is immutable because String objects in Java are not objects, but merely references. These objects point to strings. You can change what they point to, but not that which it points at.
  4. What is an immutable class?
    • Immutable class means that once an object is created, we cannot change its content.
  5. Why are Strings immutable in Java?
    • String objects in Java are not objects, but merely references. These objects point to strings. You can change what they point to, but not that which it points at.
  6. What are the latest Java 8 features that are used?
    • There are several commonly used Java 8 features including but not limited to Lambda expressions, Stream API, Method references, Functional interfaces, Collectors class, ForEach() method and Default methods.
  7. What are the purpose of lambda expressions?
    • A lambda expression is a block of code that can be passed around to execute. It was added in Java 8 onward to treat functionality as a method argument or code as data, and to make a function that can be created without belonging to any class
  8. Can you create an object of type abstract class? How and why?
    • No, you cannot create an object of type abstract class because an abstract class cannot be instantiated as an object.
  9. What if you want to define an object outside a class?
    • You cannot define an object outside of a class. You need to define any and all objects within a class.
  10. Can we have an abstract class without an abstract method?
    • Yes
  11. What will happen if I define an abstract class without an abstract method, will it behave like a normal class or behave differently?
    • The abstract class without an abstract method acts the same as an abstract class with an abstract method. It doesn’t affect the behavior of the abstract class.

Sources:

Leave a comment

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