Basic Java Interview Programs for Freshers with Questions and Answers

Basic Java Interview Programs
Basic Java Interview Programs

Introduction to Basic Java Interview Programs

Basic Java interview programs play a crucial role in evaluating a candidate’s understanding of Java and their ability to apply core concepts through coding. In most technical interviews, employers focus on simple yet logical programs to assess how well a candidate understands Java fundamentals, problem-solving approach, and coding structure. Java is one of the most widely used programming languages and is commonly applied in building real-world Java applications. Because of this, interviewers often ask basic Java programs that test knowledge of variables, control statements, loops, classes, and object handling. These programs help interviewers understand whether a candidate can translate theoretical concepts into working code.

For freshers, practicing basic Java interview programs builds confidence and strengthens coding skills required to clear entry-level interviews. A clear understanding of how Java code is compiled into Java bytecode and executed by the Java Virtual Machine also helps candidates explain their solutions more effectively during interviews.

Why Basic Java Interview Programs Are Important?

Basic Java interview programs are important because they help interviewers evaluate a candidate’s knowledge of Java fundamentals and their ability to apply concepts in real coding scenarios. Rather than testing memorized answers, interviewers prefer simple programs to check how well a candidate understands logic, syntax, and program flow while writing code. Java is a widely used object-oriented programming language, and many companies rely on it for building scalable applications. By asking basic Java programs, interviewers can assess how comfortably a candidate works with classes, objects, methods, and control structures using Java. These programs also reveal how well a candidate handles programming errors and approaches problem-solving under interview conditions.

For freshers, practicing basic Java interview programs improves overall programming skills and builds confidence in writing code during interviews. It also helps candidates understand how Java source code is converted into Java bytecode and executed within the Java runtime environment, which is often discussed during technical interviews. Overall, basic Java interview programs act as a strong foundation for advanced topics and prepare candidates to face commonly asked Java interview questions with clarity and confidence.

Java Interview Programs
Java Interview Programs

Core Java Concepts for Interview Programs

Core Java interview programs are designed to test how well a candidate understands basic programming logic and applies Java concepts through code. These programs are simple in nature but reveal a candidate’s clarity in syntax, control flow, and problem-solving approach using the Java programming language.

Java Basic Concepts for Interviews

Interviewers often start with small Java programs that test fundamentals like conditions, loops, and basic logic.

Example 1: Java Program to Check Whether a Number Is Even or Odd

class EvenOdd {
    public static void main(String[] args) {
        int number = 10;

        if (number % 2 == 0) {
            System.out.println("Even number");
        } else {
            System.out.println("Odd number");
        }
    }
}

This program is commonly asked in interviews to check understanding of conditional statements and operators.

Example 2: Java Program to Find the Largest of Two Numbers

class LargestNumber {
    public static void main(String[] args) {
        int a = 15;
        int b = 20;

        if (a > b) {
            System.out.println("A is greater");
        } else {
            System.out.println("B is greater");
        }
    }
}

Such programs help interviewers assess logical thinking and basic comparison operations.

Object-Oriented Programming in Java

Since Java is an object-oriented programming language, interviewers often check how well candidates understand classes, objects, and methods through simple programs.

Example 3: Java Program Using Class and Object

class Student {
    int id;
    String name;

    void display() {
        System.out.println(id + " " + name);
    }

    public static void main(String[] args) {
        Student s = new Student();
        s.id = 101;
        s.name = "John";
        s.display();
    }
}

This program tests understanding of class creation, object instantiation, and method calling.

Example 4: Java Program Demonstrating Interface

interface Animal {
    void sound();
}

class Dog implements Animal {
    public void sound() {
        System.out.println("Dog barks");
    }

    public static void main(String[] args) {
        Dog d = new Dog();
        d.sound();
    }
}

This example checks knowledge of interfaces, abstraction, and implementation commonly asked concepts in Java interviews.

Basic Java Interview Programs for Freshers

Basic Java interview programs for freshers are usually simple but very important, as they help interviewers understand a candidate’s coding approach, logic, and clarity in Java fundamentals. These programs focus on writing correct code, using proper syntax, and applying basic concepts rather than solving complex problems.

Java Interview Questions for Freshers

Freshers are commonly asked basic Java interview questions along with small programs to test their understanding of core concepts. Interviewers may ask about data types, loops, conditional statements, classes, and keywords used in Java. Questions often revolve around how Java works internally, how a Java program is executed, and how errors are handled during compilation and runtime. Having a clear knowledge of Java fundamentals helps freshers explain their answers confidently during interviews. In fresher-level Java interviews, candidates are often asked to write small Java programs to test their understanding of basic concepts, syntax, and logical thinking. These programs are simple but help interviewers quickly evaluate how well a candidate understands Java fundamentals.

Example 1: Java Program to Check Whether a Number Is Even or Odd

class EvenOdd {
    public static void main(String[] args) {
        int num = 7;

        if (num % 2 == 0) {
            System.out.println("Even number");
        } else {
            System.out.println("Odd number");
        }
    }
}

This program checks knowledge of conditional statements and arithmetic operators.

Example 2: Java Program to Find the Largest of Two Numbers

class LargestOfTwo {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;

        if (a > b) {
            System.out.println("A is greater");
        } else {
            System.out.println("B is greater");
        }
    }
}

Interviewers use this to test logical comparison and decision-making skills.

Example 3: Java Program to Print Numbers from 1 to 5

class PrintNumbers {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.println(i);
        }
    }
}

This program checks understanding of loops and iteration.

Example 4: Java Program to Find the Sum of Natural Numbers

class SumNatural {
    public static void main(String[] args) {
        int sum = 0;

        for (int i = 1; i <= 5; i++) {
            sum = sum + i;
        }

        System.out.println("Sum = " + sum);
    }
}

This is a commonly asked fresher-level program to test looping and variable handling.

Simple Java Programs for Interview

Interviewers often ask freshers to write simple Java programs to check their practical coding skills.

Example 1: Java Program to Find the Sum of Two Numbers

class SumOfNumbers {
    public static void main(String[] args) {
        int a = 5;
        int b = 10;
        int sum = a + b;

        System.out.println("Sum = " + sum);
    }
}

This program tests basic arithmetic operations and variable usage.

Example 2: Java Program to Check Whether a Number Is Positive or Negative

class PositiveNegative {
    public static void main(String[] args) {
        int number = -3;

        if (number > 0) {
            System.out.println("Positive number");
        } else {
            System.out.println("Negative number");
        }
    }
}

Such programs are commonly asked Java interview programs for freshers to evaluate logical thinking and conditional handling. Practicing these simple Java interview programs helps freshers build confidence, improve coding accuracy, and prepare effectively for entry-level Java interviews.

Java Interview Programs on Arrays and Collections

In Java interviews, array and collection-based programs are used to understand how candidates manage data, apply looping logic, and work with built-in data structures. These programs are especially important because arrays and collections are heavily used while building real Java applications and solving day-to-day programming problems.

Array in Java – Interview Programs

Array-related questions are commonly asked to test how well a candidate understands indexing, iteration, and basic data manipulation.

Example 1: Java Program to Calculate the Total of Array Values

class ArrayTotal {
    public static void main(String[] args) {
        int[] values = {3, 6, 9, 12};
        int total = 0;

        for (int value : values) {
            total += value;
        }

        System.out.println("Total value = " + total);
    }
}

This program helps interviewers check knowledge of arrays and enhanced for-loops.

Example 2: Java Program to Identify the Highest Value in an Array

class HighestValue {
    public static void main(String[] args) {
        int[] data = {15, 8, 22, 4};
        int highest = data[0];

        for (int i = 1; i < data.length; i++) {
            if (data[i] > highest) {
                highest = data[i];
            }
        }

        System.out.println("Highest value = " + highest);
    }
}

Such programs are frequently asked to test comparison logic and array traversal.

Java Collections Framework Interview Programs

The Java Collections Framework allows flexible storage and handling of objects. Interviewers use simple collection-based programs to check whether candidates can use collections effectively instead of arrays.

Example 3: Java Program to Store and Display Values Using ArrayList

import java.util.ArrayList;

class CollectionDisplay {
    public static void main(String[] args) {
        ArrayList<String> courses = new ArrayList<>();
        courses.add("Java");
        courses.add("Spring");
        courses.add("Hibernate");

        for (String course : courses) {
            System.out.println(course);
        }
    }
}

This program checks familiarity with collections, generics, and iteration.

Example 4: Java Program to Count Elements in a Collection

import java.util.ArrayList;

class CollectionCount {
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(5);
        numbers.add(10);
        numbers.add(15);

        System.out.println("Number of elements = " + numbers.size());
    }
}

Interviewers use such programs to verify understanding of common collection methods.

Java Coding Interview Questions and Challenges

Java coding interview challenges are used to assess how well candidates translate logic into working programs. These questions focus on problem-solving ability, clarity in writing Java code, and how efficiently a solution is implemented. Interviewers are more interested in the thought process than complex syntax.

Java Coding Interview Questions

Candidates are often asked small programs that test loop handling, condition checks, and number or string processing.

Example 1: Java Program to Count Digits in a Number

class CountDigits {
    public static void main(String[] args) {
        int number = 56789;
        int count = 0;

        while (number > 0) {
            number = number / 10;
            count++;
        }

        System.out.println("Total digits = " + count);
    }
}

This program checks understanding of loops and integer manipulation.

Example 2: Java Program to Find the Sum of Digits

class SumOfDigits {
    public static void main(String[] args) {
        int number = 123;
        int sum = 0;

        while (number != 0) {
            sum += number % 10;
            number /= 10;
        }

        System.out.println("Sum of digits = " + sum);
    }
}

Interviewers use this question to evaluate logical flow and arithmetic operations.

Pattern Programs in Java

Pattern-based questions are popular because they reveal how well candidates understand nested loops and output formatting.

Example 3: Java Program to Print a Number Pattern

class NumberPattern {
    public static void main(String[] args) {
        for (int i = 1; i <= 4; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(j + " ");
            }
            System.out.println();
        }
    }
}

This program tests loop nesting and output control.

Java Interview Programs for Experienced Professionals

For experienced Java developers, interview programs are designed to evaluate the depth of understanding, not just the correctness of output. Interviewers focus on how efficiently a solution is written, how edge cases are handled, and how well the candidate understands Java’s internal behavior in real execution scenarios.

Core Java Interview Questions for Experienced

At this level, programs usually involve refining logic and demonstrating better control over data and execution flow.

Example 1: Java Program to Check Whether an Array Contains a Specific Element

class SearchElement {
    public static void main(String[] args) {
        int[] values = {3, 8, 12, 5, 9};
        int target = 12;
        boolean found = false;

        for (int value : values) {
            if (value == target) {
                found = true;
                break;
            }
        }

        if (found) {
            System.out.println("Element found");
        } else {
            System.out.println("Element not found");
        }
    }
}

This program is used to evaluate loop usage, conditional checks, and clean logical flow—often discussed in experienced-level interviews.

Example 2: Java Program to Reverse an Array

class ReverseArray {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};

        for (int i = arr.length - 1; i >= 0; i--) {
            System.out.print(arr[i] + " ");
        }
    }
}

Interviewers use such programs to assess array handling and iteration logic.

Java Multithreading and Memory Interview Programs

For senior roles, interviewers frequently explore concurrency and memory-related concepts, as these directly impact application performance and stability.

Example 3: Java Program Using Runnable Interface

class Task implements Runnable {
    public void run() {
        System.out.println("Task executed by thread");
    }

    public static void main(String[] args) {
        Thread t = new Thread(new Task());
        t.start();
    }
}

This program tests understanding of thread creation using Runnable, which is preferred in many real-world applications.

Example 4: Java Program Demonstrating Object Eligibility for Garbage Collection

class MemoryTest {
    public static void main(String[] args) {
        MemoryTest ref1 = new MemoryTest();
        MemoryTest ref2 = new MemoryTest();

        ref1 = ref2;
        System.gc();

        System.out.println("Objects are eligible for garbage collection");
    }
}

This example helps interviewers discuss memory cleanup and garbage collection in Java, a common topic for experienced professionals.

Java 8 Interview Programs and Modern Java Concepts

Java 8 interview programs focus on functional programming, cleaner syntax, and improved coding efficiency. Interviewers use these programs to check how well candidates understand modern Java concepts such as lambda expressions, streams, and functional interfaces.

Java 8 Features in Interview Programs

1. Java 8 Program Using Lambda Expression

interface Hello {

    void sayHello();

}

class LambdaDemo {

    public static void main(String[] args) {

        Hello h = () -> System.out.println("Hello Java 8");

        h.sayHello();

    }

}

2. Java 8 Program to Iterate List Using forEach

import java.util.*;

class ForEachExample {

    public static void main(String[] args) {

        List<String> names = Arrays.asList("Java", "Python", "C++");

        names.forEach(n -> System.out.println(n));

    }

}

3. Java 8 Program to Filter Even Numbers Using Stream

import java.util.*;

class EvenStream {

    public static void main(String[] args) {

        List<Integer> nums = Arrays.asList(1,2,3,4,5,6);

        nums.stream().filter(n -> n % 2 == 0).forEach(System.out::println);

    }

}

4. Java 8 Program to Sort List Using Lambda

import java.util.*;

class SortList {

    public static void main(String[] args) {

        List<Integer> list = Arrays.asList(5,2,8,1);

        list.sort((a,b) -> a - b);

        System.out.println(list);

    }

}

5. Java 8 Program to Find Length of Strings Using Stream

import java.util.*;

class StringLength {

    public static void main(String[] args) {

        List<String> words = Arrays.asList("Java","Spring","Boot");

        words.stream().map(String::length).forEach(System.out::println);

    }

}

6. Java 8 Program Using Method Reference

interface Print {

    void show(String msg);

}

class MethodRef {

    static void display(String msg) {

        System.out.println(msg);

    }

    public static void main(String[] args) {

        Print p = MethodRef::display;

        p.show("Method Reference Example");

    }

}

7. Java 8 Program to Convert List to Uppercase

import java.util.*;

class UpperCase {

    public static void main(String[] args) {

        List<String> list = Arrays.asList("java","api");

        list.stream().map(String::toUpperCase).forEach(System.out::println);

    }

}

8. Java 8 Program to Find First Element Using Stream

import java.util.*;

class FirstElement {

    public static void main(String[] args) {

        List<Integer> list = Arrays.asList(10,20,30);

        list.stream().findFirst().ifPresent(System.out::println);

    }

}

9. Java 8 Program to Count Elements in Stream

import java.util.*;

class CountStream {

    public static void main(String[] args) {

        List<String> list = Arrays.asList("A","B","C");

        System.out.println(list.stream().count());

    }

}

10. Java 8 Program Using Predicate

import java.util.function.Predicate;

class PredicateDemo {

    public static void main(String[] args) {

        Predicate<Integer> isEven = n -> n % 2 == 0;

        System.out.println(isEven.test(4));

    }

}

11. Java 8 Program Using Consumer

import java.util.function.Consumer;

class ConsumerDemo {

    public static void main(String[] args) {

        Consumer<String> c = s -> System.out.println(s);

        c.accept("Java 8 Consumer");

    }

}

12. Java 8 Program Using Supplier

import java.util.function.Supplier;

class SupplierDemo {

    public static void main(String[] args) {

        Supplier<Double> s = () -> Math.random();

        System.out.println(s.get());

    }

}

13. Java 8 Program to Remove Duplicate Elements

import java.util.*;

class RemoveDuplicates {

    public static void main(String[] args) {

        List<Integer> list = Arrays.asList(1,2,2,3,3);

        list.stream().distinct().forEach(System.out::println);

    }

}

14. Java 8 Program to Sum Numbers Using Stream

import java.util.*;

class SumStream {

    public static void main(String[] args) {

        List<Integer> list = Arrays.asList(1,2,3);

        int sum = list.stream().mapToInt(i -> i).sum();

        System.out.println(sum);

    }

}

15. Java 8 Program Using Optional

import java.util.Optional;

class OptionalDemo {

    public static void main(String[] args) {

        Optional<String> name = Optional.of("Java");

        System.out.println(name.isPresent());

    }

}

Java Technical Interview Questions and Programs

Java technical interview questions and programs are used to evaluate how well a candidate understands real execution behavior, error handling, and core runtime concepts of Java. Unlike basic coding questions, these programs focus on how Java behaves internally and how developers handle common technical scenarios during application development. Below are technical-level Java interview programs that are frequently asked to test clarity in logic, runtime flow, and problem handling.

1. Java Program to Handle Multiple Catch Blocks

class MultiCatchDemo {

    public static void main(String[] args) {

        try {

            int[] arr = new int[3];

            System.out.println(arr[5]);

        } catch (ArithmeticException e) {

            System.out.println("Arithmetic error");

        } catch (ArrayIndexOutOfBoundsException e) {

            System.out.println("Array index error");

        }

    }

}

This program tests understanding of exception hierarchy and error handling order.

2. Java Program to Demonstrate Custom Exception

class InvalidAgeException extends Exception {

    InvalidAgeException(String msg) {

        super(msg);

    }

}

class CustomExceptionDemo {

    static void validate(int age) throws InvalidAgeException {

        if (age < 18) {

            throw new InvalidAgeException("Age not valid");

        }

    }

    public static void main(String[] args) {

        try {

            validate(16);

        } catch (InvalidAgeException e) {

            System.out.println(e.getMessage());

        }

    }

}

Interviewers use this to check how candidates create and use user-defined exceptions.

3. Java Program to Show Constructor Call Order

class Base {

    Base() {

        System.out.println("Base constructor");

    }

}

class Derived extends Base {

    Derived() {

        System.out.println("Derived constructor");

    }

    public static void main(String[] args) {

        new Derived();

    }

}

This program tests understanding of inheritance and constructor execution flow.

4. Java Program to Demonstrate Final Variable

class FinalVariable {

    public static void main(String[] args) {

        final int x = 10;

        System.out.println(x);

    }

}

Used to discuss immutability and restrictions of the final keyword.

5. Java Program to Check Object Reference Behavior

class ReferenceTest {

    int value = 5;

    public static void main(String[] args) {

        ReferenceTest obj1 = new ReferenceTest();

        ReferenceTest obj2 = obj1;

        obj2.value = 20;

        System.out.println(obj1.value);

    }

}

This program evaluates understanding of object references and memory behavior.

6. Java Program to Demonstrate Wrapper Class Conversion

class WrapperDemo {

    public static void main(String[] args) {

        String number = "100";

        int value = Integer.parseInt(number);

        System.out.println(value + 50);

    }

}

Frequently used to test type conversion and wrapper classes.

7. Java Program to Demonstrate Runtime Polymorphism Using Method Call

class Shape {

    void draw() {

        System.out.println("Drawing shape");

    }

}

class Circle extends Shape {

    void draw() {

        System.out.println("Drawing circle");

    }

    public static void main(String[] args) {

        Shape s = new Circle();

        s.draw();

    }

}

This program checks understanding of method overriding and dynamic binding.

How to Prepare for a Java Coding Interview?

Preparing for a Java coding interview requires a balanced approach that combines conceptual understanding, hands-on coding practice, and clear explanation skills. Start by strengthening your foundation in Java fundamentals such as data types, control statements, classes, objects, and core object-oriented principles. A strong grasp of how Java programs are compiled and executed will help you answer technical questions with confidence.

Regular practice of basic Java interview programs is essential. Write small programs daily to improve logic building and problem-solving speed. Focus on commonly asked areas like arrays, strings, collections, exception handling, multithreading, and Java 8 features. While practicing, make it a habit to explain your approach out loud, as interviewers often evaluate how well you communicate your thought process along with the final solution.

In addition to coding, revise commonly asked Java interview questions and understand why certain solutions are preferred over others. Pay attention to edge cases, performance considerations, and clean code practices. Reviewing past interview experiences, mock interviews, and technical discussions can further boost confidence. Consistent preparation and clarity in fundamentals are the key factors that help candidates perform well in Java coding interviews.

Final Thoughts

Mastering basic Java interview programs is an essential step for anyone preparing for technical interviews, whether you are a fresher or an experienced professional. Regular practice of Java programs, a clear understanding of core concepts, and the ability to explain your logic confidently can make a strong impression during interviews. Focusing on fundamentals, problem-solving techniques, and modern Java features helps candidates stay prepared for a wide range of interview scenarios.

For learners who want structured guidance and hands-on practice, Payilagam, the best software training institute in Chennai, offers practical and career-focused Java Training in Velachery, Chennai, with 100% Placement Assistance. The training emphasizes real interview programs, coding practice, and concept clarity, helping learners build confidence and strong programming skills. With the right preparation approach and continuous learning, cracking Java interviews becomes a much more achievable goal.

We are a team of passionate trainers and professionals at Payilagam, dedicated to helping learners build strong technical and professional skills. Our mission is to provide quality training, real-time project experience, and career guidance that empowers individuals to achieve success in the IT industry.