0% found this document useful (0 votes)
2 views

Diff or When to go for abstract class and when for interface (1)

The document provides a comprehensive overview of Object-Oriented Programming (OOP) concepts in Java, including key principles such as encapsulation, abstraction, inheritance, and polymorphism. It also discusses Java's memory model, the role of the Java Virtual Machine (JVM), class loaders, and various Java features introduced in Java 8, such as lambda expressions and the Streams API. Additionally, it covers exception handling, multithreading concepts, and various Java tools and frameworks, making it a valuable resource for understanding Java programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Diff or When to go for abstract class and when for interface (1)

The document provides a comprehensive overview of Object-Oriented Programming (OOP) concepts in Java, including key principles such as encapsulation, abstraction, inheritance, and polymorphism. It also discusses Java's memory model, the role of the Java Virtual Machine (JVM), class loaders, and various Java features introduced in Java 8, such as lambda expressions and the Streams API. Additionally, it covers exception handling, multithreading concepts, and various Java tools and frameworks, making it a valuable resource for understanding Java programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Object Oriented Programming in JAVA (Just Another Virtual Accelerator)

Java is designed to be platform-independent, the concept of "write once, run anywhere"


(WORA)

JVM (Java Virtual Machine) is machine-dependent in the sense that each platform or
operating system requires its own implementation of the JVM. different hardware
architectures like x86, ARM, or others.

Encapsulation: Wrapping of the data (variables) and methods that into a single unit or
class, and restricting access to some of the object's components.

Abstraction: Hiding the complex implementation details and showing only the necessary
features of an object.

Interface: Defines a contract for what a class can do, Interfaces can only declare
methods (prior to Java 8) without implementations and constants.

Starting from Java 8, interfaces can also have default and static methods with
implementations.

A default method in Java is a method defined in an interface with a default


implementation. This feature was introduced in Java 8 to allow interfaces to have concrete
methods
Interface memory (interfaces do not have any memory associated with them in the
sense of storing data) and can we override default method? (Yes)

Abstract Class: Provides a common base class for other classes to extend. An abstract
class can have both abstract methods (without implementation) and concrete methods
(with implementation). It can also have member variables and constructors. Or to maintain
a hierarchy

Inheritance: Creating a new class (derived class) that inherits attributes and behaviors
(methods) from an existing class (base class), As child parent relationship.

Types of inheritance java supported: single, multilevel, hierarchical, and hybrid

The "diamond problem" is a term often used in the context of multiple inheritance,

Polymorphism: When you override a default method, the overridden method in the class
will be called, even if the method is called on a reference of the interface type.

Compile time (method overloading), Run time (method overriding child-parent relation),
Explain the different access modifiers in Java.
Private: The members are accessible only within its own class.

Default: (No modifier) The member is accessible only within its own package.

Protected: The member is accessible within its own package and by subclasses in other
packages.

Public: The member is accessible from any other class.

JMM memory model or java memory model (method area/heap/stack area)


How JVM Works? - JVM Architecture
Class loaders?

A class loader is a subsystem of JVM that loads Java classes dynamically during the
runtime. Every Java class is loaded by a class loader. When a Java program is executed,
class loaders are responsible for loading the class files into the JVM. It is a part of Java
Runtime Environment (JRE).

The JVM does not need to know about files and file systems, as this is delegated to the
class loader.

There are three main types of class loaders:

• Bootstrap Class Loader:

The bootstrap class loader is the first-class loader to load classes. It is responsible for
loading the core Java classes that are part of the JRE.

• Extension Class Loader:

The extension class loader is responsible for loading classes from the JRE extension
directory.

• System Class Loader:

The system class loader is responsible for loading classes from the classpath.

Class loaders are also used to implement security features. For example, the class loader
can be used to prevent classes from being loaded from untrusted sources.

Object class?

In Java, the Object class is the root class of all classes. Every class in Java implicitly or
explicitly extends the Object class. It resides in the java.lang package, which is
automatically imported into every Java program.

1. toString(): Returns a string representation of the object. By default, it returns the


class name followed by the hash code of the object.
2. equals(Object obj): Indicates whether some other object is "equal to" this one.
By default, it checks for reference equality.
3. hashCode(): Returns a hash code value for the object. This method is used by
hash-based data structures like HashMap.
4. getClass(): Returns the runtime class of the object.
5. notify(), notifyAll(), and wait(): These methods are used for inter-thread
communication and synchronization.

Java Interned? "String pool" or "intern pool."

String literals that are interned are stored in this pool. When you create a string literal that
matches an existing one in the pool, the JVM returns a reference to the existing string
instead of creating a new one.
• You can explicitly intern strings using the intern () method, which ensures that
the string is stored in the intern pool.
• Interning strings can be useful for conserving memory and optimizing string
comparison operations.

Serialization? UUID, transients keyword

Serialization (ObjectOutputStream) is the process of converting an object into a byte


stream for storage or transmission.

Deserialization is the reverse process of reconstructing an object from its serialized form.
In Java, serialization is achieved by implementing the Serializable interface.
Serialization allows objects to be saved to files or sent over networks. Deserialization
(ObjectInputStream)reconstructs objects from byte streams, restoring their state.

Universally Unique Identifier is a 128-bit value typically represented as a sequence of


hexadecimal digits separated by hyphens. It guarantees uniqueness across space and
time, even when generated by different systems. java.util.UUID.randomUUID()
transient keyword is used to indicate that a field should not be serialized when an object
of the class is serialized. And are initialized to their default values

Marker interface? Tagging interface or just an empty interface

Java 8 new features


Lambda Expressions, Functional Interfaces Default Methods, Date and Time API
(java.time), Completable Future Class, Optional Class , Streams API

Lambda expressions introduce a new syntax for defining anonymous functions in Java.

Lambda expressions are particularly useful when working with collections and the new
streams API.

Functional interface = lambda expression SAM (Single Abstract Method)

Default Methods: @refer interface related

Optional class is a container object that may or may not contain a value.It helps to
eliminate null

• Optional.of(value) creates an Optional instance containing the specified non-


null value. If the value is null, it throws a NullPointerException.
• Optional.ofNullable(value) creates an Optional instance containing the
specified value. If the value is null, it returns an empty Optional.

CompletableFuture allows you to perform tasks asynchronously, meaning that the


computation can be executed concurrently with other tasks without blocking the calling
thread.

CompletableFuture.supplyAsync(() -> "Hello, World!")

.thenAccept(result -> System.out.println("Result: " + result));

• Non-blocking Operations: Unlike Future, which requires blocking operations to


check if a task is complete (using get or isDone), CompletableFuture offers non-
blocking operations with callback mechanisms to handle task completion.
• Exception Handling: It provides better mechanisms for handling exceptions in
asynchronous computations using methods like exceptionally, handle, and
whenComplete.
• Manual Completion: CompletableFuture allows manual completion of the future
using the complete and completeExceptionally methods, which is useful for
integrating with other asynchronous APIs.

Exception example:

CompletableFuture.supplyAsync(() -> {

if (true) throw new RuntimeException("Error occurred!");

return "Result";

}).exceptionally(ex -> {

System.out.println("Exception: " + ex.getMessage());

return "Default Result";

}).thenAccept(result -> {

System.out.println("Result: " + result);

});

Functional programming using steam api *

Map meathod in stream api

Method References: In Java?

Method references in Java provide a shorthand syntax for invoking methods or


constructors using lambda expressions. They allow you to reference methods or
constructors without actually invoking them, making your code more concise and
readable.

// Lambda expression

Function<Integer, String> converter = (num) -> Integer.toString(num);


// Method reference ClassName::staticMethodName

Function<Integer, String> converter = Integer::toString;

static Keyword?

• The static keyword is used to declare static variables and static methods in Java.
• When a variable or method is declared as static, it belongs to the class rather than
to instances of the class. This means there is only one instance of the static
member shared across all instances of the class.
• Static variables are initialized when the class is loaded into memory and are
typically initialized with default values.
• Static methods can be invoked without creating an instance of the class.

Static Initialization Block (static Block)?

• Static initialization blocks are executed when the class is loaded into memory, just
like static variables.
• They are particularly useful when static variables need complex initialization logic
beyond simple assignment.
• Static initialization blocks are executed in the order they appear in the class, from
top to bottom.

static {
// Static initialization block
staticVariable = calculateStaticVariable();
}

Comparable and comparator?

• Comparable is used to define the natural ordering of objects within a class,It


contains a single method compareTo(Object obj) that compares the current
object with another object.
• Objects that implement the Comparable interface can be directly sorted using
methods like Collections.sort() or Arrays.sort().
public class MyClass implements Comparable<MyClass> {
private int value;
// Constructor, getters, setters
@Override
public int compareTo(MyClass other) {
return Integer.compare(this.value, other.value);
}
}

Comparator Interface:

• The Comparator interface is used to define custom comparison logic for sorting
objects.
• It contains a single method compare(Object obj1, Object obj2) that
compares two objects.
• Comparator objects can be passed to sorting methods to specify the custom
comparison logic.
public class MyComparator implements Comparator<MyClass> {
@Override
public int compare(MyClass obj1, MyClass obj2) {
return Integer.compare(obj1.getValue(), obj2.getValue());
}
}

Concurrent hash map? Synchronized keyword is one at a time


HashMap?
Errors and Exceptions?

Errors:

Errors are usually caused by the JVM or the underlying system encountering problems that
prevent it from continuing normal operation.

Examples of errors include OutOfMemoryError, StackOverflowError,


VirtualMachineError, and LinkageError.

Errors are not meant to be caught or handled by applications. They indicate severe
problems that often require intervention at the system level or by the JVM itself.

Exceptions:

• Exceptions represent exceptional conditions that occur within the application's


normal flow of execution.
• Exceptions can be caused by various factors, such as invalid user input, network
failures, file I/O errors, or programming mistakes.
• Examples of exceptions include NullPointerException,
IllegalArgumentException, IOException, ClassNotFoundException, etc.
• Exceptions can be caught and handled by the application using try-catch

NoClassDefFoundError (runtime if .class file not found or deleted) vs


ClassNotFoundException (compile time if class file not found)?

• What is the difference between checked and unchecked exceptions?


the exceptions that must be declared in a method's throws clause (checked
exceptions) and
those that do not need to be declared (unchecked exceptions).
• What is the difference between throw and throws in Java?
throw keyword, which is used to explicitly throw an exception, and
throws keyword, which is used to declare exceptions that a method may throw.

• How do you handle exceptions in Java?


Explanation of techniques for handling exceptions, such as using try-catch blocks,
throwing exceptions, and using finally blocks for cleanup.
• What is the purpose of the finally block in exception handling?
Understanding the role of the finally block in exception handling and its use for
cleanup tasks that should always be executed, regardless of whether an exception
occurs.
• What is the difference between final, finally, and finalize in Java?
final keyword (used to declare constants or make variables immutable), the
finally block (used in exception handling), and
the finalize() method (used for object cleanup before garbage collection).

• What are some common Java exceptions and their meanings?


Familiarity with commonly encountered exceptions in Java, such as
NullPointerException, ArrayIndexOutOfBoundsException,
FileNotFoundException, IOException, etc.
Multi-threading

Thread dump(deadlock how to identify) or stack and hierarchy

What is? Thread pool? Concurrency? Deadlock/starvation? Simaphore? Binary- producer-


consumer (mutex lock) ? Dinning philosopher
Exceptions in multi-threaded Env

Using try-catch Blocks

Using Thread.UncaughtExceptionHandler

public class Main {


public static void main(String[] args) {
Thread thread = new Thread(() -> {
throw new RuntimeException("Exception in thread");
});

thread.setUncaughtExceptionHandler((t, e) -> {
System.out.println("Exception in thread " + t.getName() + ": " + e.getMessage());
e.printStackTrace();
});
thread.start();
}
}
Using ExecutorService and Future: When using an ExecutorService to manage threads,
you can submit tasks that return a Future. You can then handle exceptions by calling the
get method on the Future, which will throw an ExecutionException if the task
encountered an exception.

import java.util.concurrent.*;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(2);

Callable<String> task = () -> {


if (true) throw new RuntimeException("Exception in task");
return "Task result";
};
Future<String> future = executor.submit(task);
try {
String result = future.get();
} catch (InterruptedException | ExecutionException e) {
System.out.println("Exception: " + e.getCause().getMessage());
e.printStackTrace();
} finally {
executor.shutdown();
}
}
Difference between Runnable and Callable ?

Runnable:
• Does not return a result.
• Cannot throw checked exceptions.
• Functional method: void run().
• Used for simple tasks or when no result is needed.
Callable:
• Returns a result.
• Can throw checked exceptions.
• Functional method: V call() throws Exception.
• Used for tasks that need to return a result or handle exceptions. especially when
using ExecutorService for concurrent execution.

++Springboot and rest api url structure n basic bean life cycle

@annotations? restcontroller?webservice?

@autowired?

Junit testing but we’re using spock

Micro services (optional) monolithic?

Multiprocessing? OSI model?

Sql basic? Joins? Union all? Why left outer join is faster?One sample sql havingclause?
Partition?

Microservices with apache kafka? Docker?

Kunernetes? Cicd pipelines optional

React js basic
Neo4j, graphQL, nodejs, java script, aws, gcp

Cloud, json/xml

Distributed system + scala + tableau + looker

Bi Tools custom

Design patterns?

1+2(3-2) expression resolution using visitor and tree, reverse link list? Sorting algorithms
with time complexity,

Recursion based examples

Java generics

System design for multi processing

High level + Low level with java

Caching + kafka

Design a redbus multithreading book a seat

Taxi booking etc

2pointers sliding window

Work@tech

Multithreading problem 1 to 1000

Divide n conquer approach

Time complexity analysis


Multi threading bus problem

List string count, patterns

Design custom threadpool and cache

Feedback——————————

introduction little slow abstraction vs interfae calarity asked only give ans

immutable, class custome, clonable (SHAWOD, DEEP) HOW? object copy exception
custome cutsome thread pool

ask intervieer to goin rigth exception

Procedu serial version unid

chid method overide to avoid serilization

how to sort value by values, comparator with key

++String pool

++design pattern

++class loaders

Teradata, hive, postgres

GCP bigquery, firestore, oauth, bigtables, k8s

Awa lambda, async, dynomodb

Neo4j, mongodb

Sping cloud, swagger, rest api, micro services, postman


Scala, dataproc , hdfs

Replit, redis

Render.com

You might also like