Core Java Interview Questions

This section discusses some important questions from the Core Java domain with their best possible answers. I hope this will help you to prepare well for any interview on Core Java Programming. I wish you best of luck for your career.

____________________________________________________________________________________________________________

1. Differentiate between POP and OOP.

Answer: In procedure-oriented programming (POP) approach (e.g. C, PASCAL, COBOL, FORTRAN etc.), a program is divided into components called functions, while in object-oriented programming (OOP) approach (e.g. C++, Java, Python, Ruby etc.); the program is divided into components called objects. Another key difference is that object-oriented programming follows the “bottom-up” approach, while procedural programming follows the “top-down” approach.

Because objects are more versatile, OOP can be used to develop complex programs with less code. The use of objects also facilitates code reuse. In POP, the focus is placed on the functions and sequence of actions to be performed and not on data. In OOP, however, the focus is placed on the data and not the functions. That is why object-oriented programming approach can provide a more realistic view of a software system.

____________________________________________________________________________________________________________

2. Mention the essential features of OOP.

Answer: The essential features of OOP are —

  • Encapsulation: This is an important concept that binds together the data and functions that manipulate the data, and that keeps both safe from outside interference and misuse. Encapsulation led to the OOP concept of data hiding.
  • Inheritance: It is the procedure by which one object acquires the properties of another object. This increases code reusability.
  • Polymorphism: The concept enables one entity to be used as general category for different types of actions. The specific action is determined by the exact nature of the situation. The concept of polymorphism can be explained as “one interface, multiple methods”.

____________________________________________________________________________________________________________

3. What do you know about Java?

Answer: Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. It runs on a variety of platforms, such as MS Windows, Mac OS, and the various distributions of UNIX/LINUX. Presently, Oracle Corporation owns Java technology.

____________________________________________________________________________________________________________

4. What do you mean by platform independent feature of Java?

Answer: Platform independence means that we can write and compile the Java code in one platform (e.g. MS Windows) and can run the generated bytecode in any other supported platform (e.g. Linux, Mac OS etc).

____________________________________________________________________________________________________________

5. What is Java Virtual Machine and how it is related to Java’s platform independent feature?

Answer: When a Java program is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by virtual Machine (JVM) on whichever platform it is being run.

____________________________________________________________________________________________________________

6. Why is Java Architectural Neutral?

Answer: The Java compiler generates an architecture-neutral object file format called bytecode, which makes the compiled code to be executable on many processors, with the presence of Java runtime system.

____________________________________________________________________________________________________________

7. Mention some basic features of Java.

Answer: Some basic features of Java include Object Oriented, Platform Independent, Compiled & Interpreted, Robust, Multithreaded.

____________________________________________________________________________________________________________

8. Mention any two IDEs of Java.

Answer: The two most popular IDEs of Java are NetBeans and Eclipse.

____________________________________________________________________________________________________________

9. Differentiate among JDK, JRE and JVM.

Answer: Java Development Kit (JDK) is the full featured software development kit for Java, including JRE, and the compilers and tools (like JavaDoc, and Java Debugger) to create and compile programs. On the other hand, Java Runtime Environment (JRE) provides Java Virtual Machine (JVM), class libraries, and other components to run applets and applications written in the Java programming language. It also includes browser plugins for Applet execution.  

In essence, JDK is a superset of JRE, and contains everything that is in JRE, plus tools such as the compilers and debuggers necessary for developing applets and applications. Usually, when we only care about running Java programs on our browser or computer we will only install JRE.

____________________________________________________________________________________________________________

10. Differentiate among JSE, JEE and JME.

Answer: Java is a programming language that enables the development on many platforms. It is possible to run Java programs on small devices (like mobile phones), on personal computers and even on mainframes. To be able to do that Java has three development environments: JSE, JEE and JME.

  • JSE: Java Standard Edition or Java SE (i.e. JSE) is a widely used platform for programming in the Java language. It is the platform used to deploy portable applications for general use. In practical terms, JSE consists of a virtual machine, which must be used to run Java programs, together with a set of libraries (or “packages”) needed to allow the use of file systems, networks, graphical interfaces, and so on, from within those programs. The other two environments (JEE and JME) are based on JSE.
  • JEE: Java Enterprise Edition or Java EE (i.e. JEE) differs from the JSE Platform in that it adds libraries which provide functionality to deploy fault-tolerant, distributed, multi-tier Java software, based largely on modular components running on an application server.
  • JME: Java Micro Edition or Java ME (i.e. JME), is a Java platform designed for embedded systems (mobile devices are one kind of such systems). Target devices range from industrial controls to mobile phones (especially feature phones) and set-top boxes.

____________________________________________________________________________________________________________

11. Mention the differences between C++ and Java.

  • Platform dependency – C++ is platform dependent, while Java is platform independent
  • Keyword goto – C++ supports goto statement, on the other hand Java doesn’t.
  • Pointer support – C++ supports pointer concept, while Java does not support it.
  • Multiple inheritance – C++ supports multiple inheritance, on the other hand Java doesn’t .
  • Multithreading – C++ does not have in-build thread support, while Java supports multithreading
  • Virtual keyword – C++ has virtual keyword, it determines if a member function of a class can be overridden in its child class. In Java, there is no concept of virtual keyword.

____________________________________________________________________________________________________________

12. What do you mean by an object?

Answer: Object is a runtime entity and its state is stored in attributes and behavior is shown via methods. Methods operate on an object’s internal state and serve as the primary mechanism for object-to-object communication.

____________________________________________________________________________________________________________

13. What do you mean by a class?

Answer: A class is a blue print from which individual objects are created. A class can contain fields and methods to describe the behavior of an object.

____________________________________________________________________________________________________________

14. What do you mean by a constructor?

Answer: A constructor gets invoked when a new object is created. Every class has a constructor. If we do not explicitly write a constructor for a class the Java compiler simply builds a default no-argument constructor for that class.

____________________________________________________________________________________________________________

15. Mention the types of variables in a Java class.

Answer: A class in Java consist of local variables, instance variables and class variables.

____________________________________________________________________________________________________________

16. What do you mean by local variables in Java?

Answer: Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and it will be destroyed when the method has completed.

____________________________________________________________________________________________________________

17. What do you mean by instance variables in Java?

Answer: Instance variables are variables within a class but outside any method. These variables are instantiated when the class is loaded.

____________________________________________________________________________________________________________

18. What do you mean by class variables in Java?

Answer: Class variables are variables declared with in a class, outside any method, with the static keyword.

____________________________________________________________________________________________________________

19. Mention the types of methods in a Java class.

Answer: A class in Java consist of instance methods and class methods.

____________________________________________________________________________________________________________

20. What is meant by Inheritance and what are its advantages?

Answer: The process by which one class acquires the properties and functionalities of another existing class is called inheritance. The existing class is called superclass and the derived class is called subclass. Inheritance brings reusability of code in a Java application. 

____________________________________________________________________________________________________________

21. Does Java support Multiple Inheritance?

Answer: When a class extends more than one classes then it is called multiple inheritance. Java doesn’t support multiple inheritance whereas C++ supports it, this is one of the difference between Java and C++.

____________________________________________________________________________________________________________

22. Differentiate between IS-A and HAS-A relationship.

Answer: The IS-A (i.e. Inheritance) relationship is basically a generalization-specialization relationship in OOP. A human being is a kind of mammal. Mammal is a kind of animal. It is a relationship between a special class and a general class. The special class inherits the properties of general class.

On the other hand, HAS-A (i.e. Aggregation) relationships are classes whose attributes are comprised of other classes. By composition, we simply mean using attributes that are references to other objects. For example, Car has an Engine. So, Car class has an instance of Engine class as its member.

____________________________________________________________________________________________________________

23. What is the super class of all classes in Java?

Answer: The Object class is the super class of all classes in Java. This class is in the default package of Java that is java.lang. That is why we don’t need to inherit this class. But each and every class in Java inherits it implicitly. JVM does this for all the classes.

____________________________________________________________________________________________________________

24. What is Polymorphism and what are the types of it?

Answer: Polymorphism is the ability of an object to take many forms. The most common use of polymorphism in OOPs is to have more than one method with the same name in a single class. There are two types of polymorphism: compile time polymorphism (e.g. method overloading) and run time polymorphism (e.g. method overriding).

____________________________________________________________________________________________________________

25. What is method overloading?

Answer: When a class has more than one method with the same name but different number, sequence or types of arguments then it is known as method overloading.

____________________________________________________________________________________________________________

26. Is it possible to overload main() method of a class?

Answer: Yes, we can overload main() method in Java.

____________________________________________________________________________________________________________

27. Can we overload a method by just changing the return type and without changing the signature of method?

Answer: No, We cannot do this. To overload a method, the method signature must be different, return type doesn’t play any role in method overloading.

____________________________________________________________________________________________________________

28. What is method overriding in Java?

Answer: If a subclass provides a specific implementation of a method that is already provided by its superclass, it is known as method overriding. It is applicable to instance methods only.

____________________________________________________________________________________________________________

29. Can we override a static method?

Answer: No, we cannot override a static method in Java. Static methods belong to a class and not to individual objects and are resolved at the time of compilation (not at run time). This concept is applicable to instance methods only. 

____________________________________________________________________________________________________________

30. Does Java support operator overloading?

Answer: Operator overloading is not supported in Java. Instead, it is supported in C++.

____________________________________________________________________________________________________________

31. What is static and dynamic binding in Java?

Answer: Binding refers to the linking of a method call to its body. A binding that happens at compile time is known as static binding while binding at runtime is known as dynamic binding.

____________________________________________________________________________________________________________

32. What is the purpose of toString() method in Java?

Answer: The toString() method of the java.lang.Object class returns the string representation of an object. If we want to represent any object as a string, toString() method comes into existence. In order to print any object, Java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on our implementation. By overriding the toString() method we can return values of the object, so we don’t need to write much code.

____________________________________________________________________________________________________________

33. What are the significant features of packages in Java?

Answer: A package is the combination of related types that provides access protection and name space management. The packages in Java are basically containers of classes, interfaces, sub-packages, enumerations and annotations. The significant features of Java package are as follows-

  • Logical grouping of classes and interfaces: The classes and interfaces that have the similar kind of functionalities can be put together into a common package.
  • Access conflict resolution: If we have two classes with the same name under the same directory that might lead to access conflict. So, it will be better to put them into two separate packages in order to resolve the access conflict.
  • Support for class libraries: The package concept provides wider range of class libraries support for the Java programmer. This ensures the reusability aspect of Java packages and APIs.
  • Access Protection: Java package provides access protection for different types of access specifiers namely public, private, protected and default.

____________________________________________________________________________________________________________

34. Explain the use of Wrapper classes in Java.

Answer: A Wrapper class wraps (encloses) around a data type and gives it an object appearance. Wherever, the data type is required as an object, the concept of Wrapper class can be used. Wrapper classes include methods to unwrap the object and give back the original data type. It can be compared with a chocolate. The manufacturer wraps the chocolate with some foil or paper. The customer takes the chocolate, removes and throws the wrapper and eats it. See the following statements:

int a = 100;
Integer obj = new Integer(a);

The int data type a is converted into an object, obj using Integer class. The obj object can be used in Java programming wherever a is required an object. The following code can be used to unwrap (getting back int from Integer object) the object obj.

int i = obj.intValue();

The intValue() is a method of Integer class that returns an int data type.

There are mainly two uses with wrapper classes:

  • To convert simple data types into objects, that is, to give object form to a data type; here constructors are used.
  • To convert strings into data types (known as parsing operations), here methods of type parseType( ) [i.e., parseInt( ), parseDouble( ) etc.] are used.

____________________________________________________________________________________________________________

35. Differentiate between object and reference in Java.

Answer: Let’s start with an example. We might have contacts of many people in our mobile. We can use a contact to call a person. The person is actually somewhere else, but the contact helps us to call them. We can think of a reference variable to be a contact and object to be the actual person we are calling. Basically a reference variable just points to an actual object. For example if we have a class named Person such as:

class Person {
    String name = "Ram";
   int age = 27;
}

If we instantiate the class Person like this:

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 area of JVM. The reference variable p only contains the memory address of Person class object on the heap area. So the actual value of p can be said to be an address on the heap.

____________________________________________________________________________________________________________

36. Why is Java called a ‘strongly typed’ programming language?

Answer: Java is a strongly typed programming language because every variable must be declared with a data type. A variable cannot start off life without knowing the range of values it can hold, and once it is declared, the data type of the variable cannot change.

____________________________________________________________________________________________________________

37. Why can’t constructors be final, static, or abstract in Java?

Answer: When we set a method as final it means that we don’t want any class override it. But the constructor according to the Java Language Specification (JLS) can’t be overridden, so it is not possible.

When we set a method as abstract it means that the method doesn’t have a body and it should be implemented in a child class. But the constructor is called implicitly when the new keyword is used so it can’t lack a body.

When we set a method as static it means that the method belongs to the class, not a particular object. But the constructor is implicitly called to initialize an object, so there is no purpose in having a static constructor.

____________________________________________________________________________________________________________

38. How is a Java source code file named?

Answer: A Java source code file may contain at most one public class or interface. If a public class or interface is defined within a source code file, then the source code file must take the name of the public class or interface. If no public class or interface is defined within a source code file, then the file must take on a name that is different than its classes and interfaces. Source code files use the .java extension.

____________________________________________________________________________________________________________

39. Explain the significance of: public static void main (String args[]).

Answer: All Java stand-alone programs begin execution with the method named main(). This method gets executed by the JVM and has the following signature:

public static void main(String args[])

Declaring this method as ‘publicmeans that it is accessible from outside the class so that the JVM can find it when it looks for the program to start executing it. The keyword static‘ denotes that the main() method is a direct member of the class to which it belongs. It is necessary that the method is declared with return type ‘void‘ (i.e. no value is returned from the method). The main() method contains a String argument array that can contain the command line arguments.

____________________________________________________________________________________________________________

40. Explain the significance of: System.out.pritnln().

Answer: System.out.println() is a Java statement that prints the argument passed, into the System.out which basically denotes the standard output stream.

  1. System: It is a class in the java.lang package.
  2. out: It is a static member of the System class, and is an instance of java.io.PrintStream class
  3. println(): It is a method of java.io.PrintStream class. This method is overloaded to print message to output destination, which is typically a console or file.

____________________________________________________________________________________________________________

41. Mention the types available in Java.

Answer: In Java, two types are available namely primitive type and object reference type (i.e. reference type).

____________________________________________________________________________________________________________

42. List the primitive types in Java.

Answer: Java primitive types are listed below:

  • byte – 8 bit (integer)
  • short – 16 bit (integer)
  • int – 32 bit (integer)
  • long – 64 bit (integer)
  • float – 32 bit (single-precision floating-point)
  • double – 64 bit (double-precision floating-point)
  • char – 16 bit Unicode
  • boolean – true / false 

____________________________________________________________________________________________________________

43. What is typecasting in Java?

Answer: There are two types of typecasting in Java, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.

____________________________________________________________________________________________________________

44. Can a class have multiple constructors?

Answer: Yes, a class can have multiple constructors with different parameters. Among them, which constructor gets used for object creation depends on the arguments passed while creating the objects.

____________________________________________________________________________________________________________

45. What is dynamic binding or late binding?

Answer: Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding means that the code associated with a given procedure call is not known until the time of the call at run time.

____________________________________________________________________________________________________________

46. What is runtime polymorphism or dynamic method dispatch?

Answer: Runtime polymorphism or dynamic method dispatch is a procedure in which a call to an overridden method is resolved at run time rather than at compile time. In this procedure, an overridden method is called through the reference variable of a superclass.

____________________________________________________________________________________________________________

47. How garbage collection is done in Java?

Answer: In Java, when an object is not referenced any more, garbage collection takes place and the object is destroyed automatically. For automatic garbage collection Java calls either System.gc() method or Runtime.gc() method.

____________________________________________________________________________________________________________

48. How objects of a class are created if no constructor is defined in the class?

Answer: Even if no explicit constructor is defined in a Java class, objects get created successfully as a default constructor is implicitly used for object creation. This constructor has no parameters.

____________________________________________________________________________________________________________

49. What do you mean by exception in Java? What is exception handling?

Answer: An exception in Java is an unexpected event, which occurs during the execution of a program that interrupts the normal flow of the program’s instructions. When an exception occurs within a method, the method creates an object and hands it off to the runtime system.

After a method throws an exception, the runtime system attempts to find some mechanism to handle it. Java exception handling is used to handle exceptional conditions in a program systematically by taking the necessary actions. The purpose of exception handling mechanism is to provide a means to detect and report exceptional conditions so that appropriate actions can be taken. The exception handling mechanism basically consists of two segments, one to detect unexpected events and to throw exceptions and the other to catch exceptions and to take appropriate actions.

Java uses the keyword try to preface a block of code that is likely to cause an abnormal condition and “throw” an exception. A catch block defined by the keyword catch “catches” the exception thrown by the try block and handles it appropriately. The catch block is added immediately after the try block. See the code snippet below.

try {
// block of code that generates an exception
}
catch (ExceptionType e) {
// block of code that handles the exception for ExceptionType
}

See here for details

____________________________________________________________________________________________________________

50. Differentiate between checked and unchecked exception in Java.

Answer: When an exception occurs, it must be dealt with in either a “try/catch” block or by declaring a “throws” in a method. This concept is called to catch or to declare an exception object. Now during compile time whether to catch/declare an exception or not, based on this, Java also defines two kinds of exceptions called checked and unchecked exceptions:

  • Checked exceptions: Compiler will check that we have done one of the two things (catch, or declare).  So these are called checked exceptions. Exceptions that inherit from the java.lang.Exception class (except RuntimeException and its subclasses) are checked exceptions. Checked Exceptions force programmers to deal with the exception that may be thrown by the API, either in a catch clause or by forwarding it outward with the throws clause. E.g. IOException, FileNotFoundException etc.
  • Unchecked exceptions: Both java.lang.RuntimeException and java.lang.Error and their subclasses are not checked by the Java compiler (even though we can choose to catch, or declare, it is not required).  So, these two are called unchecked exceptions. Unlike checked exceptions the subclasses of RuntimeException do not need to be caught at compile time. The subclasses of Error often cannot be. E.g. ArithmeticException, NullPointerException, StackOverflowError, VirtualMachineError etc.

____________________________________________________________________________________________________________