Complete Java Programming Guide
1. Introduction to Java
What is Java?
Java is a high-level, object-oriented, platform-independent programming language.
Key Terms:
• JDK (Java Development Kit) – Includes compiler, libraries, JRE.
• JRE (Java Runtime Environment) – Runs Java apps (has JVM + libraries).
• JVM (Java Virtual Machine) – Executes Java bytecode.
Sample Program: Hello World
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, Java!");
2. Variables, Data Types & Operators
Data Types:
• Primitive: int, float, char, boolean, double, byte, short, long
• Non-Primitive: String, Array, Class, Object
Code Example:
public class DataTypes {
public static void main(String[] args) {
int age = 21;
double salary = 56000.50;
char grade = 'A';
boolean isPass = true;
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
System.out.println("Grade: " + grade);
System.out.println("Pass: " + isPass);
3. Input/Output using Scanner
Code Example:
import java.util.Scanner;
public class UserInput {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter name: ");
String name = sc.nextLine();
System.out.print("Enter age: ");
int age = sc.nextInt();
System.out.println("Hello " + name + ", age " + age);
4. Control Statements (if-else, switch)
Code Example (if-else):
int age = 18;
if(age >= 18) {
System.out.println("Eligible to vote");
} else {
System.out.println("Not eligible");
Code Example (switch):
int day = 3;
switch(day) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
default: System.out.println("Other Day");
5. Loops (for, while, do-while)
For loop:
for(int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
While loop:
int i = 1;
while(i <= 5) {
System.out.println(i);
i++;
6. Arrays
Code Example (1D Array):
int[] nums = {10, 20, 30};
for(int i = 0; i < nums.length; i++) {
System.out.println(nums[i]);
7. Object-Oriented Programming (OOP)
4 Pillars:
1. Encapsulation
2. Inheritance
3. Polymorphism
4. Abstraction
Class and Object
Code:
class Car {
String color = "Red";
void drive() {
System.out.println("Car is driving");
public class Main {
public static void main(String[] args) {
Car c = new Car();
System.out.println(c.color);
c.drive();
}
8. Constructor, this keyword
Code:
class Student {
String name;
Student(String name) {
this.name = name;
void show() {
System.out.println("Name: " + name);
9. Inheritance
Code:
class Animal {
void eat() {
System.out.println("Eating...");
class Dog extends Animal {
void bark() {
System.out.println("Barking...");
public class Test {
public static void main(String[] args) {
Dog d = new Dog();
d.eat();
d.bark();
10. Polymorphism
Method Overloading:
class MathOp {
int sum(int a, int b) {
return a + b;
double sum(double a, double b) {
return a + b;
Method Overriding:
class Animal {
void sound() {
System.out.println("Some sound");
class Cat extends Animal {
void sound() {
System.out.println("Meow");
}
11. Abstraction
Using Interface:
interface Shape {
void draw();
class Circle implements Shape {
public void draw() {
System.out.println("Drawing Circle");
12. Exception Handling
Code:
try {
int a = 10 / 0;
} catch(ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
13. Collections (ArrayList, HashMap)
ArrayList:
import java.util.ArrayList;
ArrayList<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
for(String lang : list) {
System.out.println(lang);
HashMap:
import java.util.HashMap;
HashMap<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
System.out.println(map.get("A"));
14. File Handling
import java.io.*;
public class FileWrite {
public static void main(String[] args) {
try {
FileWriter fw = new FileWriter("test.txt");
fw.write("Hello file!");
fw.close();
} catch (IOException e) {
e.printStackTrace();
15. JDBC (Database Connectivity)
// Pseudocode
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(url, user, password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM students");
16. Multithreading
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");
Great! Let's now move on to the Advanced Java Concepts with theory and code.
Advanced Java Concepts (With Code + Theory)
17. Lambda Expressions (Java 8 Feature)
What is it?
Lambda expressions provide a clear and concise way to represent one-method
interfaces (functional interfaces).
Syntax:
(parameter) -> expression
Code Example:
interface Greet {
void sayHello();
}
public class LambdaDemo {
public static void main(String[] args) {
Greet greet = () -> System.out.println("Hello using Lambda!");
greet.sayHello();
18. Functional Interfaces
What is it?
An interface with only one abstract method (can have multiple default/static
methods).
Example:
@FunctionalInterface
interface Add {
int sum(int a, int b);
19. Stream API (Java 8 Feature)
What is it?
Stream API is used to process collections in a functional style (filter, map, reduce).
Code Example:
import java.util.*;
import java.util.stream.*;
public class StreamExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Java", "Python", "C++", "Go");
names.stream()
.filter(name -> name.startsWith("J"))
.forEach(System.out::println);
20. Inner Classes
What is it?
A class defined inside another class.
Example:
class Outer {
class Inner {
void show() {
System.out.println("Inside Inner");
21. Enum in Java
What is it?
A special class to define a set of constants.
Example:
enum Day { MON, TUE, WED }
public class EnumTest {
public static void main(String[] args) {
Day d = Day.MON;
System.out.println(d);
22. Wrapper Classes
What is it?
Convert primitives to objects: int → Integer, char → Character, etc.
Code Example:
int a = 10;
Integer obj = Integer.valueOf(a); // Boxing
int b = obj.intValue(); // Unboxing
23. Annotations
What is it?
Metadata for code used by compiler or frameworks.
Example:
@Override
public String toString() {
return "Overridden toString()";
24. Java GUI (Swing)
Code Example:
import javax.swing.*;
public class SwingDemo {
public static void main(String[] args) {
JFrame f = new JFrame("My Window");
JButton b = new JButton("Click Me");
b.setBounds(50, 100, 100, 40);
f.add(b);
f.setSize(300, 300);
f.setLayout(null);
f.setVisible(true);
25. Java Multithreading
Thread using Runnable:
class MyThread implements Runnable {
public void run() {
System.out.println("Running in thread");
public class ThreadDemo {
public static void main(String[] args) {
Thread t = new Thread(new MyThread());
t.start();
26. Synchronization
What is it?
Prevents thread interference and consistency problems.
Code:
synchronized void print() {
// code that needs thread safety
27. Java JDBC (Database Connection)
Sample Code:
import java.sql.*;
public class DBConnect {
public static void main(String[] args) {
try {
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/dbname", "user", "pass");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM students");
while(rs.next()) {
System.out.println(rs.getString(1));
} catch(Exception e) {
System.out.println(e);
28. Java Packages
Code:
package mypackage;
public class MyClass {
public void display() {
System.out.println("Inside package");
29. Access Modifiers
Modifier Class Package Subclass World
public
protected
default
private
30. Java Build Tools (Optional for Projects)
• Maven: Manages dependencies & project structure
• Gradle: Fast, flexible build tool
31. Java Frameworks (Intro Only)
• Spring Boot: Rapid web app & REST API development
• Hibernate: ORM (Object Relational Mapping)
• JavaFX: GUI Framework (advanced alternative to Swing)
32. Mini Project Idea
Build a Student Management System with:
• Java GUI (Swing)
• File handling or JDBC for data storage
• CRUD operations
Java Interview Questions & Answers (100+)
Section 1: Core Java (Basics)
1. What is Java?
Java is a high-level, object-oriented programming language developed by Sun
Microsystems. It is platform-independent, thanks to the Java Virtual Machine (JVM), and
supports WORA (Write Once, Run Anywhere).
2. Explain JVM, JRE, and JDK.
• JVM (Java Virtual Machine): Executes Java bytecode.
• JRE (Java Runtime Environment): Contains JVM + runtime libraries.
• JDK (Java Development Kit): Contains JRE + development tools (compiler,
debugger).
3. What is bytecode?
Bytecode is the intermediate representation of Java code compiled by the Java compiler
and executed by the JVM.
4. Why is Java platform-independent?
Java programs are compiled into bytecode, which can run on any system that has a JVM,
making it platform-independent.
5. What are data types in Java?
• Primitive: int, float, double, char, boolean, byte, short, long
• Non-Primitive: String, Array, Class, Object
6. What is type casting?
Converting one data type to another.
• Implicit: int to double
• Explicit: double to int
7. Difference between == and .equals()?
• ==: Compares memory addresses (reference).
• .equals(): Compares content.
8. What is a wrapper class?
Wrapper classes convert primitives to objects (e.g., int → Integer).
9. What is autoboxing and unboxing?
• Autoboxing: Primitive to object (int → Integer).
• Unboxing: Object to primitive (Integer → int).
10. What are access modifiers in Java?
• public: Accessible everywhere.
• protected: Accessible in same package and subclass.
• default: Package-level access.
• private: Accessible within the class only.
Section 2: OOP Concepts
11. What is Object-Oriented Programming?
A paradigm based on "objects" which combine data and behavior. Principles:
encapsulation, inheritance, polymorphism, abstraction.
12. What is a class and object?
• Class: Blueprint of an object.
• Object: Instance of a class.
13. What is inheritance?
Mechanism to acquire properties of a parent class.
14. What is polymorphism?
Ability to take many forms. Method overloading/overriding are examples.
15. What is method overloading?
Multiple methods with same name but different parameters.
16. What is method overriding?
Child class provides specific implementation of a parent class method.
17. What is abstraction?
Hiding implementation and showing only essential details (via abstract class/interface).
18. What is an interface?
A contract with only abstract methods (Java 8+ allows default/static methods).
19. Difference between abstract class and interface?
• Abstract: Can have methods with implementation.
• Interface: Cannot have instance variables; only static/final fields.
20. What is encapsulation?
Wrapping data and code into a single unit. Achieved using private variables and public
getters/setters.
Real-World OOP Example (Bank System):
• Class: BankAccount, Customer
• Object: acc1 = new BankAccount();
• Encapsulation: Private balance accessed via getBalance()
• Inheritance: SavingsAccount extends BankAccount
• Polymorphism: printDetails() differs in LoanAccount, SavingAccount
• Abstraction: ATMInterface with withdraw(), checkBalance()
Section 3: Control Structures & Loops
21. What are control statements?
Control the flow of execution (if, switch, loops).
22. Difference between if and switch?
• if: Works with ranges and complex conditions.
• switch: Works best for equality checks.
23. Difference between for, while, and do-while?
• for: Pre-known iterations.
• while: Condition checked before loop.
• do-while: Executes at least once.
24. What is enhanced for loop?
Simplified loop for arrays/collections: for(String s : list)
25. What is the use of break and continue?
• break: Exits the loop.
• continue: Skips current iteration.
Section 4: Strings
26. Difference between String, StringBuilder, StringBuffer?
• String: Immutable
• StringBuilder: Mutable, not thread-safe
• StringBuffer: Mutable, thread-safe
27. Is String immutable? Why?
Yes, to improve security, caching, and performance.
28. What is intern() method?
Stores string in the string pool if not already present.
29. equals() vs == in strings?
• ==: Compares reference.
• .equals(): Compares values.
30. Common String methods:
length(), charAt(), substring(), replace(), split()
Section 5: Arrays & Collections
31. What is an array?
Fixed-size container for elements of the same type.
32. How to declare and initialize arrays?
int[] a = new int[5];
33. What is ArrayList?
Resizable array from Java Collections Framework.
34. Difference between List and Set?
• List: Allows duplicates
• Set: Unique elements only
35. What is HashMap?
Stores key-value pairs with unique keys.
36. Difference between HashMap and Hashtable?
• HashMap: Not synchronized
• Hashtable: Synchronized
37. What is TreeMap?
Sorted map based on keys.
38. What is Iterator?
Interface to iterate over collections.
39. Collection vs Collections?
• Collection: Interface
• Collections: Utility class with static methods
40. How do you sort a collection?
Using Collections.sort() or stream().sorted() Java Interview Questions & Answers
(100+)
Section 6: Exception Handling
41. What is an exception?
An exception is an event that disrupts the normal flow of the program. It can be caught
and handled using exception-handling constructs.
42. Difference between checked and unchecked exceptions?
• Checked: Checked at compile-time (IOException, SQLException)
• Unchecked: Occur at runtime (NullPointerException, ArithmeticException)
43. What is the use of try, catch, finally?
• try: Code that might throw exception
• catch: Handles the exception
• finally: Executes always, used to clean up resources
44. What is throw and throws?
• throw: Used to explicitly throw an exception
• throws: Declares exceptions in method signature
45. Can we write try without catch or finally?
Yes, but try must be followed by either catch or finally.
46. What is a custom exception?
A user-defined exception class that extends Exception or RuntimeException.
47. What happens if an exception is not caught?
Program terminates abnormally and JVM prints stack trace.
Section 7: Multithreading
48. What is a thread?
A thread is a lightweight subprocess. It allows multitasking within a program.
49. How to create a thread in Java?
• Extend Thread class and override run()
• Implement Runnable interface and pass it to Thread constructor
50. Difference between Thread and Runnable?
• Thread: Inherits all thread features but restricts multiple inheritance
• Runnable: More flexible, preferred for implementing threads
51. What is synchronization?
Synchronization prevents concurrent access to shared resources to avoid data
inconsistency.
52. What is the use of wait() and notify()?
Used for inter-thread communication inside synchronized blocks.
53. What is deadlock?
A situation where two or more threads wait for each other indefinitely.
54. What is thread priority?
Determines execution order. Range: 1 (MIN) to 10 (MAX)
55. What is a daemon thread?
A low-priority thread that runs in the background (e.g., garbage collection).
Section 8: File Handling & I/O
56. How do you read a file in Java?
Using BufferedReader, Scanner, or FileReader.
57. What is BufferedReader and FileReader?
• BufferedReader: Reads text from a character-input stream efficiently
• FileReader: Reads characters from a file
58. Difference between byte and character streams?
• Byte: Reads binary data (InputStream)
• Character: Reads character data (Reader)
59. How to write to a file?
Use FileWriter or BufferedWriter.
60. What is serialization?
Converting an object into a byte stream to save or send over the network.
Section 9: Java 8 Features
61. What is a lambda expression?
An anonymous function that enables functional programming in Java.
(a, b) -> a + b;
62. What is a functional interface?
An interface with exactly one abstract method. Example: Runnable, Callable
63. What is Stream API?
Used to process collections using functional-style operations like filter, map, reduce.
64. What are default and static methods in interfaces?
From Java 8, interfaces can have:
• default methods with implementation
• static methods with implementation
65. What is Optional?
A container to avoid NullPointerException by representing optional values.
Section 10: JDBC (Java Database Connectivity)
66. What is JDBC?
Java API that allows Java applications to connect and interact with databases.
67. Steps to connect to a database using JDBC:
1. Load the driver class
2. Establish connection
3. Create statement
4. Execute query
5. Process result
6. Close connection
68. Difference between Statement and PreparedStatement?
• Statement: Compiled each time
• PreparedStatement: Compiled once, used multiple times
69. What is ResultSet?
An object that holds the data retrieved from a database using JDBC.
70. What are JDBC drivers?
Software components that enable Java to interact with databases (e.g., MySQL driver).
Section 11: Java Memory Management
71. What is garbage collection?
Automatic memory management in Java where unused objects are cleaned.
72. What is heap and stack memory?
• Heap: Stores objects
• Stack: Stores method calls and local variables
73. What are final, finally, and finalize?
• final: Prevents inheritance or modification
• finally: Executes after try-catch
• finalize(): Called by GC before object is destroyed
74. Can we force garbage collection?
We can suggest it using System.gc(), but it is not guaranteed.
75. What are strong, weak, and soft references?
Types of object references that affect garbage collection behavior.
Section 12: Java Keywords and Concepts
76. What is static keyword?
Used to define class-level members (shared across all instances).
77. What is final keyword?
Used to declare constants, prevent method overriding, or inheritance.
78. Difference between this and super?
• this: Refers to current object
• super: Refers to parent class object
79. What is instanceof?
Checks if an object is an instance of a specific class or subclass.
80. What is transient keyword?
Prevents variables from being serialized.
Section 13: Java Best Practices
81. Why prefer interfaces over abstract classes?
Allows multiple inheritance and better abstraction.
82. Why is immutability important?
Makes objects thread-safe, predictable, and easier to debug.
83. How to handle null values safely?
Use Optional, null checks, and guard clauses.
84. How to write clean Java code?
Follow naming conventions, modular code, comments, avoid redundancy.
85. Why should main() be static?
It allows JVM to invoke it without creating an instance.
Section 14: Miscellaneous / Trick Questions
86. Can a class be private?
Only inner classes can be private.
87. Can we overload the main() method?
Yes, but JVM always calls public static void main(String[] args).
88. Can constructor be private?
Yes, used in Singleton pattern.
89. What happens if you don’t write a constructor?
Java provides a default no-arg constructor.
90. Can we override a static method?
No, it is method hiding.
91. Can we override a private method?
No, private methods are not inherited.
92. Can we run a Java class without main()?
Yes, using static blocks or JavaFX/servlets.
93. Why Java doesn’t support multiple inheritance?
To avoid ambiguity (diamond problem).
94. What is method hiding?
When a static method is redefined in a subclass.
95. What is the difference between shallow and deep copy?
• Shallow: Copies references
• Deep: Copies values and nested objects
Section 15: HR + Project + Behavioral
96. Explain a Java project you’ve built.
Example: A banking system with user login, account management, transaction history
using JDBC and Swing.
97. Where did you use OOP in your project?
Classes like Account, Transaction, Customer using inheritance and polymorphism.
98. How would you handle errors in a banking system?
Using custom exceptions, try-catch-finally, and transaction rollback.
99. How to optimize a Java program?
Use data structures wisely, avoid nested loops, reuse objects, use StringBuilder, apply
caching.
100. What is your favorite Java feature and why?
Java Streams for clean and readable code using functional-style operations.
101. What is your approach to debugging Java code?
Use IDE breakpoints, loggers, isolate logic, and test incrementally.
102. How do you ensure code quality?
Follow SOLID principles, perform unit testing, and use code reviews.
103. What are SOLID principles in Java?
Design principles to write maintainable OOP code (Single Responsibility, Open/Closed,
etc.)
104. What is a Singleton pattern?
Ensures only one instance of a class exists with a private constructor and static
instance.
105. Final thoughts on Java?
Java is a mature, secure, versatile language used across enterprise, mobile, and web
development.
OOP (Object-Oriented Programming) concepts in Java
using:
OOP Concepts in Java with Real-World Examples
Java is built on four main OOP principles:
OOP Concept Real-World Analogy Java Keyword Used
Encapsulation Medicine capsule (hides internal chemicals) private, public
Abstraction Car dashboard hides engine complexity abstract, interface
Inheritance Child inherits traits from parents extends
Polymorphism One task, many forms (printing, walking) overload, override
1. Encapsulation
Definition: Binding data (variables) and behavior (methods) together in a class and
hiding it from outside access.
Real-World Analogy: Think of a bank account — you can’t directly access the
balance, you use methods like getBalance() or deposit().
Java Code:
class BankAccount {
private double balance; // Encapsulated
public void deposit(double amount) {
balance += amount;
}
public double getBalance() {
return balance;
public class TestEncapsulation {
public static void main(String[] args) {
BankAccount acc = new BankAccount();
acc.deposit(1000);
System.out.println("Balance: " + acc.getBalance()); // Balance: 1000
2. Abstraction
Definition: Hiding internal implementation and showing only necessary details.
Real-World Analogy: When driving a car, you use a steering wheel, not the internal
engine mechanics.
Java Code (Using Interface):
interface Vehicle {
void start();
class Car implements Vehicle {
public void start() {
System.out.println("Car starts with key.");
}
}
public class TestAbstraction {
public static void main(String[] args) {
Vehicle v = new Car(); // abstraction
v.start(); // hides how engine works
3. Inheritance
Definition: Acquiring the properties and behaviors of a parent class by a child class.
Real-World Analogy: A Son inherits traits from Father (like name or assets).
Java Code:
class Animal {
void sound() {
System.out.println("Makes sound");
class Dog extends Animal {
void sound() {
System.out.println("Barks");
public class TestInheritance {
public static void main(String[] args) {
Dog d = new Dog();
d.sound(); // Barks
4. Polymorphism
Definition: One interface, many implementations — the same method behaves
differently based on context.
Real-World Analogy: "Speak" action is different for a dog, human, or robot.
4.1 Compile-time Polymorphism (Method Overloading):
class Calculator {
int add(int a, int b) {
return a + b;
double add(double a, double b) {
return a + b;
public class TestOverloading {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(5, 2)); // 7
System.out.println(calc.add(5.5, 2.5)); // 8.0
4.2 Run-time Polymorphism (Method Overriding):
class Shape {
void draw() {
System.out.println("Drawing shape");
class Circle extends Shape {
void draw() {
System.out.println("Drawing circle");
public class TestOverriding {
public static void main(String[] args) {
Shape s = new Circle(); // dynamic method dispatch
s.draw(); // Drawing circle
Summary Table
Concept Purpose Keyword Real-world Example
Hide internal data, control
Encapsulation private, get/set Bank Account balance
access
Expose only essential abstract, Car interface
Abstraction
behavior interface (start/stop)
Inheritance Reuse code from parent class extends Father → Son
One method, many overload, Shape → draw as
Polymorphism
implementations override circle/square
Awesome! Here's the complete code with logic explanations for the most commonly
asked programming questions in tech interviews (TCS, Infosys, Wipro, Amazon, etc.).
Each example is in Java, cleanly structured and ready to run.
EASY LEVEL – COMPLETE JAVA CODE
1. Reverse a String
public class ReverseString {
public static void main(String[] args) {
String str = "hello";
String reversed = new StringBuilder(str).reverse().toString();
System.out.println("Reversed: " + reversed);
2. Palindrome Check
public class Palindrome {
public static boolean isPalindrome(String str) {
return str.equals(new StringBuilder(str).reverse().toString());
public static void main(String[] args) {
System.out.println(isPalindrome("madam")); // true
System.out.println(isPalindrome("hello")); // false
}
3. Prime Number Check
public class PrimeCheck {
public static boolean isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) return false;
return true;
public static void main(String[] args) {
System.out.println(isPrime(7)); // true
System.out.println(isPrime(10)); // false
4. Fibonacci Series
public class Fibonacci {
public static void printFibonacci(int n) {
int a = 0, b = 1;
for (int i = 1; i <= n; i++) {
System.out.print(a + " ");
int c = a + b;
a = b;
b = c;
}
public static void main(String[] args) {
printFibonacci(10);
5. Factorial (Recursive)
public class Factorial {
public static int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
public static void main(String[] args) {
System.out.println("Factorial of 5: " + factorial(5));
MEDIUM LEVEL – COMPLETE JAVA CODE
6. Anagram Check
import java.util.Arrays;
public class Anagram {
public static boolean isAnagram(String a, String b) {
char[] c1 = a.toCharArray();
char[] c2 = b.toCharArray();
Arrays.sort(c1);
Arrays.sort(c2);
return Arrays.equals(c1, c2);
public static void main(String[] args) {
System.out.println(isAnagram("listen", "silent")); // true
7. Find Duplicate Characters
import java.util.*;
public class DuplicateChars {
public static void findDuplicates(String str) {
Map<Character, Integer> map = new HashMap<>();
for (char ch : str.toCharArray()) {
map.put(ch, map.getOrDefault(ch, 0) + 1);
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
if (entry.getValue() > 1)
System.out.println(entry.getKey() + ": " + entry.getValue());
public static void main(String[] args) {
findDuplicates("programming");
}
8. Missing Number in Array
public class MissingNumber {
public static int findMissing(int[] arr, int n) {
int total = n * (n + 1) / 2;
int sum = 0;
for (int i : arr) sum += i;
return total - sum;
public static void main(String[] args) {
int[] arr = {1, 2, 3, 5};
System.out.println("Missing number: " + findMissing(arr, 5));
9. Second Largest in Array
public class SecondLargest {
public static int secondLargest(int[] arr) {
int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int num : arr) {
if (num > first) {
second = first;
first = num;
} else if (num > second && num != first) {
second = num;
return second;
public static void main(String[] args) {
int[] arr = {12, 35, 1, 10, 34, 1};
System.out.println("Second Largest: " + secondLargest(arr));
10. Star Pyramid Pattern
public class StarPattern {
public static void printPattern(int n) {
for (int i = 1; i <= n; i++) {
for (int j = i; j < n; j++) System.out.print(" ");
for (int k = 1; k <= (2 * i - 1); k++) System.out.print("*");
System.out.println();
public static void main(String[] args) {
printPattern(5);
}
HARD LEVEL – COMPLETE JAVA CODE
11. Two Sum
import java.util.*;
public class TwoSum {
public static int[] findTwoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int comp = target - nums[i];
if (map.containsKey(comp)) {
return new int[]{map.get(comp), i};
map.put(nums[i], i);
return new int[]{-1, -1};
public static void main(String[] args) {
int[] res = findTwoSum(new int[]{2, 7, 11, 15}, 9);
System.out.println("Indexes: " + res[0] + ", " + res[1]);
12. Longest Substring Without Repeating
Characters
import java.util.*;
public class LongestSubstring {
public static int lengthOfLongestSubstring(String s) {
Set<Character> set = new HashSet<>();
int left = 0, max = 0;
for (int right = 0; right < s.length(); right++) {
while (!set.add(s.charAt(right))) {
set.remove(s.charAt(left++));
max = Math.max(max, right - left + 1);
return max;
public static void main(String[] args) {
System.out.println(lengthOfLongestSubstring("abcabcbb")); // Output: 3
13. Balanced Parentheses
import java.util.*;
public class BalancedBrackets {
public static boolean isBalanced(String str) {
Stack<Character> stack = new Stack<>();
for (char ch : str.toCharArray()) {
if (ch == '(' || ch == '{' || ch == '[')
stack.push(ch);
else {
if (stack.isEmpty()) return false;
char top = stack.pop();
if ((ch == ')' && top != '(') ||
(ch == '}' && top != '{') ||
(ch == ']' && top != '['))
return false;
return stack.isEmpty();
public static void main(String[] args) {
System.out.println(isBalanced("{[()]}")); // true
System.out.println(isBalanced("{[(])}")); // false
HARD LEVEL (CONTINUED) – COMPLETE JAVA CODE
14. Merge Intervals
• Problem: Given a list of intervals, merge all overlapping intervals.
• Companies: Amazon, Microsoft
import java.util.*;
public class MergeIntervals {
public static int[][] merge(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
List<int[]> merged = new ArrayList<>();
for (int[] interval : intervals) {
if (merged.isEmpty() || merged.get(merged.size() - 1)[1] < interval[0])
merged.add(interval);
else
merged.get(merged.size() - 1)[1] = Math.max(merged.get(merged.size() - 1)[1],
interval[1]);
return merged.toArray(new int[0][]);
public static void main(String[] args) {
int[][] input = {{1, 3}, {2, 6}, {8, 10}, {15, 18}};
int[][] output = merge(input);
for (int[] interval : output)
System.out.println(Arrays.toString(interval));
15. Kth Largest Element
• Problem: Find the Kth largest element in an array.
• Companies: Amazon, Accenture
import java.util.*;
public class KthLargest {
public static int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int num : nums) {
pq.add(num);
if (pq.size() > k)
pq.poll();
return pq.peek();
public static void main(String[] args) {
int[] arr = {3, 2, 1, 5, 6, 4};
System.out.println("Kth Largest: " + findKthLargest(arr, 2)); // 5
16. Binary Search in Rotated Sorted Array
• Problem: Search in rotated array with binary search.
• Companies: Google, Microsoft
public class RotatedBinarySearch {
public static int search(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (nums[mid] == target) return mid;
if (nums[left] <= nums[mid]) { // left sorted
if (nums[left] <= target && target < nums[mid])
right = mid - 1;
else
left = mid + 1;
} else { // right sorted
if (nums[mid] < target && target <= nums[right])
left = mid + 1;
else
right = mid - 1;
return -1;
public static void main(String[] args) {
int[] nums = {4, 5, 6, 7, 0, 1, 2};
System.out.println(search(nums, 0)); // 4
17. Detect Loop in Linked List
• Problem: Use Floyd’s Cycle Detection Algorithm.
• Companies: Infosys, TCS Digital
class Node {
int data;
Node next;
Node(int d) { data = d; next = null; }
}
public class DetectLoop {
public static boolean hasCycle(Node head) {
Node slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast)
return true;
return false;
public static void main(String[] args) {
Node head = new Node(1);
head.next = new Node(2);
head.next.next = head; // loop
System.out.println(hasCycle(head)); // true
18. Count Pairs with Given Sum
• Problem: Find all pairs in array whose sum is equal to a given value.
• Companies: TCS, Capgemini
import java.util.*;
public class CountPairs {
public static int countPairs(int[] arr, int k) {
Map<Integer, Integer> map = new HashMap<>();
int count = 0;
for (int num : arr) {
int diff = k - num;
count += map.getOrDefault(diff, 0);
map.put(num, map.getOrDefault(num, 0) + 1);
return count;
public static void main(String[] args) {
int[] arr = {1, 5, 7, -1, 5};
System.out.println("Pairs: " + countPairs(arr, 6)); // 3
19. Find Intersection of Two Arrays
• Problem: Return common elements.
• Companies: Cognizant, Wipro
import java.util.*;
public class ArrayIntersection {
public static void intersection(int[] a, int[] b) {
Set<Integer> set = new HashSet<>();
for (int num : a) set.add(num);
for (int num : b) {
if (set.contains(num)) {
System.out.print(num + " ");
set.remove(num); // to avoid duplicates
public static void main(String[] args) {
int[] a = {1, 2, 4, 5, 6};
int[] b = {2, 3, 5, 7};
intersection(a, b); // 2 5
20. Check for Pangram
• Problem: A string is pangram if it contains all 26 letters.
• Companies: TCS, Infosys
public class Pangram {
public static boolean isPangram(String s) {
s = s.toLowerCase();
boolean[] mark = new boolean[26];
for (char c : s.toCharArray()) {
if (c >= 'a' && c <= 'z') {
mark[c - 'a'] = true;
for (boolean b : mark)
if (!b) return false;
return true;
public static void main(String[] args) {
System.out.println(isPangram("The quick brown fox jumps over the lazy dog")); //
true
21. Move Zeros to End
• Problem: Move all 0s to end, maintain relative order.
• Companies: Amazon
public class MoveZeros {
public static void moveZeros(int[] arr) {
int index = 0;
for (int num : arr) {
if (num != 0)
arr[index++] = num;
while (index < arr.length)
arr[index++] = 0;
public static void main(String[] args) {
int[] arr = {0, 1, 0, 3, 12};
moveZeros(arr);
for (int n : arr) System.out.print(n + " ");
}
TCS NQT Java Coding Questions & Solutions
1. Factorial of a Number
public class Factorial {
public static int factorial(int n) {
int result = 1;
for (int i = 2; i <= n; i++)
result *= i;
return result;
public static void main(String[] args) {
System.out.println(factorial(5)); // Output: 120
2. Prime Number Check
public class PrimeCheck {
public static boolean isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i <= Math.sqrt(n); i++)
if (n % i == 0) return false;
return true;
}
public static void main(String[] args) {
System.out.println(isPrime(7)); // true
3. Palindrome Number / String
public class Palindrome {
public static boolean isPalindrome(String str) {
return str.equals(new StringBuilder(str).reverse().toString());
public static void main(String[] args) {
System.out.println(isPalindrome("madam")); // true
4. Armstrong Number
public class Armstrong {
public static boolean isArmstrong(int num) {
int sum = 0, temp = num, digits = String.valueOf(num).length();
while (temp > 0) {
int digit = temp % 10;
sum += Math.pow(digit, digits);
temp /= 10;
return sum == num;
}
public static void main(String[] args) {
System.out.println(isArmstrong(153)); // true
5. Sum of Digits
public class SumOfDigits {
public static int sumDigits(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
return sum;
public static void main(String[] args) {
System.out.println(sumDigits(123)); // 6
6. Fibonacci Series
public class Fibonacci {
public static void printFibonacci(int n) {
int a = 0, b = 1;
for (int i = 1; i <= n; i++) {
System.out.print(a + " ");
int c = a + b;
a = b;
b = c;
public static void main(String[] args) {
printFibonacci(10);
7. LCM and GCD
public class GcdLcm {
public static int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
public static int lcm(int a, int b) {
return (a * b) / gcd(a, b);
public static void main(String[] args) {
System.out.println("GCD: " + gcd(12, 18));
System.out.println("LCM: " + lcm(12, 18));
}
8. Pattern Printing (Pyramid)
public class PyramidPattern {
public static void printPyramid(int n) {
for (int i = 1; i <= n; i++) {
for (int j = i; j < n; j++) System.out.print(" ");
for (int k = 1; k <= (2 * i - 1); k++) System.out.print("*");
System.out.println();
public static void main(String[] args) {
printPyramid(5);
9. Count Vowels
public class VowelCount {
public static int countVowels(String str) {
int count = 0;
str = str.toLowerCase();
for (char ch : str.toCharArray()) {
if ("aeiou".indexOf(ch) != -1) count++;
return count;
public static void main(String[] args) {
System.out.println(countVowels("TCS NQT")); // 2
10. Sort an Array
import java.util.Arrays;
public class SortArray {
public static void sort(int[] arr) {
Arrays.sort(arr);
for (int i : arr)
System.out.print(i + " ");
public static void main(String[] args) {
int[] arr = {5, 2, 8, 1};
sort(arr); // 1 2 5 8
11. Second Largest in Array
public class SecondLargest {
public static int findSecondLargest(int[] arr) {
int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int n : arr) {
if (n > first) {
second = first;
first = n;
} else if (n > second && n != first) {
second = n;
return second;
public static void main(String[] args) {
int[] arr = {10, 20, 30, 25};
System.out.println(findSecondLargest(arr)); // 25
12. Reverse a String
public class Reverse {
public static String reverse(String str) {
return new StringBuilder(str).reverse().toString();
public static void main(String[] args) {
System.out.println(reverse("TCS")); // SCT
13. Sum of Even and Odd Digits
public class SumEvenOdd {
public static void sumEvenOdd(int n) {
int even = 0, odd = 0;
while (n > 0) {
int d = n % 10;
if (d % 2 == 0) even += d;
else odd += d;
n /= 10;
System.out.println("Even: " + even + ", Odd: " + odd);
public static void main(String[] args) {
sumEvenOdd(123456); // Even: 12, Odd: 9
14. Missing Number in Array
public class MissingNumber {
public static int findMissing(int[] arr, int n) {
int total = n * (n + 1) / 2;
int sum = 0;
for (int num : arr) sum += num;
return total - sum;
public static void main(String[] args) {
int[] arr = {1, 2, 4, 5};
System.out.println(findMissing(arr, 5)); // 3
}
15. Swap Two Numbers
public class Swap {
public static void main(String[] args) {
int a = 5, b = 10;
// Without temp
a = a + b;
b = a - b;
a = a - b;
System.out.println("a=" + a + ", b=" + b);
16. Strong Number
public class StrongNumber {
public static int factorial(int n) {
int f = 1;
for (int i = 2; i <= n; i++) f *= i;
return f;
public static boolean isStrong(int n) {
int sum = 0, temp = n;
while (temp > 0) {
sum += factorial(temp % 10);
temp /= 10;
return sum == n;
}
public static void main(String[] args) {
System.out.println(isStrong(145)); // true
17. Automorphic Number
public class Automorphic {
public static boolean isAutomorphic(int n) {
int square = n * n;
return String.valueOf(square).endsWith(String.valueOf(n));
public static void main(String[] args) {
System.out.println(isAutomorphic(76)); // true
18. Leap Year Check
public class LeapYear {
public static boolean isLeap(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
public static void main(String[] args) {
System.out.println(isLeap(2024)); // true
}
}
19. Matrix Addition
public class MatrixAddition {
public static void main(String[] args) {
int[][] a = {{1, 2}, {3, 4}};
int[][] b = {{5, 6}, {7, 8}};
int[][] sum = new int[2][2];
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
sum[i][j] = a[i][j] + b[i][j];
for (int[] row : sum) {
for (int n : row) System.out.print(n + " ");
System.out.println();
20. Binary to Decimal
public class BinaryToDecimal {
public static int toDecimal(String binary) {
int decimal = 0, base = 1;
for (int i = binary.length() - 1; i >= 0; i--) {
decimal += (binary.charAt(i) - '0') * base;
base *= 2;
}
return decimal;
public static void main(String[] args) {
System.out.println(toDecimal("1011")); // 11
Great! Here are the Java solutions with explanations for the 8 coding problems from
the 2024 TCS Prime PYQ Practice Sheet:
1. Make Number Prime
Problem: Given a number n, find the minimum number to be added to make it a prime
number.
public class MakePrime {
public static boolean isPrime(int n) {
if (n < 2) return false;
for (int i = 2; i <= Math.sqrt(n); i++)
if (n % i == 0) return false;
return true;
public static int makePrime(int n) {
int i = 0;
while (!isPrime(n + i)) i++;
return i;
}
public static void main(String[] args) {
System.out.println(makePrime(14)); // Output: 3 → 14+3 = 17
2. Palindromic Factorial Less Than N
Problem: Find factorials starting from 1. Stop if factorial < N and is a palindrome.
public class PalindromicFactorial {
public static boolean isPalindrome(int n) {
String s = String.valueOf(n);
return s.equals(new StringBuilder(s).reverse().toString());
public static void main(String[] args) {
int N = 100000;
int fact = 1, i = 1;
while (true) {
fact *= i;
if (fact < N && isPalindrome(fact)) {
System.out.println("Palindromic factorial: " + fact);
break;
i++;
3. Count Palindromic Substrings
Problem: Count all substrings in a string that are palindromes.
public class CountPalindromes {
public static int countPalindromicSubstrings(String s) {
int count = 0;
for (int i = 0; i < s.length(); i++)
for (int j = i; j < s.length(); j++)
if (isPalindrome(s.substring(i, j + 1))) count++;
return count;
public static boolean isPalindrome(String s) {
return s.equals(new StringBuilder(s).reverse().toString());
public static void main(String[] args) {
System.out.println(countPalindromicSubstrings("abcba")); // Output: 7
4. Strong Number
Problem: A number is strong if the sum of the factorials of its digits is equal to the
number.
public class StrongNumber {
public static int factorial(int n) {
int f = 1;
for (int i = 2; i <= n; i++) f *= i;
return f;
}
public static boolean isStrong(int n) {
int sum = 0, temp = n;
while (temp > 0) {
sum += factorial(temp % 10);
temp /= 10;
return sum == n;
public static void main(String[] args) {
System.out.println(isStrong(145)); // true
5. Diagonal Difference (Matrix)
Problem: Find the absolute difference between the sum of primary and secondary
diagonals.
public class DiagonalDiff {
public static int diagonalDifference(int[][] mat) {
int n = mat.length;
int sum1 = 0, sum2 = 0;
for (int i = 0; i < n; i++) {
sum1 += mat[i][i];
sum2 += mat[i][n - i - 1];
return Math.abs(sum1 - sum2);
}
public static void main(String[] args) {
int[][] mat = {
{11, 2, 4},
{4, 5, 6},
{10, 8, -12}
};
System.out.println(diagonalDifference(mat)); // Output: 15
6. Divisor-Digit Count
Problem: Count how many digits in the number divide the number exactly.
public class DivisorDigits {
public static int countDivisorDigits(int n) {
int count = 0, temp = n;
while (temp > 0) {
int d = temp % 10;
if (d != 0 && n % d == 0) count++;
temp /= 10;
return count;
public static void main(String[] args) {
System.out.println(countDivisorDigits(124)); // Output: 2 (1 and 4 divide 124)
}
7. Prime Numbers in Range
Problem: Print all prime numbers in a range [A, B].
public class PrimeRange {
public static boolean isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i <= Math.sqrt(n); i++)
if (n % i == 0) return false;
return true;
public static void printPrimes(int a, int b) {
for (int i = a; i <= b; i++)
if (isPrime(i)) System.out.print(i + " ");
public static void main(String[] args) {
printPrimes(10, 20); // Output: 11 13 17 19
8. Anagram Substring Pairs
Problem: Count how many substring pairs in a string are anagrams.
For simplicity, we use HashMap<String, Integer> on sorted substrings.
import java.util.*;
public class AnagramPairs {
public static int countAnagramPairs(String s) {
Map<String, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
for (int j = i + 1; j <= s.length(); j++) {
char[] chars = s.substring(i, j).toCharArray();
Arrays.sort(chars);
String key = new String(chars);
map.put(key, map.getOrDefault(key, 0) + 1);
int count = 0;
for (int val : map.values()) {
count += val * (val - 1) / 2; // nC2 pairs
return count;
public static void main(String[] args) {
System.out.println(countAnagramPairs("abba")); // Output: 4