Thursday, December 18, 2025

Java Object-Oriented Design (OOD)

 

1. What is OOPS?

Answer:


OOPS stands for Object-Oriented Programming System.

It is a programming paradigm where the software design is based on objects, which represent real-world entities.
Each object is an instance of a class and contains state (data) and behavior (methods).


2. What are the basic concepts of OOPS?

Answer:
The four fundamental principles of OOPS are:

  1. Abstraction

  2. Encapsulation

  3. Inheritance

  4. Polymorphism


3. What is a Class?

Answer:
A class is a blueprint or template used to create objects.
It defines:

  • Properties (variables / fields)

  • Behaviors (methods)

Example:

class Car { String color; void drive() {} }

4. What is an Object?

Answer:
An object is a runtime instance of a class.
It has:

  • State → variables

  • Behavior → methods

  • Identity → unique memory reference


5. What is Encapsulation?

Answer:
Encapsulation is the process of binding data and methods together and restricting direct access to object data.

It is achieved using access modifiers:

  • public

  • protected

  • default

  • private

Example:

private int balance; public int getBalance() { return balance; }

6. What is Polymorphism?

Answer:
Polymorphism means “many forms”.
It allows the same method to behave differently based on the object type.

Types:

  • Compile-time (Method Overloading)

  • Runtime (Method Overriding)


7. What is Inheritance?

Answer:
Inheritance allows one class to reuse properties and methods of another class.

Types:

  • Single Inheritance

  • Multilevel Inheritance

  • Hierarchical Inheritance

Java does not support multiple inheritance with classes but supports it using interfaces.


8. What are Manipulators?

Answer:
Manipulators are special functions used with stream operators (<<, >>) in C++ to format input/output.

Examples:

  • endl

  • setw

⚠️ Not applicable in Java.


9. What is a Constructor?

Answer:
A constructor is a special method used to initialize an object.

Rules:

  • Same name as the class

  • No return type

  • Automatically invoked during object creation

class Person { Person() {} }

10. What is a Destructor?

Answer:
A destructor releases resources when an object is destroyed.

⚠️ Java does not support destructors.
Garbage Collection handles memory cleanup.


11. What is an Inline Function?

Answer:
An inline function is expanded at compile time to reduce function call overhead.

⚠️ Java does not support inline functions explicitly (JIT compiler optimizes internally).


12. What is Function Overloading?

Answer:
Function overloading allows multiple methods with the same name but different:

  • Parameters

  • Data types

  • Number of arguments

Example:

int add(int a, int b) double add(double a, double b)

13. What is a Virtual Function?

Answer:
A virtual function supports runtime polymorphism.

⚠️ In Java:

  • All non-static methods are virtual by default

  • Implemented using method overriding


14. What is a Friend Function?

Answer:
Friend functions allow access to private members of a class.

⚠️ Java does NOT support friend functions (encapsulation is strict).


15. What is Operator Overloading?

Answer:
Operator overloading allows operators to behave differently for different operands.

⚠️ Java does not support operator overloading
(Except + for String concatenation).


16. What is an Abstract Class?

Answer:
An abstract class:

  • Cannot be instantiated

  • Can contain abstract and non-abstract methods

abstract class Shape { abstract void draw(); }

17. What is a Ternary Operator?

Answer:
The ternary operator is a conditional operator:

result = (condition) ? value1 : value2;

18. What is the use of finalize() method?

Answer:
finalize() was used for cleanup before garbage collection.

⚠️ Deprecated in Java 9+
Not recommended for resource management.


19. What are the types of Arguments?

Answer:

  1. Call by Value – Java supports this

  2. Call by Reference – Not supported directly in Java

Java always passes object references by value.


20. What is the super keyword?

Answer:
super is used to:

  • Access parent class methods

  • Access parent constructor

  • Access hidden variables


21. What is Method Overriding?

Answer:
Method overriding allows a child class to provide its own implementation of a parent class method.

Rules:

  • Same method name

  • Same parameters

  • Same return type


22. What is an Interface?

Answer:
An interface contains:

  • Abstract methods

  • Default methods (Java 8+)

  • Static methods

Used to achieve multiple inheritance in Java.


23. What is Exception Handling?

Answer:
Exception handling manages runtime errors using:

  • try

  • catch

  • finally

  • throw

  • throws


24. What are Tokens?

Answer:
Tokens are the smallest units of a program.

Examples:

  • Keywords

  • Identifiers

  • Constants

  • Operators

  • Separators


25. Difference between Overloading and Overriding?

FeatureOverloadingOverriding
BindingCompile-timeRuntime
ParametersDifferentSame
Return TypeCan varyMust match
ClassSame classParent-Child

Wednesday, December 17, 2025

Big-O Notation Explained – Data Structures & Sorting Algorithms

Big-O Notation Explained – Data Structures & Sorting Algorithms (Complete Reference)

1. What is Big‑O Notation?

Big‑O notation describes how an algorithm scales as input size n grows.

Common Notations

NotationMeaningExample
O(1)  Constant     Array index access
O(log n) Logarithmic   Binary search
O(n) Linear  Loop through array
O(n log n) Linearithmic  Efficient sorting
O(n²) Quadratic Nested loops


2. Common Data Structure Operations

📊 Table: Time & Space Complexity (All Columns Covered)






3. Explanation with Examples

Array

  • Access O(1): arr[10]

  • Insert/Delete O(n): shifting elements

  • Use case: Fast reads, static data

Stack (LIFO)

  • Insert/Delete O(1): push/pop

  • Search O(n): scan all elements

  • Use case: Undo, recursion, JVM stack

Queue (FIFO)

  • Insert/Delete O(1): enqueue/dequeue

  • Use case: Kafka, task scheduling

Hash Table

  • Average O(1): hash-based lookup

  • Worst O(n): collision chain

  • Use case: Caching, indexing

Balanced Trees (AVL / Red‑Black)

  • Guaranteed O(log n)

  • Use case: Sorted data (TreeMap)


4. Array Sorting Algorithms

📊 Table: Sorting Time & Space Complexity

AlgorithmTime Complexity (Best)AverageWorstSpace (Worst)
QuicksortΩ(n log n)Θ(n log n)O(n²)O(log n)
MergesortΩ(n log n)Θ(n log n)O(n log n)O(n)
TimsortΩ(n)Θ(n log n)O(n log n)O(n)
HeapsortΩ(n log n)Θ(n log n)O(n log n)O(1)
Bubble SortΩ(n)Θ(n²)O(n²)O(1)
Insertion SortΩ(n)Θ(n²)O(n²)O(1)
Selection SortΩ(n²)Θ(n²)O(n²)O(1)
Counting SortΩ(n+k)Θ(n+k)O(n+k)O(k)
Radix SortΩ(nk)Θ(nk)O(nk)O(n+k)

5. How to Choose the Right One

RequirementBest Choice
Fast lookupHashMap
Sorted dataTreeMap / AVL
Large dataset sortMerge / TimSort
Memory constrainedHeapSort
MessagingQueue

6. Interview‑Ready Summary

Arrays → Fast access
Linked Lists → Fast insertion
Hash Tables → Fast lookup
Trees → Ordered & scalable
O(n log n) → Optimal sorting

Sunday, December 14, 2025

Java Overview

 Q1. Why use Java?

A1. One needs to use the best tool for the job, whether that tool is Java or not. When choosing a technology to solve your business problems, you need to consider many factors like development cost, infrastructure cost, ongoing support cost, robustness, flexibility, security, performance, etc.

  • Java provides client technologies, server technologies, and integration technologies to solve small scale to very large scale business problems.
  • Firstly, Java is a proven and matured technology used in many mission critical projects, and there are millions of developers world wide, thousands of
  • frameworks, tools, and libraries for it, and millions of sites, blogs, and books to find relevant information.
  • The emergence of open-source technologies has truly made Java a powerful competitor in the server and integration technology space. You can always find
  • a proven framework that best solves your business problems.
  • The platform also comes with a rich set of APIs. This means developers spend less time writing support libraries, and more time developing content for their applications.
  • Built-in support for multi-threading, socket communication, and automatic memory management (i.e. automatic garbage collection).



Q2. Is Java a 100% Object Oriented (OO) language? if yes why? and if no, why not?


A2. I would say Java is not 100% object oriented, but it embodies practical OO concepts. 


There are 6 qualities to make a programming language to be pure object oriented. They are:

1. Encapsulation – data hiding and modularity.

2. Inheritance – you define new classes and behavior based on existing classes to obtain code reuse.

3. Polymorphism – the same message sent to different objects results in behavior that’s dependent on the nature of the object receiving the message.

4. All predefined types are objects.

5. All operations are performed by sending messages to objects.

6. All user defined types are objects.



Reason #1: The main reason why Java cannot be considered 100% OO is due to its existence of 8 primitive variables (i.e. violates point number 4) like int, long, char, float, etc. These data types have been excused from being objects for simplicity and to improve performance. Since primitive data types are not objects, they don’t have any qualities such as inheritance or polymorphism. Even though Java provides immutable wrapper classes like Integer, Long, Character, etc representing corresponding primitive data as objects, the fact that it allowed non object oriented primitive variables to exist, makes it not fully OO.


Reason #2: Another reason why Java is considered not full OO is due to its existence of static methods and variables (i.e. violates point number 5). Since static methods can be invoked without instantiating an object, we could say that it breaks the rules of encapsulation.


Reason #3: Java does not support multiple class inheritance to solve the diamond problem because different classes may have different variables with same name that may be contradicted and can cause confusions and result in errors. In Java, any class can extend only one other class, but can implement multiple interfaces.

We could also argue that Java is not 100% OO according to this point of view. But Java realizes some of the key benefits of multiple inheritance through its

support for multiple interface inheritance and in Java 8, you can have multiple behavior (not state) inheritance as you can have default methods in interfaces.


Reason #4: Operator overloading is not possible in Java except for string concatenation and addition operations. String concatenation and addition example,

System.out.println(1 + 2 + ”3”);//outputs 33

System.out.println(“1” + 2 + 3); //outputs 123

Since this is a kind of polymorphism for other operators like * (multiplication), / (division), or – (subtraction), and Java does not support this, hence one could debate that Java is not 100% OO. Working with a primitive in Java is more elegant than working with an object like BigDecimal. 


For example,

int a,b, c;

/without operator overloading

a = b – c * d

What happens in Java when you have to deal with large decimal numbers that must be accurate and of unlimited size and precision? You must use a BigDecimal. BigDecimal looks verbose for larger calculations without the operator overloading as shown below:

BigDecimal b = new BigDecimal(“25.24”);

BigDecimal c = new BigDecimal(“3.99”);

BigDecimal d = new BigDecimal(“2.78”);

BigDecimal a = b.subtract(c).multiply(d); //verbose and wrong

Also, the last line above is wrong. 


The rules of precedence have changed. With chained method calls like this, evaluation is strictly left-to-right. Instead of

subtracting the product of c and d from b, we are multiplying the difference between b and c by d. We would have to rewrite the last line as shown below:

BigDecimal a = b.subtract(c.multiply(d)); //correct

So, it is error prone as well. Another point is that the BigDecimal class is immutable and, as such, each of the “operator” methods returns a new instance. In

future Java versions, you may have operator overloading for BigDecimal, and it would make your code more readable as shown below.

BigDecimal a = b – (c * d); //much better



Q3. What is the difference between C++ and Java?


A3. Both C++ and Java use similar syntax and are Object Oriented, but:

1) Java does not support pointers. Pointers are inherently tricky to use and troublesome.

2) Java does not support multiple inheritances because it causes more problems than it solves. Instead Java supports multiple interface behavior inheritance (In

Java 8, you can have interfaces with default & static methods, but can’t have state), which allows an object to inherit many method signatures from different

interfaces with the condition that the inheriting object must implement those inherited methods.

3) Java does not support destructors but rather adds a finalize() method. Finalize methods are invoked by the garbage collector prior to reclaiming the memory

occupied by the object, which has the finalize() method. This means you do not know when the objects are going to be finalized. Avoid using finalize() method

to release non-memory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources and you do not

know when the garbage collection is going to kick in to release these resources through the finalize() method.4) Java does not include structures or unions. Java make use of the Java Collection framework.

5) All the code in Java program is encapsulated within classes therefore Java does not have global variables or functions.

6) C++ requires explicit memory management, while Java includes automatic garbage collection.


Q4. What is the main difference between the Java platform and the other software platforms?


A4. Java platform is a software-only platform, which runs on top of other hardware-based platforms like Unix, Windows, Mac OS, etc.

Java platform

The Java platform has 2 components:

1) Java Virtual Machine (JVM) – ‘JVM’ is a software that can be ported onto various hardware platforms. Byte codes are the machine language of the JVM.

2) Java Application Programming Interface (Java API) – is nothing but a set of classes and interfaces that come with the JDK. All these classes are written using

the Java language and contains a library of methods for common programming tasks like manipulating strings and data structures, networking, file transfer, etc.

The source *.java files are in the src.zip archive and the executable *.class files are in the rt.jar archive.


Q5. How would you differentiate JDK, JRE, JVM, and JIT?

A5. There is no better way to get the big picture than a diagram.JDK, JRE, JVM, and JIT

1) JDK: You can download a copy of the Java Development Kit (JDK) for your operating system like Unix, Windows, etc.2) JRE: Java Runtime Environment is an implementation of the JVM. The JDK typically includes the Java Runtime Environment (JRE) which contains the

virtual machine and other dependencies to run Java applications.

3) JIT: A JIT is a code generator that converts Java byte code into native machine code. Java programs invoked with a JIT generally run much faster than when

the byte code is executed by the interpreter. The JIT compiler is a standard tool that is part of the JVM and invoked whenever you use the Java interpreter

command. You can disable the JIT compiler using the -Djava.compiler=NONE option to the Java VM. You might want to disable the JIT compiler if you are

running the Java VM in remote debug mode, or if you want to see source line numbers instead of the label (Compiled Code) in your Java stack traces.


Q6. Is it possible to convert byte code into source code?

A6. Yes. A Java decompiler is a computer program capable of reversing the work done by a compiler. In essence, it can convert back the byte code (i.e. the

.class file) into the source code (i.e the .java file). There are many decompilers that exist today, but the most widely used JD – Java Decompiler is available both

as stand-alone GUI program and as an eclipse plug-in.


Q7. When would you use a decompiler?

A7.

1) When you have *.class files and you do not have access to the source code (*.java files). For example, some vendors do not ship the source code for java

class files or you accidentally lost (e.g deleted) your source code, in which case you can use the Java decompiler to reconstruct the source file.

2) Another scenario is that if you generated your .class files from another language like a groovy script, using the groovyc command, you may want to use a

Java decompiler to inspect the Java source code for the groovy generated class files to debug or get a better understanding of groovy integration with Java.

3) To ensure that your code is adequately obfuscated before releasing it into the public domain.

4) Fixing and debugging .class files when developers are slow to respond to questions that need immediate answers. To learn both Java and how the Java VM

works.

5) Learn and debug how code with generics has been converted after compilation.



Q8. Is it possible to prevent the conversion from byte code into source code?


A8. If you want to protect your Java class files from being decompiled, you can take a look at a Java obfuscator tool like yGuard or ProGuard, otherwise you

will have to kiss your intellectual property good bye.


Q9. What are the two flavors of JVM?

A9. Client mode and server mode.

Client mode is suited for short lived programs like stand-alone GUI applications and applets. Specially tuned to reduce application start-up time and memory

footprint, making it well suited for client applications. For example: c:\> java -client MyProgramServer mode is suited for long running server applications, which can be active for weeks or months at a time. Specially tuned to maximize peak operating

speed. The fastest possible operating speed is more important than fast start-up time or smaller runtime memory footprint. c:\> java -server MyProgram


Q10. How do you know in which mode your JVM is running?

A10. c:\> java -version


Q11. What are the two different bits of JVM? What is the major limitation of 32 bit JVM?

A11. JVMs are available in 32 bits (-d32 JVM argument) and 64 bits (-d64 JVM argument). 64-bit JVMs are typically only available from JDK 5.0 onwards. It

is recommended that the 32-bit be used as the default JVM and 64-bit used if more memory is needed than what can be allocated to a 32-bit JVM. The Oracle

Java VM cannot grow beyond ~2GB on a 32bit server machine even if you install more than 2GB of RAM into your server. It is recommended that a 64bit OS

with larger memory hardware is used when larger heap sizes are required. For example, >4GB is assigned to the JVM and used for deployments of >250

concurrent or >2500 casual users.


Q12. What are some of the JVM arguments you have used in your projects?

A12. To set a system property that can be retrieved using System.getPropety(“name”);

$java -Dname=value MyApp

To set the classpath: -cp or -classpath

$java -cp library.jar MyApp

To set minimum and maximum heap sizes:$java -Xms1024 -Xmx1024 MyApp

To set garbage collection options:

$ java -Xincgc MyApp



Q13. How do you monitor the JVMs?

A13. Since Java SE 5.0, the JRE provides a mean to manage and monitor the Java Virtual Machine. It comes in two flavors:

JVM Monitoring1) The JVM has built-in instrumentation that enables you to monitor and manage it using Java Management eXtension (JMX). You can also monitor

instrumented applications with JMX. To start a Java application with the management agent for local monitoring, set the following JVM argument when you run

your application.

$JA V A_HOME/bin/java -Dcom.sun.management.jmxremote MyApp

To start the JConsole:

$JA V A_HOME/bin/jconsole

2) The other is a Simple Network Management Protocol (SNMP) agent that builds upon the management and monitoring API of the Java SE platform, and

exposes the same information through SNMP. SNMP events can be sent Splunk. Nagios, Zenoss, OpenNMS, and netsnmp are some of the popular SNMP tools.



Q14. What is a jar file? How does it differ from a zip file?

A14. The jar stands for Java ARchive. A jar file usually has a file name extension .jar. It mainly contains Java class files but any types of files can be included.

For example, XML files, properties files, HTML files, image files, binary files, etc. You can use the “jar” application utility bundled inside /JDK1.6.0/jre/bin to

create, extract, and view its contents. You can also use any zip file utility program to view its contents. A jar file cannot contain other jar files., whereas a war

or ear file used in Java EE.

Basically, a jar file is same as a zip file, except that it contains a META-INF directory to store meta data or attributes. The most known file is META-

INF/MANIFEST.MF. When you create a JAR file, it automatically receives a default manifest file. There can be only one manifest file in an archive. Most uses

of JAR files beyond simple archiving and compression require special information to be in the manifest file. For example,

— If you have an application bundled in a JAR file, you need some way to indicate which class within the JAR file is your application’s entry point. The entry

point is the class having a method with signature public static void main(String[ ] args). For example, Main-Class: Test.class

— A package within a JAR file can be optionally sealed, which means that all classes defined in that package must be archived in the same JAR file. You might

want to seal a package, for example, to ensure version consistency among the classes in your software or as a security measure.Name: myCompany/myPackage/

Sealed: true



Q15. What do you need to develop and run Java programs? How would you go about getting started?


A15. Step 1: Download and install the Java Development Kit (JDK) SE (Standard Edition) for your operating system (e.g. Windows, Linux, etc) and processor

(32 bit, 64 bit, etc) .


Step 2: Configure your environment. The first environment variable you need to set is the JA V A_HOME.

JA V A_HOME=C:\DEV\java\jdk-1.6.0_11 #on windows

export JA V A_HOME=/usr/java/jdk-1.6.0_11 #on Unix

The second environment variable is PATH.

PATH=%JA V A_HOME%\bin; #on windows

export PATH=$PATH:$JA V A_HOME/bin #on Unix


Step 3: Verify your configurations with the following commands:

echo %JA V A_HOME% #windows

echo %PATH% #windows

$ echo $JA V A_HOME #Unix

$ echo $PATH #UnixStep 5: Verify your installation with


$ javac -version

$ java -version



Q16. How do you create a class under a package in Java? What is the first statement in Java?


A16. ou can create a class under a package as follows with the package keyword, which is the first keyword in any Java program followed by the import

statements. The java.lang package is imported implicitly by default and all the other packages must be explicitly imported. The core Java packages like

java.lang.*, java.net.*, java.io*, etc and its class files are distributed in the archive file named rt.jar.

package com.xyz.client ;

mport java.io.File;

mport java.net.URL;





Java Object-Oriented Design (OOD)