Interview Question

Java Interview Question And Answers Pdf -Quiz -5

Java Interview Question And Answers Pdf
Java Interview Question And Answers Pdf

Java Interview Question And Answers

Technical interview preparation becomes stronger when you regularly solve programming problems instead of focusing only on theoretical concepts. Small coding exercises help improve logical thinking, syntax knowledge, problem-solving ability, and confidence during technical assessments.

This article combines Java Interview Questions Quiz 4 and Quiz 5. The questions cover common programming concepts such as FizzBuzz, palindrome checking, factorial calculation, even-number sums, number guessing, prime numbers, string reversal, character counting, digit operations, and pattern printing.

The examples below provide practical code that can be studied and practiced while preparing for programming interviews.

Java Interview Question And Answers Pdf -Quiz -5

YT:- DecodeIT

Java Interview Questions and Answers PDF (Quiz – 4)

1. FizzBuzz

Question: Write a program that displays numbers from 1 through 100. When a number is divisible by 3, display Fizz. For numbers divisible by 5, display Buzz. If a number is divisible by both, display FizzBuzz.

The important part of this problem is checking the condition for both 3 and 5 before checking the individual conditions.

for i in range(1, 101):
    if i % 3 == 0 and i % 5 == 0:
        print("FizzBuzz")
    elif i % 3 == 0:
        print("Fizz")
    elif i % 5 == 0:
        print("Buzz")
    else:
        print(i)

2. Palindrome Checker

Question: Create a function that determines whether a word or phrase reads identically from both directions. Spaces and punctuation should not affect the result.

The function first creates a cleaned version of the input by keeping only alphanumeric characters and converting them to lowercase. It then compares that value with its reversed form.

def is_palindrome(word):
    cleaned_word = ''.join(char.lower() for char in word if char.isalnum())
    return cleaned_word == cleaned_word[::-1]

# Example usage:
word_to_check = "A man, a plan, a canal, Panama!"
print(is_palindrome(word_to_check))

3. Factorial Calculation

Question: Write a function that calculates the factorial of a non-negative integer. The factorial is obtained by multiplying all positive integers from 1 through the specified number.

The function handles 0 and 1 as base cases. For larger values, it calls itself with the previous integer and multiplies the returned result by the current number.

def factorial(n):
    if n == 0 or n == 1:
        return 1
    else:
        return n * factorial(n-1)

# Example usage:
user_input = int(input("Enter a non-negative integer: "))
print(factorial(user_input))

4. Sum of Even Numbers

Question: Create a program that calculates the total of all even numbers between 1 and a limit supplied by the user.

The function starts at 2 and moves through the range in steps of 2, ensuring that only even numbers are included in the calculation.

def sum_even_numbers(limit):
    result = sum(i for i in range(2, limit+1, 2))
    return result

# Example usage:
user_limit = int(input("Enter the limit: "))
print(sum_even_numbers(user_limit))

5. Guess the Number Game

Question: Develop a simple game in which the computer chooses a random number between 1 and 100. The player continues entering guesses until the correct number is found. The program should indicate whether each guess is too high or too low.

The random module generates the hidden number. A loop continues until the player’s guess matches that number.

import random

def guess_the_number():
    secret_number = random.randint(1, 100)
    guess = None

    while guess != secret_number:
        guess = int(input("Guess the number (between 1 and 100): "))

        if guess < secret_number:
            print("Too low! Try again.")
        elif guess > secret_number:
            print("Too high! Try again.")
        else:
            print(f"Congratulations! You guessed the correct number {secret_number}!")

# Example usage:
guess_the_number()

Java Interview Questions and Answers PDF (Quiz – 5)

1. Prime Number Checker

Question: Write a function that checks whether a positive integer is a prime number.

The program rejects values less than or equal to 1. It then checks possible divisors up to the square root of the number. If a divisor is found, the number is not prime.

public class PrimeNumberChecker {
    public static boolean isPrime(int number) {
        if (number <= 1) {
            return false;
        }

        for (int i = 2; i <= Math.sqrt(number); i++) {
            if (number % i == 0) {
                return false;
            }
        }

        return true;
    }

    public static void main(String[] args) {
        int userInput = 17;
        System.out.println(isPrime(userInput));
    }
}

2. Reverse a String

Question: Create a Java method that accepts a string and produces the characters in reverse order.

The example uses Java’s StringBuilder class. Its reverse() method reverses the character sequence before it is converted back into a String.

public class ReverseString {
    public static String reverseString(String input) {
        return new StringBuilder(input).reverse().toString();
    }

    public static void main(String[] args) {
        String inputString = "Hello, World!";
        System.out.println(reverseString(inputString));
    }
}

Check: 100+ JAVA Spring Boot Projects with Source Code

3. Count Vowels and Consonants

Question: Write a Java program that counts the vowels and consonants contained in a string.

The input is converted to lowercase before each character is examined. Only alphabetic characters are counted. Characters belonging to aeiou increase the vowel count, while the remaining alphabetic characters increase the consonant count.

public class CountVowelsConsonants {
    public static void countVowelsConsonants(String input) {
        int vowels = 0, consonants = 0;
        String lowerInput = input.toLowerCase();

        for (char ch : lowerInput.toCharArray()) {
            if (ch >= 'a' && ch <= 'z') {
                if ("aeiou".contains(String.valueOf(ch))) {
                    vowels++;
                } else {
                    consonants++;
                }
            }
        }

        System.out.println("Vowels: " + vowels);
        System.out.println("Consonants: " + consonants);
    }

    public static void main(String[] args) {
        String userInput = "Programming is Fun!";
        countVowelsConsonants(userInput);
    }
}

4. Sum of Digits

Question: Develop a function that calculates the total of all digits in a positive integer.

The program repeatedly obtains the last digit using the remainder operator. That digit is added to the total, and integer division by 10 removes the last digit. The process continues until no digits remain.

public class SumOfDigits {
    public static int sumOfDigits(int number) {
        int sum = 0;

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

        return sum;
    }

    public static void main(String[] args) {
        int userInput = 12345;
        System.out.println(sumOfDigits(userInput));
    }
}

Check: 50+ JAVA Projects with Source Code

5. Pattern Printing – Right Triangle

Question: Write a Java program that displays a right-angled triangle made with asterisks. The number of rows should be determined by the user’s input.

The outer loop controls the number of rows, while the inner loop determines how many stars are printed on each row. As the row number increases, one additional star is displayed.

Complete Advance AI Topics: Click Here
SQL Tutorial:
Click Here

import java.util.Scanner;

public class RightTrianglePattern {
    public static void printRightTriangle(int height) {
        for (int i = 1; i <= height; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the height of the right-angled triangle: ");
        int userHeight = scanner.nextInt();

        printRightTriangle(userHeight);

        scanner.close();
    }
}

Frequently Asked Questions

Are these questions useful for Java interview preparation?

Yes. The Java-based questions in Quiz-5 cover common programming concepts such as prime numbers, strings, character counting, digit processing, and nested loops.

Which question is suitable for beginners?

Problems such as FizzBuzz, factorial calculation, sum of even numbers, string reversal, and sum of digits are useful starting points for practicing basic programming logic.

What does a palindrome mean?

A palindrome is a word or phrase that produces the same sequence when read forward and backward after the specified spaces and punctuation are ignored.

What is a prime number?

A prime number is a positive integer greater than 1 that has no divisors other than 1 and itself.

What concepts are practiced through pattern printing?

The right-triangle problem provides practice with nested loops, iteration, user input, and controlling the number of characters printed on each row.

Why should I practice coding questions before an interview?

Regular practice can improve familiarity with programming syntax and logical problem-solving. It also helps candidates become more comfortable with solving coding problems within an interview or assessment environment.

Keywords: Java interview questions and answers PDF, Java interview questions for freshers, Core Java interview questions, Java coding interview questions, Java interview question PDF, Java interview preparation, Java string interview questions, Java programming questions, Java interview questions for experienced

Source Code Available

Interested in This Project?

Get the complete source code for this project at a very affordable price — perfect for your portfolio, college submission, or learning. Message us on WhatsApp and we'll get back to you instantly!

Full source code included Step-by-step setup guide Instant delivery on WhatsApp Instant reply on WhatsApp
Chat on WhatsApp

We usually reply within a few minutes

Leave a Reply

Your email address will not be published. Required fields are marked *

Chat with us