P NP NP-Complete NP-hard

____________________________________________________________
| Problem Type | Verifiable in P time | Solvable in P time | Increasing Difficulty
___________________________________________________________|           |
| P            |        Yes           |        Yes         |           |
| NP           |        Yes           |     Yes or No *    |           |
| NP-Complete  |        Yes           |      Unknown       |           |
| NP-Hard      |     Yes or No **     |      Unknown ***   |           |
____________________________________________________________           V

What are the Data Types supported by Java ?
The eight primitive data types supported by the Java programming language are:

  • byte
  • short
  • int
  • long
  • float
  • double
  • boolean
  • char

Why don’t Java support multiple inheritance?

Static Binding vs Dynamic Binding (还是有点不太明白 再查查)

When should inner classes be used in Java?

Are objects of the same type as the inteface implemented

  • What is printed out in the Java code below – true or false?

      public interface Animal{
        public void sleeps( );
      }
    
      public class Dog implements Animal{
         /*
           ...
         */  
      }
    
      public class SomeClass {
    
        public static void main(String [ ] args){
          Dog d = new Dog( ) ;   
    
         // this checks to see if d is of type Animal
          if ( d instanceof Animal) 
              System.out.println("true");
          else   
              System.out.println("false");
        }
      }
    
  • In order to understand the code above, you must understand that any time a class implements an interface, this means that when an object of that class is created, it will also have the interface type. This means that in the code above, the “d” object will be of both the Dog type and the Animal type. This means that the code above will print out “true”.

What is the diamond problem? Does it exist in Java? If so, how can it be avoided?

Can an interface extend another interface in Java?

  • Yes, an interface can extend another interface in Java. This is what the code for something like that would look like:

      // this interface extends from the Body interface:
      public interface FourLegs extends Body{
          public void walkWithFourLegs( );
    
      }
    
  • Remember that any class that implements an interface must implement the method headings that are declared in that interface. And, if that interface extends from other interfaces, then the implementing class must also implement the methods in the interfaces that are being extended or derived from. So, in the example above, if we have a class that implements the FourLegs interface, then that class must have definitions for any method headings in both the FourLegs interface and the Body interface.

Upcasting and Downcasting in Java?

  • Upcasting is casting to a supertype, while downcasting is casting to a subtype. Supercasting is always allowed, but subcasting involves a type check and can throw a ClassCastException.
  • In your case, a cast from from Dog to an Animal is a upcast, because a Dog is-a Animal. In general, you can upcast whenever there is an is-a relationship between two classes.
  • Downcasting would be something like this:
      Animal animal = new Dog();
      Dog castedDog = (Dog) animal;
    
    Basically what you're doing is telling the program that you know what the runtime type of the object really is. The program will do the conversion, but will still do a sanity check to make sure that it's possible. In this case, the cast is possible because at runtime animal is actually a Dog even though the static type of animal is Animal.
  • However, if you were to do this:
      Animal animal = new Animal();
      Dog dog = (Dog) animal;
    
    You'd get a ClassCastException. The reason why is because animal's runtime type is Animal, and so when you tell the runtime to perform the cast it sees that animal isn't really a Dog and so throws a ClassCastException.
  • To call a superclass's method you can do super.method() or be performing the upcast.
  • To call a subclass's method you have to do a downcast and risk the ClassCastException.

What is the differences between references in Java and pointers in C++?

  • References store an address. That address is the address in memory of the object. So, when a class is declared like so: PersonClass y = new PersonClass();, the "y" variable actually stores an address in memory. If you were to look at that address in memory you would see the details of the PersonClass object. Pointers in C++, however, point directly to the object.
  • You can not perform arithmetic operations on references. So, adding 1 to a pointer is not possible, but is possible in C++.

What’s the difference between a primitive type and a class type in Java?

  • For a variable of a primitive type, the value of the variable is stored in the memory location assigned to the variable. So, if an integer variable is declared as “int x = 3″, then when we look at the memory location of “x”, there will be a “3” stored there just as expected. A value of a primitive type – like a type int – will always require the same amount of memory to store one value. There is a maximum value of type int, which means that values of type int will have a limit on their size.
  • However, a variable of a class type only stores the memory address of where the object is located – not the values inside the object. So, if we have a class called “SomeClass”, when we create an object like this: “SomeClass anObject”, then when we look at “anObject” in memory, we will see that it does not store any of the variables that belong to that object in memory. Instead, the variable “anObject” just stores an address of another place in memory where all the details of “anObject” reside. This means that the object named by the variable is stored in some other location in memory and the variable contains only the memory address of where the object is stored. This memory address is called a reference to the object. If this is confusing, you will see an example of this further down.

What are different type of cloning in Java?

  • Java supports two type of cloning: - Deep and shallow cloning.
  • By default shallow clone is used in Java. Object class has a method clone() which does shallow cloning.

Java deep copy, shallow copy, clone()?

What is a transient variable?

  • If some of the properties of a class are not required to be serialized then the varaibles are marked as transient. When an object is deserialized the transient variables retains the default value depending on the type of variable declared and hence lost its original value.
  • Transient variables in Java

What is a strictfp modifier?

  • Java strictfp keyword ensures that you will get the same result on every platform if you perform operations in the floating-point variable. The precision may differ from platform to platform that is why java programming language have provided the strictfp keyword, so that you get same result on every platform.
  • Java Strictfp Keyword

What is immutable class? How to create an immutable class? Immutable objects are automatically thread-safe? Which classes in java are immutable? What are the advantages of immutability?

  • Immutable class is a class which once created, it’s contents can not be changed. Immutable objects are the objects whose state can not be changed once constructed. e.g. String class
  • To create an immutable class following steps should be followed:

    • The instance variable of the class is final i.e. we cannot change the value of it after creating an objec
    • The class is final so we cannot create the subclass.
    • There is no setter methods i.e. we have no option to change the value of the instance variable.

      public final class Employee{
        final String pancardNumber;
      
        public Employee(String pancardNumber){
            this.pancardNumber=pancardNumber;  
        }
        public String getPancardNumber(){  
            return pancardNumber;  
        }  
      }
      
  • Yes. Since the state of the immutable objects can not be changed once they are created they are automatically synchronized/thread-safe.
  • All wrapper classes in java.lang are immutable – String, Integer, Boolean, Character, Byte, Short, Long, Float, Double, BigDecimal, BigInteger.
  • The advantages are as below:
    • Automatically thread-safe
    • Once created the state of the immutable object can not be changed so there is no possibility of them getting into an inconsistent state.
    • The references to the immutable objects can be easily shared or cached without having to copy or clone them as there state can not be changed ever after construction.
    • The best use of the immutable objects is as the keys of a map.

Why super class assignment to subclass will give an error? Explicit casting from super class to subclass does not generate a compilation error, but at runtime it generates a ClassCastException. Why can't the compiler detect this error?

  • Because all cats are animals, but not all animals are cats.
  • By using a cast you're essentially telling the compiler "trust me. I'm a professional, I know what I'm doing and I know that although you can't guarantee it, I'm telling you that this animal variable is definitely going to be a dog." Since the animal isn't actually a dog (it's an animal, you could do Animal animal = new Dog(); and it'd be a dog) the VM throws an exception at runtime because you've violated that trust (you told the compiler everything would be ok and it's not!)

What is object? What is object reference? What is final reference variable?

  • Lets start with an example. You must have contacts of many people in your mobile. You can use a contact to call a person. The person is actually somewhere else, but the contact helps you to call them. You can think of a Reference variable to be a contact and Object to be the actual person you are calling. Basically a reference variable just points to an actual object.

  • For example if we have a class,

      class Person {
          String name = "Eric";
          int age = 25;
      }
    
      Person p = new Person();
    

    Here p is a reference variable which points to an object of class Person. The actual object of class Person created in that statement resides on the heap. The reference variable p only contains the memory address of Person class object on the heap. So the actual value of p can be said to be an address on the heap.

  • Difference Between Object and Reference in Java

How many ways to create object in Java?

  • Using new Keyword
      MyObject object = new MyObject();
    
  • Using clone()
      MyObject anotherObject = new MyObject();
      MyObject object = (MyObject) anotherObject.clone();
    
  • Using Class.forName()
      MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance();
    
  • Using object deserialization
      ObjectInputStream inStream = new ObjectInputStream(anInputStream );
      MyObject object = (MyObject) inStream.readObject();
    

What is Reflection?

  • Reflection makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc.
  • Java Reflection Tutorial

Given classes A, B, and C where B extends A and C extends B and where all classes implement the instance method void doIt(). Is it possible for the version of the doIt() method in class A to be called by an instance of class B? What is the syntax?

  • super.doIt()

What is Autoboxing and Unboxing ?

  • Autoboxing is the automatic conversion made by the Java compiler between the primitive types and their corresponding object wrapper classes. For example, the compiler converts an int to an Integer, a double to a Double, and so on.
  • If the conversion goes the other way, this operation is called unboxing.

What’s the difference between equals() and ==?

  • “==” checks to see if the objects refer to the same place in memory.
  • equals() checks to see if both objects reference the same place in memory.

What is the difference between an Interface and an Abstract class ? What is non-abstract class called?

  • Below are the difference:
    • All methods in an interface are implicitly abstract. On the other hand, an abstract class may contain both abstract and non-abstract methods.
    • A class may implement a number of Interfaces, but can extend only one abstract class
    • In order for a class to implement an interface, it must implement all its declared methods. However, a class may not implement all declared methods of an abstract class. Though, in this case, the sub-class must also be declared as abstract.
    • Abstract class would be more appropriate when there is a strong relationship between the abstract class and the classes that will derive from it. Again, this is because an abstract class is very closely linked to inheritance, which implies a strong relationship. But, with interfaces there need not be a strong relationship between the interface and the classes that implement the interface.
  • A non abstract class is called a concrete class.

What is a Constructor, Constructor Overloading in Java?

  • A Constructor gets invoked when a new object is created. Every class has a constructor. In case the programmer does not provide a constructor for a class, the Java compiler (Javac) creates a default constructor for that class.
  • Constructor Overloading is similar to method overloading in Java. Different constructors can be created for a single class. Each constructor must have its own unique parameter list.

What does the “static” keyword mean ? Can you override private or static method in Java ? Can you access non static variable in static context ? What is static class ?

  • "static" denotes that a member variable or method can be accessed, without requiring an instantiation of the class to which it belongs.
  • A user cannot override static methods in Java, because method overriding is based upon dynamic binding at runtime and static methods are statically binded at compile time. A static method is not associated with any instance of a class so the concept is not applicable.
  • A static variable in Java belongs to its class and its value remains the same for all its instances. A static variable is initialized when the class is loaded by the JVM. If your code tries to access a non-static variable, without any instance, the compiler will complain, because those variables are not created yet and they are not associated with any instance.
  • A class cannot be declared static. But a class can be said a static class if all the variables and methods of the class are static and the constructor is private. Making the constructor private will prevent the class to be instantiated. So the only possibility to access is using Class name only

What is the Difference between JDK and JRE ?

  • The Java Runtime Environment (JRE) is basically the Java Virtual Machine (JVM) where your Java programs are being executed. It also includes browser plugins for applet execution.
  • The Java Development Kit (JDK) is the full featured Software Development Kit for Java, including the JRE, the compilers and tools (like JavaDoc, and Java Debugger), in order for a user to develop, compile and execute Java applications.

What is the difference between public, private, protected and defalut?

  • A public member or method can be accessed from any other class.
  • A private member or method is accessible only within its own class.
  • Finally, a protected member is accessible within its class, its sub-classes and in all classes that reside in the same package.
  • default means its accessable in the same package, but not accessable in different package.

What are pass by reference and pass by value ?

  • When an object is "passed by value", this means that a copy of the object is passed. Thus, even if changes are made to that object, it doesn’t affect the original value.
  • When an object is "passed by reference", this means that the actual object is not passed, rather a reference of the object is passed. Thus, any changes made by the external method, are also reflected in all places. "passed by reference" (also called pass by address), a copy of the address of the actual parameter is stored.
  • Does Java pass by reference or by value?
  • pass by value or pass by reference?

Composition VS. Inheritance. How to choose?

  • Generally when there exists an "IS A" relation we use Inheritance.
  • When a "HAS-A" relationship exists then we use Composition.

How does System.out.println() work?

  • Most interviewers would not expect you to know the answer to do this right away – but would like to see how you think and arrive at an answer.
  • In Java, the dot operator can only be used to call methods and variables so we know that out must be either a method or a variable. Well, out could not possibly be a method because of the fact that there are no parentheses. Because out is being called with the System class name itself, and not an instance of a class (an object), then we know that out must be a static variable. So now we know that out is a static member variable belonging to the System class.
  • The more exact answer to the original question is this: inside the System class is the declaration of out that looks like: public static final PrintStream out, and inside the Prinstream class is a declaration of println() that has a method signature that looks like: public void println().

What is JVM ? Why is Java called the “Platform Independent Programming Language” ?
What is the meaning of platform independence?

  • A Java virtual machine (JVM) is a process virtual machine that translate the bytecode into the machine language for a particular computer and then execute Java bytecode.
  • Each Java source file is compiled into a bytecode file, which is executed by the JVM.
  • Java was designed to allow application programs to be built that could be run on any platform, without having to be rewritten or recompiled by the programmer for each separate platform.

What’s the difference between method overloading and method overriding?

  • Overloading in Java occurs when two or more methods in the same class have the exact same name, but different parameters. It’s also very important to understand that method overloading is NOT something that can be accomplished with either, or both, of these two things.
    1. Just changing the return type of the method. If the return type of the method is the only thing changed, then this will result in a compiler error.
    2. Changing just the name of the method parameters, but not changing the parameter types. If the name of the method parameter is the only thing changed then this will also result in a compiler error.
  • Overriding is defined as the case when a child class redefines the same method as a parent class. Overridden methods must have the same name, argument list, and return type.
  • Overloading happens at compile time. Overriding happens at run time

What is the point of having a private constructor?

  • Can used in singleton pattern.
  • Can prevent creation of objects.

What is Copy constructor? why do we use it? Does Java support Copy Constructor ?

  • A copy constructor is a constructor that takes only one parameter which is the same exact type as the class in which the copy constructor is defined. For example, suppose we define a class called X. Then, a copy constructor defined in class X would also expect a parameter of type X.
  • Copy constructors are widely used for creating a duplicates of objects known as cloned objects. Duplicate object in the sense the object will have the same characteristics of the original object from which duplicate object is created. But we have to ensure that both original and duplicate objects refer to different memory locations.
  • Java does support copy constructors like C++, but the difference lies in the fact that Java doesn’t create a default copy constructor if you don’t write your own.
    Copy Constructor in Java 详解

What does the ‘final’ modifier mean when applied to a method, class, and an instance variable?

  • final method indicates that the method may not be overridden in a derived class.
  • final class indicates that the class can not be used as a base class to derive any class from it.
  • final variable means that the instance variable can’t be changed.

What does the finally block do? Will finally run after return? Which situation finally will not run after return? What if there is a return statement in the finally block as well?

  • The finally block is placed after a try block and the catch blocks that follow it. The finally block contains code that will be run whether or not an exception is thrown in a try block.
  • Yes, the finally block will be executed before the return statement.

      public class SomeMethod{
          public static void main(String args[]){
              System.out.println(SomeClass.proveIt()); 
          }
    
          public static int proveIt(){
              try{
                  return 1;
              }
              finally{
                  System.out.println("Finally bolck is run before method returns");
              }
          }
      }
    

    Running the code above gives us this output:

      finally block is run before method returns.
      1
    
  • The finally block will not be called if System.exit() is called first, or if the JVM crashes.
  • If we have a return statement in both the finally block and the try block, then anything that is returned in the finally block will actually override any exception or returned value that is inside the try/catch block