Skip to content

Instantly share code, notes, and snippets.

@slezhnin
Last active October 10, 2019 08:50
Show Gist options
  • Save slezhnin/ed6530776cc1f1a225d74890aae879f3 to your computer and use it in GitHub Desktop.
Save slezhnin/ed6530776cc1f1a225d74890aae879f3 to your computer and use it in GitHub Desktop.
Java interview topic list

Java Language

Classes and Objects

QA

Q:

  1. What's wrong with the following program?
    public class SomethingIsWrong {
        public static void main(String[] args) {
            Rectangle myRect;
            myRect.width = 40;
            myRect.height = 50;
            System.out.println("myRect's area is " + myRect.area());
        }
    }
  2. The following code creates one array and one string object. How many references to those objects exist after the code executes? Is either object eligible for garbage collection?
    String[] students = new String[10];
    String studentName = "Peter Parker";
    students[0] = studentName;
    studentName = null;
  3. How does a program destroy an object that it creates?

A:

  1. The code never creates a Rectangle object. With this simple program, the compiler generates an error. However, in a more realistic situation, myRect might be initialized to null in one place, say in a constructor, and used later. In that case, the program will compile just fine, but will generate a NullPointerException at runtime.
  2. There is one reference to the students array and that array has one reference to the string Peter Smith. Neither object is eligible for garbage collection. The array students is not eligible for garbage collection because it has one reference to the object studentName even though that object has been assigned the value null. The object studentName is not eligible either because students[0] still refers to it.
  3. A program does not explicitly destroy objects. A program can set all references to an object to null so that it becomes eligible for garbage collection. But the program does not actually destroy objects.

Nested Classes

Inner Classes

Non Static
Static
Local
Anonymous

Like local classes, anonymous classes can capture variables; they have the same access to local variables of the enclosing scope:

  • An anonymous class has access to the members of its enclosing class.
  • An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final.
  • Like a nested class, a declaration of a type (such as a variable) in an anonymous class shadows any other declarations in the enclosing scope that have the same name. See Shadowing for more information.

Anonymous classes also have the same restrictions as local classes with respect to their members:

  • You cannot declare static initializers or member interfaces in an anonymous class.
  • An anonymous class can have static members provided that they are constant variables.

Note that you can declare the following in anonymous classes:

  • Fields
  • Extra methods (even if they do not implement any methods of the supertype)
  • Instance initializers
  • Local classes

However, you cannot declare constructors in an anonymous class.

Enums

Enums can have constructor, methods and fields just like class. Implicitly inherits enum class.

QA

Q:

  1. True or false: an Enum type can be a subclass of java.lang.String.

A:

  1. False

Interfaces

QA

Q:

  1. What methods would a class that implements the java.lang.CharSequence interface have to implement?
  2. What is wrong with the following interface?
    public interface SomethingIsWrong {
        void aMethod(int aValue){
            System.out.println("Hi Mom");
        }
    }
  3. Fix the interface in question 2.
  4. Is the following interface valid?
    public interface Marker {
    }

A:

  1. charAt, length, subSequence, and toString
  2. It has a method implementation in it. Only default and static methods have implementations.
  3. Remove implementation or add default keyword (Java 8).
  4. Yes. Methods are not required. Empty interfaces can be used as types and to mark classes without requiring any particular method implementations. For an example of a useful empty interface, see java.io.Serializable.

Generics

Generic Methods

Bounded Type Parameters

Wildcards

Upper Bounded Wildcards

Unbounded Wildcards

The unbounded wildcard type is specified using the wildcard character (?), for example, List<?>. This is called a list of unknown type. There are two scenarios where an unbounded wildcard is a useful approach:

If you are writing a method that can be implemented using functionality provided in the Object class. When the code is using methods in the generic class that don't depend on the type parameter. For example, List.size or List.clear. In fact, Class<?> is so often used because most of the methods in Class do not depend on T.

Lower Bounded Wildcards

Note: You can specify an upper bound for a wildcard, or you can specify a lower bound, but you cannot specify both.

Type Erasure

QA

Q

  1. Will the following class compile? If not, why?
    public final class Algorithm {
        public static <T> T max(T x, T y) {
            return x > y ? x : y;
        }
    }
  2. If the compiler erases all type parameters at compile time, why should you use generics?
  3. What is the following method converted to after type erasure?
    public static <T extends Comparable<T>>
        int findFirstGreaterThan(T[] at, T elem) {
        // ...
    }
  4. Will the following method compile? If not, why?
    public static void print(List<? extends Number> list) {
        for (Number n : list)
            System.out.print(n + " ");
        System.out.println();
    }
  5. Will the following class compile? If not, why?
    public class Singleton<T> {
    
        public static T getInstance() {
            if (instance == null)
                instance = new Singleton<T>();
    
            return instance;
        }
    
        private static T instance = null;
    }
  6. Will the following code compile? If not, why?
     class Shape { /* ... */ }
     class Circle extends Shape { /* ... */ }
     class Rectangle extends Shape { /* ... */ }
     class Node<T> { /* ... */ }
    
     Node<Circle> nc = new Node<>();
     Node<Shape>  ns = nc;
  7. Will the following code compile? If not, why?
    class Node<T> implements Comparable<T> {
        public int compareTo(T obj) { /* ... */ }
        // ...
    }
    Node<String> node = new Node<>();
    Comparable<String> comp = node;

A

  1. No. The greater than (>) operator applies only to primitive numeric types. How to fix?
  2. You should use generics because:
    • The Java compiler enforces tighter type checks on generic code at compile time.
    • Generics support programming types as parameters.
    • Generics enable you to implement generic algorithms.
  3. public static int findFirstGreaterThan(Comparable[] at, Comparable elem) {}
  4. Yes.
  5. No. You cannot create a static field of the type parameter T.
  6. No. Because Node is not a subtype of Node.
  7. Yes.

Collections

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment