Java Programming Placement Questions
Java Programming Questions for Placement 2026 (with Solutions)
Last Updated: March 2026
Introduction
Java remains one of the most popular and widely-used programming languages in the industry. Its platform independence, robust standard library, and strong object-oriented features make it a favorite among companies like Infosys, TCS, Wipro, Cognizant, Accenture, Capgemini, and many product-based companies. Java is extensively tested in placement exams for its OOP concepts, collections framework, multithreading, and exception handling.
Why Java is Important for Placements
- Industry Standard: Widely used in enterprise applications, Android development, and web services
- OOP Mastery: Pure object-oriented language testing OOP understanding
- Platform Independence: Write Once, Run Anywhere philosophy
- Rich Ecosystem: Extensive libraries and frameworks (Spring, Hibernate)
- Strong Community: Abundant resources and documentation
Companies Testing Java Programming
| Company | Difficulty | Common Topics |
|---|---|---|
| Infosys | Moderate | OOP, Collections, Exception Handling |
| TCS | Easy-Moderate | Basics, Inheritance, Polymorphism |
| Wipro | Moderate | String handling, Arrays, Classes |
| Cognizant | Moderate | JDBC, Collections, Multithreading basics |
| Accenture | Moderate | OOP concepts, String manipulation |
| Capgemini | Moderate | Core Java, Collections |
| Product Companies | Hard | Advanced collections, Concurrency, Design Patterns |
Frequently Asked Coding Questions with Solutions
Question 1: Class and Object Implementation
Problem: Create a BankAccount class with deposit, withdrawal, and balance check functionality.
Solution:
class BankAccount {
private String accountNumber;
private String accountHolder;
private double balance;
// Constructor
public BankAccount(String accNum, String holder, double initialBalance) {
this.accountNumber = accNum;
this.accountHolder = holder;
this.balance = initialBalance;
}
// Deposit method
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposited: $" + amount);
} else {
System.out.println("Invalid deposit amount");
}
}
// Withdraw method
public boolean withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrawn: $" + amount);
return true;
} else {
System.out.println("Insufficient funds or invalid amount");
return false;
}
}
// Get balance
public double getBalance() {
return balance;
}
// Display account info
public void displayInfo() {
System.out.println("Account: " + accountNumber);
System.out.println("Holder: " + accountHolder);
System.out.println("Balance: $" + balance);
}
}
public class BankingSystem {
public static void main(String[] args) {
BankAccount account = new BankAccount("ACC001", "John Doe", 1000.0);
account.displayInfo();
System.out.println();
account.deposit(500.0);
account.withdraw(200.0);
System.out.println();
System.out.println("Current Balance: $" + account.getBalance());
}
}
Output:
Account: ACC001
Holder: John Doe
Balance: $1000.0
Deposited: $500.0
Withdrawn: $200.0
Current Balance: $1300.0
Question 2: Inheritance and Method Overriding
Problem: Demonstrate inheritance with Employee as parent and Manager/Developer as child classes.
Solution:
// Parent class
class Employee {
protected String name;
protected int id;
protected double salary;
public Employee(String name, int id, double salary) {
this.name = name;
this.id = id;
this.salary = salary;
}
public void work() {
System.out.println(name + " is working");
}
public double calculateBonus() {
return salary * 0.10;
}
public void displayInfo() {
System.out.println("ID: " + id + ", Name: " + name);
System.out.println("Salary: $" + salary);
}
}
// Child class - Manager
class Manager extends Employee {
private int teamSize;
public Manager(String name, int id, double salary, int teamSize) {
super(name, id, salary);
this.teamSize = teamSize;
}
@Override
public void work() {
System.out.println(name + " is managing a team of " + teamSize);
}
@Override
public double calculateBonus() {
return salary * 0.20; // 20% bonus
}
public void conductMeeting() {
System.out.println(name + " is conducting a team meeting");
}
}
// Child class - Developer
class Developer extends Employee {
private String programmingLanguage;
public Developer(String name, int id, double salary, String lang) {
super(name, id, salary);
this.programmingLanguage = lang;
}
@Override
public void work() {
System.out.println(name + " is coding in " + programmingLanguage);
}
@Override
public double calculateBonus() {
return salary * 0.15; // 15% bonus
}
public void debugCode() {
System.out.println(name + " is debugging code");
}
}
public class CompanySystem {
public static void main(String[] args) {
Manager manager = new Manager("Alice", 101, 80000, 10);
Developer developer = new Developer("Bob", 102, 60000, "Java");
System.out.println("=== Manager ===");
manager.displayInfo();
manager.work();
System.out.println("Bonus: $" + manager.calculateBonus());
manager.conductMeeting();
System.out.println("\n=== Developer ===");
developer.displayInfo();
developer.work();
System.out.println("Bonus: $" + developer.calculateBonus());
developer.debugCode();
}
}
Output:
=== Manager ===
ID: 101, Name: Alice
Salary: $80000.0
Alice is managing a team of 10
Bonus: $16000.0
Alice is conducting a team meeting
=== Developer ===
ID: 102, Name: Bob
Salary: $60000.0
Bob is coding in Java
Bonus: $9000.0
Bob is debugging code
Question 3: Interface Implementation
Problem: Create interfaces and demonstrate multiple interface implementation.
Solution:
// Interface 1
interface Drawable {
void draw();
default void print() {
System.out.println("Printing...");
}
}
// Interface 2
interface Resizable {
void resize(double factor);
}
// Interface 3
interface Movable {
void move(int x, int y);
}
// Class implementing multiple interfaces
class Rectangle implements Drawable, Resizable, Movable {
private double width;
private double height;
private int x, y;
public Rectangle(double w, double h) {
this.width = w;
this.height = h;
this.x = 0;
this.y = 0;
}
@Override
public void draw() {
System.out.println("Drawing rectangle: " + width + " x " + height);
}
@Override
public void resize(double factor) {
width *= factor;
height *= factor;
System.out.println("Resized to: " + width + " x " + height);
}
@Override
public void move(int newX, int newY) {
x = newX;
y = newY;
System.out.println("Moved to position: (" + x + ", " + y + ")");
}
public double getArea() {
return width * height;
}
}
public class InterfaceDemo {
public static void main(String[] args) {
Rectangle rect = new Rectangle(10, 20);
rect.draw();
rect.move(5, 10);
rect.resize(1.5);
System.out.println("Area: " + rect.getArea());
rect.print(); // Default method from Drawable
}
}
Output:
Drawing rectangle: 10.0 x 20.0
Moved to position: (5, 10)
Resized to: 15.0 x 30.0
Area: 450.0
Printing...
Question 4: ArrayList Operations
Problem: Demonstrate ArrayList operations with custom objects.
Solution:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
class Student implements Comparable<Student> {
private String name;
private int rollNumber;
private double marks;
public Student(String name, int roll, double marks) {
this.name = name;
this.rollNumber = roll;
this.marks = marks;
}
public String getName() { return name; }
public int getRollNumber() { return rollNumber; }
public double getMarks() { return marks; }
@Override
public int compareTo(Student other) {
return this.rollNumber - other.rollNumber;
}
@Override
public String toString() {
return rollNumber + ": " + name + " (" + marks + ")";
}
}
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
// Adding elements
students.add(new Student("Alice", 103, 85.5));
students.add(new Student("Bob", 101, 90.0));
students.add(new Student("Charlie", 102, 78.5));
System.out.println("=== Original List ===");
for (Student s : students) {
System.out.println(s);
}
// Sort by roll number (using Comparable)
Collections.sort(students);
System.out.println("\n=== Sorted by Roll Number ===");
for (Student s : students) {
System.out.println(s);
}
// Sort by marks (using Comparator)
students.sort(Comparator.comparingDouble(Student::getMarks).reversed());
System.out.println("\n=== Sorted by Marks (Desc) ===");
for (Student s : students) {
System.out.println(s);
}
// Find student with highest marks
Student topStudent = Collections.max(students, Comparator.comparingDouble(Student::getMarks));
System.out.println("\nTop Student: " + topStudent);
}
}
Output:
=== Original List ===
103: Alice (85.5)
101: Bob (90.0)
102: Charlie (78.5)
=== Sorted by Roll Number ===
101: Bob (90.0)
102: Charlie (78.5)
103: Alice (85.5)
=== Sorted by Marks (Desc) ===
101: Bob (90.0)
103: Alice (85.5)
102: Charlie (78.5)
Top Student: 101: Bob (90.0)
Question 5: HashMap Usage
Problem: Count word frequencies using HashMap.
Solution:
import java.util.HashMap;
import java.util.Map;
public class WordFrequency {
public static void main(String[] args) {
String text = "the quick brown fox jumps over the lazy dog the fox was quick";
// Split into words
String[] words = text.toLowerCase().split("\\s+");
// Count frequencies
HashMap<String, Integer> frequencyMap = new HashMap<>();
for (String word : words) {
frequencyMap.put(word, frequencyMap.getOrDefault(word, 0) + 1);
}
// Display results
System.out.println("=== Word Frequencies ===");
for (Map.Entry<String, Integer> entry : frequencyMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// Find most frequent word
String mostFrequent = "";
int maxCount = 0;
for (Map.Entry<String, Integer> entry : frequencyMap.entrySet()) {
if (entry.getValue() > maxCount) {
maxCount = entry.getValue();
mostFrequent = entry.getKey();
}
}
System.out.println("\nMost frequent word: '" + mostFrequent + "' (appears " + maxCount + " times)");
// Check if word exists
if (frequencyMap.containsKey("fox")) {
System.out.println("'fox' appears " + frequencyMap.get("fox") + " times");
}
}
}
Output:
=== Word Frequencies ===
the: 3
quick: 2
brown: 1
fox: 2
jumps: 1
over: 1
lazy: 1
dog: 1
was: 1
Most frequent word: 'the' (appears 3 times)
'fox' appears 2 times
Question 6: Exception Handling
Problem: Demonstrate custom exception and exception handling.
Solution:
// Custom exception
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
class InvalidAmountException extends RuntimeException {
public InvalidAmountException(String message) {
super(message);
}
}
class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}
public void withdraw(double amount) throws InsufficientFundsException {
if (amount <= 0) {
throw new InvalidAmountException("Amount must be positive");
}
if (amount > balance) {
throw new InsufficientFundsException("Insufficient funds. Balance: $" + balance);
}
balance -= amount;
System.out.println("Withdrawn: $" + amount);
}
public double getBalance() {
return balance;
}
}
public class ExceptionDemo {
public static void main(String[] args) {
BankAccount account = new BankAccount(1000.0);
// Test 1: Normal withdrawal
try {
account.withdraw(500.0);
System.out.println("Balance: $" + account.getBalance());
} catch (InsufficientFundsException e) {
System.out.println("Error: " + e.getMessage());
}
// Test 2: Insufficient funds
try {
account.withdraw(1000.0);
} catch (InsufficientFundsException e) {
System.out.println("Error: " + e.getMessage());
}
// Test 3: Invalid amount (runtime exception)
try {
account.withdraw(-100.0);
} catch (InsufficientFundsException e) {
System.out.println("Error: " + e.getMessage());
} catch (InvalidAmountException e) {
System.out.println("Error: " + e.getMessage());
}
System.out.println("\nProgram continues normally...");
}
}
Output:
Withdrawn: $500.0
Balance: $500.0
Error: Insufficient funds. Balance: $500.0
Error: Amount must be positive
Program continues normally...
Question 7: String Manipulation
Problem: Demonstrate various String operations.
Solution:
public class StringOperations {
public static void main(String[] args) {
String str = " Hello, World! Welcome to Java ";
// Basic operations
System.out.println("Original: '" + str + "'");
System.out.println("Trimmed: '" + str.trim() + "'");
System.out.println("Length: " + str.length());
System.out.println("Uppercase: " + str.toUpperCase());
System.out.println("Lowercase: " + str.toLowerCase());
// Substring
String substring = str.substring(10, 15);
System.out.println("Substring (10,15): '" + substring + "'");
// Replace
String replaced = str.replace("World", "Java");
System.out.println("Replaced: " + replaced);
// Split
String[] words = str.trim().split("\\s+");
System.out.println("\nWords count: " + words.length);
for (String word : words) {
System.out.println("- " + word);
}
// StringBuilder for mutable strings
StringBuilder sb = new StringBuilder();
sb.append("Java");
sb.append(" is");
sb.append(" awesome");
System.out.println("\nStringBuilder: " + sb.toString());
sb.reverse();
System.out.println("Reversed: " + sb.toString());
// Check palindrome
String palindrome = "racecar";
boolean isPalindrome = new StringBuilder(palindrome).reverse().toString().equals(palindrome);
System.out.println("\n'" + palindrome + "' is palindrome: " + isPalindrome);
}
}
Output:
Original: ' Hello, World! Welcome to Java '
Trimmed: 'Hello, World! Welcome to Java'
Length: 33
Uppercase: ' HELLO, WORLD! WELCOME TO JAVA '
Lowercase: ' hello, world! welcome to java '
Substring (10,15): 'orld!'
Replaced: Hello, Java! Welcome to Java
Words count: 5
- Hello,
- World!
- Welcome
- to
- Java
StringBuilder: Java is awesome
Reversed: emosewa si avaJ
'racecar' is palindrome: true
Question 8: Multithreading Basics
Problem: Create and run multiple threads.
Solution:
class NumberPrinter extends Thread {
private String name;
private int start;
private int end;
public NumberPrinter(String name, int start, int end) {
this.name = name;
this.start = start;
this.end = end;
}
@Override
public void run() {
for (int i = start; i <= end; i++) {
System.out.println(name + ": " + i);
try {
Thread.sleep(100); // Sleep for 100ms
} catch (InterruptedException e) {
System.out.println(name + " interrupted");
}
}
System.out.println(name + " finished");
}
}
class RunnableTask implements Runnable {
private String message;
public RunnableTask(String msg) {
this.message = msg;
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println(Thread.currentThread().getName() + ": " + message);
try {
Thread.sleep(150);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
// Using Thread class
NumberPrinter t1 = new NumberPrinter("Thread-1", 1, 3);
NumberPrinter t2 = new NumberPrinter("Thread-2", 10, 12);
// Using Runnable interface
Thread t3 = new Thread(new RunnableTask("Hello from Runnable"), "Runnable-Thread");
System.out.println("Starting threads...\n");
t1.start();
t2.start();
t3.start();
// Wait for threads to complete
try {
t1.join();
t2.join();
t3.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("\nAll threads completed!");
}
}
Output: (Order may vary)
Starting threads...
Thread-1: 1
Thread-2: 10
Runnable-Thread: Hello from Runnable
Thread-1: 2
Thread-2: 11
Runnable-Thread: Hello from Runnable
Thread-1: 3
Thread-2: 12
Runnable-Thread: Hello from Runnable
Thread-1 finished
Thread-2 finished
All threads completed!
Question 9: File I/O Operations
Problem: Read from and write to files.
Solution:
import java.io.*;
import java.util.ArrayList;
import java.util.List;
class Student implements Serializable {
private String name;
private int roll;
private double marks;
public Student(String name, int roll, double marks) {
this.name = name;
this.roll = roll;
this.marks = marks;
}
@Override
public String toString() {
return roll + "," + name + "," + marks;
}
}
public class FileOperations {
public static void main(String[] args) {
String filename = "students.txt";
List<Student> students = new ArrayList<>();
students.add(new Student("Alice", 101, 85.5));
students.add(new Student("Bob", 102, 90.0));
students.add(new Student("Charlie", 103, 78.5));
// Write to file
writeToFile(students, filename);
// Read from file
System.out.println("\nReading from file:");
readFromFile(filename);
}
static void writeToFile(List<Student> students, String filename) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) {
writer.write("Roll,Name,Marks");
writer.newLine();
for (Student s : students) {
writer.write(s.toString());
writer.newLine();
}
System.out.println("Data written to " + filename);
} catch (IOException e) {
System.out.println("Error writing: " + e.getMessage());
}
}
static void readFromFile(String filename) {
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
String line;
boolean isFirstLine = true;
while ((line = reader.readLine()) != null) {
if (isFirstLine) {
System.out.println("Header: " + line);
isFirstLine = false;
} else {
String[] parts = line.split(",");
System.out.println("Student: Roll=" + parts[0] +
", Name=" + parts[1] +
", Marks=" + parts[2]);
}
}
} catch (IOException e) {
System.out.println("Error reading: " + e.getMessage());
}
}
}
Question 10: Lambda Expressions and Streams
Problem: Demonstrate Java 8+ features: Lambdas and Streams.
Solution:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
class Employee {
private String name;
private String department;
private double salary;
public Employee(String name, String dept, double salary) {
this.name = name;
this.department = dept;
this.salary = salary;
}
public String getName() { return name; }
public String getDepartment() { return department; }
public double getSalary() { return salary; }
}
public class StreamDemo {
public static void main(String[] args) {
List<Employee> employees = Arrays.asList(
new Employee("Alice", "IT", 75000),
new Employee("Bob", "HR", 60000),
new Employee("Charlie", "IT", 80000),
new Employee("David", "Finance", 70000),
new Employee("Eve", "HR", 65000)
);
// Filter employees with salary > 65000
System.out.println("Employees with salary > 65000:");
employees.stream()
.filter(e -> e.getSalary() > 65000)
.forEach(e -> System.out.println("- " + e.getName() + ": $" + e.getSalary()));
// Calculate average salary by department
System.out.println("\nAverage salary by department:");
employees.stream()
.collect(Collectors.groupingBy(
Employee::getDepartment,
Collectors.averagingDouble(Employee::getSalary)
))
.forEach((dept, avg) -> System.out.println(dept + ": $" + avg));
// Find highest paid employee
Employee highestPaid = employees.stream()
.max((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()))
.orElse(null);
System.out.println("\nHighest paid: " + highestPaid.getName() +
" ($" + highestPaid.getSalary() + ")");
// Get names of all IT employees (sorted)
List<String> itEmployees = employees.stream()
.filter(e -> e.getDepartment().equals("IT"))
.map(Employee::getName)
.sorted()
.collect(Collectors.toList());
System.out.println("\nIT Employees: " + itEmployees);
// Count employees in HR
long hrCount = employees.stream()
.filter(e -> e.getDepartment().equals("HR"))
.count();
System.out.println("HR Employee count: " + hrCount);
}
}
Output:
Employees with salary > 65000:
- Alice: $75000.0
- Charlie: $80000.0
- David: $70000.0
Average salary by department:
Finance: $70000.0
HR: $62500.0
IT: $77500.0
Highest paid: Charlie ($80000.0)
IT Employees: [Alice, Charlie]
HR Employee count: 2
Output Prediction Questions (10 Questions)
Question 1: What is the output?
public class Test {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "Hello";
System.out.println(s1 == s2);
}
}
Question 2: What is the output?
public class Test {
public static void main(String[] args) {
String s1 = new String("Hello");
String s2 = new String("Hello");
System.out.println(s1 == s2);
}
}
Question 3: What is the output?
public class Test {
static int x = 10;
public static void main(String[] args) {
Test t1 = new Test();
Test t2 = new Test();
t1.x = 20;
System.out.println(t2.x);
}
}
Question 4: What is the output?
class Parent {
void show() { System.out.println("Parent"); }
}
class Child extends Parent {
void show() { System.out.println("Child"); }
}
public class Test {
public static void main(String[] args) {
Parent p = new Child();
p.show();
}
}
Question 5: What is the output?
public class Test {
public static void main(String[] args) {
try {
int x = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("AE");
} catch (Exception e) {
System.out.println("E");
}
}
}
Question 6: What is the output?
import java.util.*;
public class Test {
public static void main(String[] args) {
HashSet<Integer> set = new HashSet<>();
set.add(3);
set.add(1);
set.add(2);
set.add(1);
System.out.println(set);
}
}
Question 7: What is the output?
public class Test {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println(sb);
}
}
Question 8: What is the output?
public class Test {
public static void main(String[] args) {
Integer i1 = 127;
Integer i2 = 127;
System.out.println(i1 == i2);
}
}
Question 9: What is the output?
public class Test {
public static void main(String[] args) {
Integer i1 = 128;
Integer i2 = 128;
System.out.println(i1 == i2);
}
}
Question 10: What is the output?
public class Test {
public static void main(String[] args) {
int[] arr = {1, 2, 3};
System.out.println(arr.length);
}
}
MCQs on Java Fundamentals (10 Questions)
Question 1: Which keyword is used to inherit a class?
a) implements b) extends c) inherits d) uses
Question 2: What is the superclass of all classes in Java?
a) Class b) Object c) Super d) Main
Question 3: Which collection doesn't allow duplicates?
a) List b) Set c) Map d) Queue
Question 4: What is the default value of int variable?
a) 0 b) null c) undefined d) -1
Question 5: Can we have multiple catch blocks?
a) Yes b) No c) Only two d) Depends on try block
Question 6: Which interface provides sorting capability?
a) Runnable b) Comparable c) Serializable d) Cloneable
Question 7: What is method overloading?
a) Same method name, different parameters b) Same method name, different return type c) Different method names d) Changing method in subclass
Question 8: Can an interface extend another interface?
a) Yes b) No c) Only with implements d) Only abstract interfaces
Question 9: What does 'final' keyword mean for a class?
a) Cannot be instantiated b) Cannot be extended c) Cannot have methods d) Must be abstract
Question 10: Which is not a wrapper class?
a) Integer b) Float c) Char d) Boolean
Tips for Java Coding Rounds
1. Master OOP Concepts
- Understand inheritance, polymorphism, encapsulation
- Know when to use abstract class vs interface
- Practice design patterns basics
2. Collections Framework
- Know List, Set, Map differences
- Understand when to use ArrayList vs LinkedList
- Master HashMap and TreeMap
3. String Handling
- Know String immutability
- Use StringBuilder for modifications
- Understand String pool concept
4. Exception Handling
- Know checked vs unchecked exceptions
- Use try-with-resources
- Create custom exceptions when needed
5. Java 8+ Features
- Master lambda expressions
- Understand Stream API
- Know default and static methods in interfaces
6. Memory Management
- Understand garbage collection
- Know about memory leaks
- Understand stack vs heap
Frequently Asked Questions (FAQ)
Q1: Is Java better than C++ for placements?
Both have their strengths. Java is preferred for enterprise/web development roles, while C++ is preferred for systems/game development. Many companies accept either. Choose based on the role you're targeting.
Q2: What are the most important Java topics for placements?
Core Java: OOP concepts, Collections framework, Exception handling, String manipulation, Multithreading basics. Advanced: Streams API, Generics, JDBC basics.
Q3: Should I learn Spring/Hibernate for placements?
For service-based companies, core Java is sufficient. For product companies, basic Spring knowledge is beneficial. Focus on strong fundamentals first.
Q4: What's the difference between String, StringBuilder, and StringBuffer?
String: immutable, thread-safe StringBuilder: mutable, not thread-safe (faster) StringBuffer: mutable, thread-safe (slower due to synchronization)
Q5: How important are Java 8 features for placements?
Very important! Lambda expressions, Stream API, and functional interfaces are commonly asked. Modern Java code heavily uses these features.
Master Java through consistent practice focusing on OOP concepts, collections, and modern Java features. Practice writing clean, efficient code using best practices. Good luck with your placement preparation!
Explore this topic cluster
More resources in Uncategorized
Use the category hub to browse similar questions, exam patterns, salary guides, and preparation resources related to this topic.