Most Common Interview Questions on Java

What is Java?

Java is a popular programming language and development platform that allows developers to write code that can run on any machine regardless of architecture or platform. Some key Java features include object-oriented programming, platform independence, and high performance.

What are the main features of Java?

Some of the main features of Java include:

  • Platform Independence – Java code can run on any platform with a Java Runtime Environment.
  • Object Oriented – Everything in Java revolves around objects and classes. The language provides full support for object-oriented programming concepts like inheritance, abstraction, polymorphism and more.
  • Portable – Java applications can be run on any machine irrespective of architecture.
  • Robust – Java utilizes strong memory management and error handling to provide secure and stable applications.
  • Interpreted – Java code is interpreted line by line at runtime for platform flexibility.

What is JVM and how does it work?

JVM stands for Java Virtual Machine. It is the runtime environment in which Java code executes. JVM reads and interprets compiled Java binary code (bytecode) and translates it into native machine code. This makes Java platform-independent. There is a separate JVM process for every Java application running in the machine.

Explain the platform independence of Java with an example.

Java platform independence means that as long as a JVM is present, any Java program can run on top of it irrespective of underlying hardware or operating system configurations like Windows, Mac or Linux. For example, a Java application created on a Windows OS can be compiled into bytecode and run on a Mac by feeding the bytecode to the JVM on MacOS.

What is bytecode in Java?

Bytecode is a set of instructions generated by Java compilers to target the JVM. Java code is first compiled into bytecode that is then interpreted by the JVM at runtime. Bytecode is more platform-independent compared to native machine code.

What are the main Java concepts every developer should know?

The four key concepts Java developers should know are:

  • Object-oriented programming
  • Inheritance
  • Polymorphism
  • Encapsulation A strong grasp of these main OOP concepts is essential for writing Java code that adheres to good practices and design principles.

What is a class in Java?

A class is a blueprint or template from which objects are created. A Java class defines attributes and behaviors as fields and methods that will be common for all objects of that class. Classes allow related data and functions to be bundled for cleaner code.

What is an object in Java?

An object is an instance that inherits the attributes and behaviors from its class blueprint. Objects contain state and operations that simulate a real-world entity. An object’s state is stored in attributes and its functions are implemented via methods in Java. Multiple objects can be instantiated from a single class.

What is inheritance in Java?

Inheritance is an OOP concept where a derived subclass gains all data fields and methods defined in a parent superclass. The child class can also override existing methods and add new ones to specialize behavior while reusing common logic in superclasses. Inheritance enables code reusability.

What is method overloading and overriding?

Method overloading refers to the practice of creating multiple methods within the same class that share the same name but have different parameter lists. Method overriding means having two methods with the same name and parameter lists across parent and child classes, with the subclass overriding the parent.

What is an interface in Java?

An interface is a reference type that only contains abstract methods and final variables. There is no method body and are implemented by classes. Interfaces specify what classes inheriting from them must do without dictating how. This enables loose coupling between classes.

What is polymorphism in Java?

Polymorphism represents the ability of different data types to respond to a common interface. In Java, the same method or operator can behave differently depending on the runtime data types of operands. Method overloading and overriding are key examples of polymorphism.

What is abstraction in Java?

Abstraction focuses on the essential features of an entity while hiding the background details and implementation complexities. Java uses abstract classes and interfaces to enable abstraction. An abstract method only contains a method signature and is implemented by all inheriting subclasses.

Explain Java encapsulation.

Encapsulation refers binding together code and data related to an entity, while hiding the implementation details from external components. Encapsulation is achieved by creating classes and exposing public methods while keeping fields private. This prevents external tampering.

What are access modifiers in Java?

Java provides access modifiers to set accessibility of classes, methods, constructors and member variables. Commonly used access modifiers in Java include public, private and protected. Fields are marked private while methods tend to be public to allow object access.

What is the difference between heap and stack memory?

The stack stores reference variables and call return values. Stack has size limits and references to objects are stored here. Heap memory stores the actual objects loaded at runtime and dynamically allocates memory to programs based on consumption – there is no pre-defined limit.

What are constructors in Java?

Java constructors are special methods that create and initialize newly created objects. Constructor names must match the class name and cannot have an explicit return type. Constructors can take parameters to initialize attributes during object creation. Creating a no-args constructor is a best practice.

Why is Java platform independent?

Java platform independence stems from it being an interpreted language that gets compiled to bytecode during runtime by the JVM on any system. This abstracts away machine dependencies. Java code uses the same bytecodes regardless of the underlying hardware or operating system.

What are packages in Java?

Packages in Java act as containers for related classes allowing modularization and code reuse. Package declaration defines which group a class belongs to. Packages prevent naming conflicts between different modules. Java also provides access controls through package imports within classes.

What is a Java main method?

The main() method is an application entry point and is mandatory for any executable Java class. main() is called by the JVM when running a Java program. This method must be defined as static public void and receives String array argument containing runtime arguments.

How does Java arraycopy work in memory?

System.arraycopy() allows fast in-memory copying of arrays behind the scenes without having to shunt data out to application layer. Both destination and source arrays must be instantiated with element sizes defined. arraycopy() leverages native system memory copying functions for efficiency.

What is Autoboxing and Unboxing?

Autoboxing refers to the automatic conversion between wrapper classes (like Integer) to primitive types (like int) during compilation. Unboxing is reverse conversion from wrapper to primitive. This was introduced to reduce developer effort on manual conversions.

What are Java annotations?

Annotations provide metadata and supplementary information on Java code – they are informative comments that are embedded in and persist alongside the code. Annotations do not alter program semantics and execution behavior. Common annotations include @Override, @Deprecated, @SuppressWarnings and more.

Compare ArrayList vs LinkedList.

ArrayLists dynamically resize arrays to enable O(1) random access. But insertion and deletion is slow as remaining elements must be shifted. LinkedLists enable fast O(1) additions and removals via reference pointer shifting but slow O(n) random access without direct indexing.

What is a singleton class?

A singleton class restricts instantiation to only one object across entire application. Singleton pattern ensures global point of access and prevents mismatched versions. Java handles singletons by creating a private constructor, a static class attribute and public access method.

When should static methods be used?

Static methods belong to the class rather than on any object instance. They retain no state information and serve as utility methods that perform operations based solely on input parameters. Methods that don’t depend on internal object state should be declared static for wider reusability.

What is final keyword?

The final keyword prevents inherited classes from changing the meaning of constants and overridden methods. Final classes cannot be extended, final attributes cannot be modified, and final methods cannot be overridden. Final variables act as constants.

What does the static word mean in Java?

The static keyword in Java signifies that a member belongs to a type itself rather than individual objects. Static members get allocated memory only once per class loads or initialize rather than per object instance created. All instances share the same static member.

What is variable shadowing in Java?

Variable shadowing refers to declaring a local variable within a method with the same name as an instance or class attribute. This shadows the attribute from the class since the new local variable takes higher precedence inside the method body.

What are Java Collections Framework?

Java Collections Framework are a set of reusable data structures like ArrayList, LinkedList, HashMaps that allow storage, retrieval, manipulation and traversal for data elements. Common interfaces include Collection, Set, List, Queue, Map – these are implemented by classes providing reusable data containers.

What are lambda expressions in Java?

Lambda expressions are anonymous inner functions that can be passed into higher-order functions and actions. Lambdas provide implementation behavior to interfaces that have just one abstract method. These lightweight closures reduce coding syntax and allow passing behavior as parameters.

How is a Java string pool implemented?

Java String Pool refers to a storage area in Java heap space where literal strings get stored and referenced from instead of creating multiple instances. String manipulation instead changes the reference to different literals within the string pool to avoid wasting too much transient memory which can slow performance.

What is thread synchronization in Java?

Synchronization refers to controlling concurrent access shared mutable data to avoid inconsistencies due to race conditions. Java provides synchronized code blocks restricting execution of critical section to only one thread at a time. syncronized prevents data corruptions imposing exclusive execution.

What is Java Serialization?

Java provides serialization where objects are converted into byte streams that can be persisted into memory or file storage. Deserialization constructs object back when needed. This allows saving object states meaning fields, class types and inheritance relationships so it can be transferred.

What are anonymous Java inner classes?

Anonymous inner classes allow creating inline implementation for a class avoiding the hassle of explicit subclassing just for temporary use. Helps reduce code syntactically where functional implementation matters only once rather than a formally defined class everytime.

Differentiate Checked vs Unchecked Exceptions.

Checked exceptions require mandatory catch block handling as they indicate invalid conditions that can potentially be resolved by code. Unchecked exceptions typically user or environment issues like unsupported operations not catchable. RuntimeExceptions are unchecked since external factors.

What is a memory leak in Java?

Memory leaks happen when applications hold references to unused allocated instance hindering garbage collection. Common in long-running apps that frequently create-destroy objects. Leaked memory cannot be reused slowing down systems as more memory gets allocated over time.

How are Java exceptions handled?

Via try-catch blocks.

try {
  // Code that could throw an exception
  int x = 10 / 0; // ArithmeticException

  int[] numbers = new int[5];
  numbers[10] = 50; // ArrayIndexOutOfBoundsException

  String str = null;
  int length = str.length(); // NullPointerException
  
} catch (ArithmeticException e) {
  // Handle arithmetic exception
  System.out.println("Cannot divide by zero!");
} catch (ArrayIndexOutOfBoundsException e) {
  // Handle array boundary issue
  System.out.println("Index out of bounds for array!");  
} catch (NullPointerException e) {
  // Handle null value
  System.out.println("Cannot invoke method on null object!");
} finally {
  // Optional finally block that executes after try/catch
  System.out.println("Performing clean up steps");
}

// Rest of program continues
System.out.println("Program completed");
Java

In this example, the try block contains code that could potentially throw 3 different exceptions. The catch blocks handle each specific exception type with custom error messages. The optional finally block executes cleanup code regardless of exception outcomes before continuing program execution after the try-catch.

This allows anticipating and gracefully handling issues that arise during runtime without abrupt program crashes.

What design patterns are useful?

Commonly used Gang of Four design patterns in Java include Singleton, Factory, Facade, Observer, Decorator, Controller, Adapter, Composite, Strategy, Template Method, Iterator and more – all solve recurring software design problems around instantiation, organization and execution.

What are the advantages of Java?

Java advantages include platform independence, automatic memory management, advanced security features, portability across devices, robust technology ecosystem with third-party libraries and frameworks, versatile deployment onto cloud infrastructure and leveraging modern application architectures.

Similar Posts