Choose.. X Home Exams Certifications
 

Core Java Interview Questions

1 . What is the difference between constructors and other regular methods?

  • Constructors Regular methods Constructors must have the same name as the class name and cannot return a value. The constructors are called only once per creation of an object while regular methods can be called many times.
    E.x. for a Car.class public Car() {} /* constructor*/
    Regular methods can have any name and can be called any number of times. E.x. for a Car.class.
    public String getCarName(){} /* regular method has a String return type */
    public void createCar(){} /* regular method has a void return type */

2 . What happens if you do not provide a constructor?

  • Java does not actually require an explicit constructor in the class description. If you do not include a constructor, the Java compiler will create a default constructor in the byte code with an empty argument. This default constructor is equivalent to the explicit "Car(){}".

    If a class includes one or more explicit constructors like "public Car(int id)" or "Car(){}" etc, the java compiler does not create the default constructor "Car(){}".

3 . Can you call one constructor from another?

  • Yes, by using this() syntax,
    public Car(int id) { 
    this.id = id; /* "this" means this object */
    }
    public Car (int id, String type) {
    this(id); /* calls constructor public Car(int id) */
    this.type = type; /* this means this object */
    }

4 . How to call the superclass constructor?

  • If a class called "SpecialCar" extends your "Car" class then you can use the keyword "super" to invoke the superclass's constructor. E.x.
    public SpecialCar(int id) { 
    super(id); /*must be the very first statement in the constructor */
    }
    To call a regular method in the super class use: "super.myMethod( );"

5 . What is the difference between an interface and an abstract class?

  • Interfaces are rules (Rules because you must give an implementation to them and that you can't ignore or avoid, so that are imposed like rules) which works as a common understanding document among the various teams in software development. Interfaces give the idea what is to be done but not how it will be done. So implementation completely depends on developer by following the given rules(Means given signature of methods).
    Abstract classes may contain only abstract declarations or only concrete implementations or mixed. Abstract declarations are like rules to be followed and concrete implementations are like guidelines(You can use that as it is or you can ignore it by overriding and giving your own choice implementation to it)
    1. Abstract class is a class while interface is a interface, means by extending abstract class you can not extend another class because Java does not support multiple inheritance but you can implement multiple inheritance in Java.
    2. You can not create non abstract method in interface, every method in interface is by default abstract, but you can create non abstract method in abstract class. Even a class which doesn't contain any abstract method can be abstract by using abstract keyword.
    3. Abstract class are slightly faster than interface because interface involves a search before calling any overridden method in Java. This is not a significant difference in most of cases but if you are writing a time critical application than you may not want to leave any stone unturned.
    4. Interface are better suited for Type declaration and abstract class is more suited for code reuse and evolution perspective.
    5. When you add a new method in existing interface it breaks all its implementation and you need to provide an implementation in all clients which is not good. By using abstract class you can provide default implementation in super class.

6 . Why would you use a synchronized block vs. synchronized method?

  • Synchronized blocks place locks for shorter periods than synchronized methods.

7 . Explain the usage of the keyword transient?

  • This keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).

8 . How can you force garbage collection?

  • You can't force GC, but could request it by calling

    System.gc() JVM does not guarantee that GC will be started immediately.

9 . How do you know if an explicit object casting is needed?

  • If you assign a superclass object to a variable of a subclass's data type, you need to do explicit casting. For example:
    Object a;
    Vehicle b;
    b = (Vehicle) a;

    When you assign a subclass to a variable having a superclass type, the casting is performed automatically.

10 . Can you write a Java class that could be used both as an applet as well as an application?

  • Yes. Add a
    main() method to the applet.

11 . What's the difference between constructors and other methods?

  • Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times.

12 . Can you call one constructor from another if a class has multiple constructors

  • Yes. Use this() syntax

13 . Explain the usage of Java packages.

  • This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes.

14 . If a class is located in a package, what do you need to change in the OS environment to be able to use it?

  • You need to add a directory or a jar file that contains the package directories to the

    CLASSPATH environment variable. Let's say a class Employee belongs to a package com.xyz.hr; and is located in the filec:\dev\com\xyz\hr\Test.javaIn this case, you'd need to add c:\test to the variable CLASSPATH If this class contains the method main(), you could test it from a command prompt window as follows: c:\>java com.xyz.hr.Test

15 . Differences between String,StringBuffer and StringBuilder?

    • String objects are immutable, and String reference variables are not.
    • If you create a new String without assigning it, it will be lost to your program.
    • If you redirect a String reference to a new String, the old String can be lost.
    • String methods use zero-based indexes, except for the second argument of substring().
    • The String class is final—its methods can't be overridden.
    • When the JVM finds a String literal, it is added to the String literal pool.
    • Strings have a method: length(); arrays have an attribute named length.
    • The StringBuffer's API is the same as the new StringBuilder's API, except that StringBuilder's methods are not synchronized for thread safety.
    • StringBuilder methods should run faster than StringBuffer methods.
    All of the following bullets apply to both StringBuffer and StringBuilder:
    • They are mutable—they can change without creating a new object.
    • StringBuffer methods act on the invoking object, and objects can change without an explicit assignment in the statement.
    • StringBuffer equals() is not overridden; it doesn't compare values.
    • Remember that chained methods are evaluated from left to right.
    • String methods to remember: charAt(), concat(), equalsIgnoreCase(), length(), replace(), substring(), toLowerCase(), toString(), toUpperCase(), and trim().
    • StringBuffer methods to remember: append(), delete(), insert(), reverse(), and toString().

16 . What would you use to compare two String variables - the operator == or the method equals()?

  • I'd use the method equals() to compare the values of the Strings and the == to check if two variables point at the same instance of a String object.

17 . How could Java classes direct program messages to the system console, but error messages, say to a file?

  • The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:
    Stream st = new Stream(new FileOutputStream("test.txt"));
    System.setErr(st);
    System.setOut(st);

18 . What is difference between JDK,JRE and JVM?

  • JVM is an acronym for Java Virtual Machine, it is an abstract machine which provides the runtime environment in which java bytecode can be executed. JVMs are available for many hardware and software platforms (so JVM is plateform dependent).
    JRE : JRE stands for Java Runtime Environment. It is the implementation of JVM and physically exists.
    JDK : JDK is an acronym for Java Development Kit. It physically exists. It contains JRE + development tools.

19 . How many types of memory areas are allocated by JVM?

  • Some types are:

    • Class(Method) Area
    • Heap
    • Stack
    • Program Counter Register
    • Native Method Stack

20 . What is stored in Stack and Heap in java?

  • Local variables (method variables) live on the stack. Objects and their instance variables live on the heap.

21 . Is it possible to override the main method?

  • NO, because main is a static method. A static method can't be overridden in Java.

22 . What is JIT compiler?

  • Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation.Here the term compiler refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.

23 . What is classloader?

  • The classloader is a subsystem of JVM that is used to load classes and interfaces.There are many types of classloaders e.g. Bootstrap classloader, Extension classloader, System classloader, Plugin classloader etc.

24 . Explain static vs. dynamic class loading?

  • Static class loading Classes are statically loaded with Java's "new" operator.
    class MyClass {
    public static void main(String args[]) {
    Car c = new Car();
    }
    }
    Dynamic loading is a technique for programmatically invoking the functions of a class loader at run time. Let us look at how to load classes dynamically.
    Class.forName (String className); /*static method returns the class object associated with the class  name*/ 

    The string className can be supplied dynamically at run time. Once the class is dynamically loaded the following method returns an instance of the loaded class. It's just like creating a class object with no arguments.
     class.newInstance (); /*A non-static method, which creates an instance of a */ 

25 . What is instanceOf operator?

  •     instanceof is for reference variables only, and checks for whether the object is of a particular type. The instanceof operator can be used only to test objects (or null) against class types that are in the same class hierarchy.
        For interfaces, an object passes the instanceof test if any of its superclasses implement the interface on the right side of the instanceof operator.

26 . Can we overload the main method in Java?

  • You can overload the main() method, but only public static void main(String[] args) will be used when your class is launched by the JVM.
    For example:
    public class Test {
    public static void main(String[] args) {
    System.out.println("main(String[] args)");
    }
    public static void main(String arg1) {
    System.out.println("main(String arg1)");
    }
    public static void main(String arg1, String arg2) {
    System.out.println("main(String arg1, String arg2)");
    }
    }

    That will always print main(String[] args) when you run java Test ... from the command line, even if you specify one or two command-line arguments. You can call the main() method yourself from code, of course - at which point the normal overloading rules will be applied.

27 . How to instantiate "Set" in java

  • Set myStringSet = new HashSet(); Or Set myStringSet = new HashSet ();

28 . What is Method with var-args

  • As of Java 5, methods can declare a parameter that accepts from zero to many arguments, a so-called var-arg method.A var-arg parameter is declared with the syntax type... name; for instance: doStuff(int... x) { }A var-arg method can have only one var-arg parameter.In methods with normal parameters and a var-arg, the var-arg must come last.

29 . What is Enum in java?

  • An enum specifies a list of constant values assigned to a type.
    An enum is NOT a String or an int; an enum constant's type is the enum type. For example, SUMMER and FALL are of the enum type Season.
    An enum can be declared outside or inside a class, but NOT in a method.
    An enum declared outside a class must NOT be marked static, final, abstract, protected, or private.
    Enums can contain constructors, methods, variables, and constant class bodies.
    enum constants can send arguments to the enum constructor, using the syntax BIG(8), where the int literal 8 is passed to the enum constructor.
    enum constructors can have arguments, and can be overloaded.
    enum constructors can NEVER be invoked directly in code. They are always called automatically when an enum is initialized. The semicolon at the end of an enum declaration is optional. These are legal:
    enum Foo { ONE, TWO, THREE}
    enum Foo { ONE, TWO, THREE};

    MyEnum.values() returns an array of MyEnum's values.

30 . What is Coupling and Cohesion?

  • 1. Coupling refers to the degree to which one class knows about or uses members of another class.
       1. Loose coupling is the desirable state of having classes that are well encapsu- lated, minimize references to each other, and limit the breadth of API usage.
       2. Tight coupling is the undesirable state of having classes that break the rules of loose coupling.
    2. Cohesion refers to the degree in which a class has a single, well-defined role or responsibility.
       1. High cohesion is the desirable state of a class whose members support a single, well-focused role or responsibility.
       2. Low cohesion is the undesirable state of a class whose members support mul- tiple, unfocused roles or responsibilities

31 . What is Garbage Collection in java?

    • In Java, garbage collection (GC) provides automated memory management.
    • The purpose of GC is to delete objects that can't be reached.
    • Only the JVM decides when to run the GC, you can only suggest it.
    • Objects must be considered eligible before they can be garbage collected.
    • An object is eligible when no live thread can reach it.
    • To reach an object, you must have a live, reachable reference to that object.
    • Request garbage collection with System.gc(); (only before the SCJP 6). Class Object has a finalize() method.
    • The finalize() method is guaranteed to run once and only once before the garbage collector deletes an object.
    • The garbage collector makes no guarantees, finalize() may never run. You can uneligibilize an object for GC from within finalize().

32 . What are different types of exception in java?

  • Exceptions come in two flavors: checked and unchecked. Checked     Checked exceptions include all subtypes of Exception, excluding classes that extend RuntimeException.
        Checked exceptions aresubject to the handle or declare rule; any method that might throw a checked exception (including methods that invoke meth- ods that can throw a checked exception) must either declare the exception using throws, or handle the exception with an appropriatetry/catch.
    Unchecked     Subtypes of Error or RuntimeException are unchecked, so the compiler doesn't enforce the handle or declare rule. You're free to handle them, or to declare them, but the compiler doesn't careone way or the other.

33 . What is finally in java?

    • If you use an optional finally block, it will always be invoked, regardless of whether an exception in the corresponding try is thrown or not, and regard less of whether a thrown exception is caught or not.
    • The only exception to the finally-will-always-be-called rule is that a finally will not be invoked if the JVM shuts down. That could happen if code from the try or catch blocks calls System.exit().
    • Just because finally is invoked does not mean it will complete. Code in the finally block could itself raise an exception or issue a System.exit().

34 . Can you create checked exceptions in java?

  •     You can create your own exceptions, normally by extending Exception or one of its subtypes. Your exception will then be considered a checked exception, and the compiler will enforce the handle or declare rule for that exception.

35 . What are Assertions in java?

  • Assertions (by way of the assert keyword) were added in Java 1.4. They are used to verify the correctness of an invariant in the code. They should never be triggered in production code, and are indicative of a bug or misuse of a code path. They can be activated at run-time by way of the -ea option on the java command, but are not turned on by default. An example:
    public Foo acquireFoo(int id) {
    Foo result = null;
    if (id > 50) {
    result = fooService.read(id);
    } else {
    result = new Foo(id);
    }
    assert result != null;
    return result;
    }

36 . What is Serialization and what are uses?

  •     Serialization is simply turning an existing object into a byte array. This byte array represents the class of the object, the version of the object, and the internal state of the object. This byte array can then be used between JVM's running the same code to transmit/read the object.
        Why would we want to do this? There are several reasons: Communication: If you have two machines that are running the same code, and they need to communicate, an easy way is for one machine to build an object with information that it would like to transmit, and then serialize that object to the other machine. It's not the best method for communication, but it gets the job done. Persistence: If you want to store the state of a particular operation in a database, it can be easily serialized to a byte array, and stored in the database for later retrieval. Deep Copy: If you need an exact replica of an Object, and don't want to go to the trouble of writing your own specialized clone() class, simply serializing the object to a byte array, and then de-serializing it to another object achieves this goal. Caching: Really just an application of the above, but sometimes an object takes 10 minutes to build, but would only take 10 seconds to de-serialize. So, rather than hold onto the giant object in memory, just cache it out to a file via serialization, and read it in later when it's needed. Cross JVM Synchronization: Serialization works across different JVMs that may be running on different architectures. Points remember.
    1. A class must implement Serializable before its objects can be serialized.
    2. The ObjectOutputStream.writeObject() method serializes objects, and the ObjectInputStream.readObject() method deserializes objects.
    3. If you mark an instance variable transient, it will not be serialized even thought the rest of the object's state will be.
    4. You can supplement a class's automatic serialization process by implementing the writeObject() and readObject() methods. If you do this, embedding calls to defaultWriteObject() and defaultReadObject(), respectively, will handle the part of serialization that happens normally.
    5. If a superclass implements Serializable, then its subclasses do automatically.
    6. If a superclass doesn't implement Serializable, then when a subclass object is deserialized, the superclass constructor will be invoked, along with its superconstructor(s).

37 . What is transient in java?

  • The transient keyword in Java is used to indicate that a field should not be serialized.

38 . What is the difference between Comparable and Comparator ?

  • ComparableA comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances.
    Java.lang.Comparable
    To implements comparable interface, class must implement a single method
    compareTo()int a.compareTo(b)
    You must modify the class whose instance you want to sort. So that only one sort sequence can be created per class. Comparator A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement theJava.util.Comparator interface.Java.lang.Comparator
    To implements comparator interface, class must implement a single method
    compare()int compare (a,b)
    You build a class separate from class whose instance you want to sort. So that multiple sort sequence can be created per class. Implementing Comparable means "I can compare myself with another object." This is typically useful when there's a single natural default comparison. Implementing Comparator means "I can compare two other objects." This is typically useful when there are multiple ways of comparing two instances of a type - e.g. you could compare people by age, name etc.

39 . What's the difference between the methods sleep() and wait()

  • The code sleep(2000); puts thread aside for exactly one second.
    The code wait(2000) , causes a wait of up to one second.
    A thread could stop waiting earlier if it receives the notify() or notifyAll() call.
    The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.

40 . Where you do not have to synchronize to propagate data from one thread to another?

  • There are a few cases where you do not have to synchronize to propagate data from one thread to another, because the JVM is implicitly performing the synchronization for you.
    These cases include:
    • When data is initialized by a static initializer (an initializer on a static field or in a static{} block)
    • When accessing final fields
    • When an object is created before a thread is created
    • When an object is already visible to a thread that it is then joined with

41 . You have thread T1, T2 and T3, how will you ensure that thread T2 run after T1 and thread T3 run after T2?

  • This can be achieved by using join method of Thread class.

42 . What is the advantage of new Lock interface over synchronized block in Java? You need to implement a high performance cache which allows multiple reader but single writer to keep the integrity how will you implement it?

  •     The major advantage of lock interfaces on multi-threaded and concurrent programming is they provide two separate lock for reading and writing which enables you to write high performance data structure like ConcurrentHashMap and conditional blocking.

43 . Why wait(), notify() and notifyAll() must be called from synchronized block or method in Java

    1. IllegalMonitorStateException in Java which will occur if we don't call wait (), notify () or notifyAll () method from synchronized context.
    2. Any potential race condition between wait and notify method in Java.

44 . Is it legal to call the start method twice on the same Thread?

  • It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution. Furthermore,it throws : IllegalThreadStateException - if the thread was already started. So yes, a Thread can only be started once. If so than what do I do if I want to run the thread again? If a Thread needs to be run more than once, then one should make an new instance of the Thread and call start on it.

45 . What is Hashmap?

  •     A Hashmap is a data structure used to implement an associative array, a structure that can map keys to values.     Basically, a HashMap allows you to store items with identifiers. They are stored in a table format with the identifier being hashed using a hashing algorithm. HashMap works on a principle of hashing.

46 . What is hashing?

  • Hashing is a way to assigning a unique code (hashcode) for any variable/object after applying any formula/algorithm on its properties. A true Hashing function must follow this rule: Hash function should return the same hash code each and every time, when function is applied on same or equal objects. In other words, two equal objects must produce same hash code consistently.

47 . What is hashcode?

  • A hashcode is a number generated from any object. This is what allows objects to be stored/retrieved quickly in a Hashtable/HashMap. The hashcode determines which bucket for the hashmap to check.
    If there is more than one object in the bucket then a linear search is done to find which item in the bucket equals the desired item (using the equals()) method.

48 . What is Loadfactor?

  •     An instance of HashMap has two parameters that affect its performance: initial capacity and load factor
    The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created.The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.

49 . What is bucket and what can be maximum number of buckets in hashmap?

  •     A bucket is an instance of the linked list (Entry Inner Class) and we can have as many number of buckets as length of the hashmap at maximum, for example, in a hashmap of length 8, there can be maximum of 8 buckets, each is an instance of linked list.

50 . What is race condition with respect to hashmaps?

  •     When two or more threads see the need for resizing the same hashmap, they might end up adding the elements of old bucket to the new bucket simultaneously and hence might lead to data loss or infinite loops.