Flat Preloader Icon

Interviews programs

  1. Java Program to print Hello World string on screen

In this java program, we are printing “Hello World” string using println method (System.out.println()). println method is used to print a line on screen.

				
					package com.tcc.java.programs;
 
/**
 * Java Program to Print Hello World on Screen
 */
public class HelloWorld 
{
    public static void main(String[] args)
    {
System.out.println("Hello World");
    }
}
				
			

Output:

				
					console.log( 'Code is Poetry' );
				
			
2. Java Program to print Hello World string 10 times using for loop
In this java program, we will print “Hello World” string 10 times using a for loop. For loop will iterate 10 times and in every iteration it prints “Hello World” string once in a separate line using System.out.println method.
				
					package com.tcc.java.programs;
 
/** * Java Program to Print "Hello World" 
10 times using for loop
 */
public class HelloWorldLoop {
    public static void main(String[] args) {
        int i;
        for (i = 0; i < 10; i++) {
            System.out.println("Hello World");
        }
    }
}
				
			

Output:

				
					Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
				
			

3. Bubble sort in Java.

				
					public class Tester {
   static void bubbleSort(int[] arr) {  
      int n = arr.length;  
      int temp = 0;  
      for(int i = 0; i < n; i++){  
         for(int j = 1; j < (n-i); j++){  
            if(arr[j-1] > arr[j]){  
               //swap elements  
               temp = arr[j-1];  
               arr[j-1] = arr[j];  
               arr[j] = temp;  
            }          
         }  
      }
   }  
   public static void main(String[] args) {  
      int arr[] = {21,60,32,01,41,34,5};
      System.out.println("Before Bubble Sort");  
      for(int i = 0; i < arr.length; i++){  
         System.out.print(arr[i] + " ");  
      }  
      System.out.println();  
      bubbleSort(arr);
      System.out.println("After Bubble Sort");  
      for(int i = 0; i < arr.length; i++){  
         System.out.print(arr[i] + " ");  
      }  
   }
}
				
			
Output:
				
					Before Bubble Sort
21 60 32 1 41 34 5
After Bubble Sort
1 5 21 32 34 41 60
				
			
4. Palindrome Program in Java Palindrome number in java: A palindrome number is a number that is same after reverse. For example 545, 151, 34543, 343, 171, 48984 are the palindrome numbers. It can also be a string like LOL, MADAM etc.

Palindrome number algorithm

Get the number to check for palindrome Hold the number in temporary variable Reverse the number Compare the temporary number with reversed number If both numbers are same, print “palindrome number” Else print “not palindrome number”

Let’s see the palindrome program in java. In this java program, we will get a number variable and check whether number is palindrome or not.

				
					class PalindromeExample{  
 public static void main(String args[]){  
  int r,sum=0,temp;    
  int n=454;
  //It is the number variable to be
  checked for palindrome  
  
  temp=n;    
  while(n>0){    
   r=n%10;  //getting remainder  
   sum=(sum*10)+r;    
   n=n/10;    
  }    
  if(temp==sum)    
   System.out.println("palindrome number ");    
  else    
   System.out.println("not palindrome");    
}  
}  
				
			

Output:

				
					palindrome  number
				
			

5. Java Program to Display Characters

There are various methods available for print or display the character. Let’s check one by one.

By Taking Static Input Character By Using Implicitly Typecast By Using Explicitly Typecast By Using Unicode System

Method-1: Java Program to Display Characters By Taking Static Input Character Approach:

Create a variable with character datatype and name it as ch Assign any character value to it. Finally just put that variable name in print statement. Result will be printed.
				
					public class Main 
{  
    public static void main(String[] args) 
    {  
//create the 
//character variable and assigned character-a to it.
        char ch='a';  
        //print the result.
         System.out.print("Result: "+ ch);  
    }         
}  
				
			
				
					Output:

Result: a
				
			

6. Reverse a String:

Question: Write a Java program to reverse a given string.

Answer:

				
					public class StringReversal {
    public static void main(String[] args) 
    {
        String input = "Hello, World!";
        String reversed 
        = new StringBuilder(input).reverse()
        .toString();
        System.out.println
        ("Reversed String: " + reversed);
    }
}

				
			

7. Find the Largest Element in an Array:

Question: Write a Java program to find the largest element in an array of integers.

Answer:

				
					public class LargestElement {
    public static void main(String[] args) {
        int[] numbers = {3, 7, 1, 9, 4, 6};
        int max = numbers[0];
        for (int num : numbers) {
            if (num > max) {
                max = num;
            }
        } System.out.print
        ("Largest element: " + max);
    }
}

				
			

8. Check if a Number is Prime:

Question: Write a Java program to check if a given number is prime.

Answer:

				
					public class PrimeChecker {
    public static void main(String[] args) {
        int number = 29;
        boolean isPrime = true;
        if (number <= 1) {
            isPrime = false;
        } else {
        for (int i = 2; i <= Math.sqrt(number); i++)
        {
                if (number % i == 0) 
                {
                    isPrime = false;
                    break;
                }
            }
        }
        System.out.println("Is Prime: " + isPrime);
    }
}

				
			

9. Find Common Elements in Two Arrays:

Question: Write a Java program to find common elements between two arrays of integers.

Answer:

				
					public class CommonElements {
    public static void main(String[] args) {
        int[] arr1 = {1, 3, 5, 7, 9};
        int[] arr2 = {2, 4, 6, 8, 9};
        for (int num1 : arr1) {
            for (int num2 : arr2) {
                if (num1 == num2) {
     System.out.println("Common Element: " + num1);
                }
            }
        }
    }
}

				
			

10. Write a Java Program to swap two numbers using the third variable

Answer:

				
					import java.util.Scanner;
 
public class SwapTwoNumbers {
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int x, y, temp;
        System.out.println("Enter x and y");
        Scanner in = new Scanner(System.in);
        x = in.nextInt();
        y = in.nextInt();
        System.out.println
        ("Before Swapping" + x + y);
        temp = x;
        x = y;
        y = temp;
        System.out.println
        ("After Swapping" + x + y);
         
    }
 
}
				
			
				
					OUTPUT:
Enter x and y
45
98
Before Swapping4598
After Swapping9845
				
			

11. Find the sum of two numbers ?

Answer:

				
					import java.util.Scanner;

public class SumOfTwoNumbers {
    public static void main(String[] args) {
        // Create a Scanner object to take input from the user
        Scanner scanner = new Scanner(System.in);

        // Prompt the user to enter the first number
        System.out.print("Enter the first number: ");
        // Read the first number from the user
        double num1 = scanner.nextDouble();

        // Prompt the user to enter the second number
        System.out.print("Enter the second number: ");
        // Read the second number from the user
        double num2 = scanner.nextDouble();

        // Calculate the sum of the two numbers
        double sum = num1 + num2;

        // Display the result
        System.out.println("The sum of " + num1 +
        " and " + num2 + " is: " + sum);

        // Close the Scanner to avoid resource leak
        scanner.close();
    }
}

				
			
				
					OUTPUT:
Enter the first number: 5
Enter the second number: 7
The sum of 5.0 and 7.0 is: 12.0

				
			

12. Find the smallest of three numbers ?

Answer:

				
					import java.util.Scanner;

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

        // Input three numbers from the user
        System.out.print("Enter the first number: ");
        int num1 = scanner.nextInt();

        System.out.print("Enter the second number: ");
        int num2 = scanner.nextInt();

        System.out.print("Enter the third number: ");
        int num3 = scanner.nextInt();

        // Find the smallest number
        int smallest = findSmallest(num1, num2, num3);

        // Display the result
        System.out.println("The smallest number is:
        " + smallest);
    }

    // Method to find the smallest of three numbers
    private static int findSmallest(int a, int b, int c) 
    {
        return Math.min(Math.min(a, b), c);
    }
}

				
			
				
					OUTPUT:
Enter the first number: 5
Enter the second number: 12
Enter the third number: 8
The smallest number is: 5


				
			

13. Check if the given number is a prime number ?

Answer:

				
					import java.util.Scanner;

public class PrimeNumberChecker {
    public static void main(String[] args) {
        // Taking input from the user
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number to check if
        it's prime: ");
        int number = scanner.nextInt();

        // Checking if the number is prime
        if (isPrime(number)) {
            System.out.println(number + " is a prime number.");
        } else {
            System.out.println(number +
            " is not a prime number.");
        }

        // Close the scanner to avoid resource leak
        scanner.close();
    }

    // Function to check if a number is prime
    private static boolean isPrime(int num) {
        if (num <= 1) {
            return false; // 0 and 1 are not prime numbers
        }

        for (int i = 2; i <= Math.sqrt(num); i++) {
            if (num % i == 0) {
                return false; // If num is divisible by
                any number from 2 to sqrt(num), it's not prime
            }
        }

        return true; // If no divisor is found,
        the number is prime
    }
}

				
			
				
					OUTPUT:
If you input 7, the output will be "7 is a prime number."
If you input 4, the output will be "4 is not a prime number."


				
			

14. Find the given string is a palindrome ?

Answer:

				
					import java.util.Scanner;

public class PalindromeCheck {
    public static void main(String[] args) {
        // Create a Scanner object to take user input
        Scanner scanner = new Scanner(System.in);

        // Prompt the user to enter a string
        System.out.println("Enter a string
        to check if it's a palindrome:");
        String input = scanner.nextLine();

        // Check if the entered string
        
        is a palindrome
        if (isPalindrome(input)) {
            System.out.println("The entered string
            is a palindrome.");
        } else {
            System.out.println("The entered
            string is not a palindrome.");
        }

        // Close the Scanner to prevent resource leak
        scanner.close();
    }

    // Function to check if a given string is a palindrome
    private static boolean isPalindrome(String str) {
        // Remove spaces and convert the string to lowercase
        str = str.replaceAll("\\s", "").toLowerCase();

        // Compare the original string with its reverse
        String reversed = new StringBuilder(str)
        .reverse().toString();
        return str.equals(reversed);
    }
}

				
			
				
					OUTPUT:
Enter a string to check if it's a palindrome:level
The entered string is a palindrome.


				
			

15. Check if a given year is a leap year ?

Answer:

				
					import java.util.Scanner;

public class LeapYearChecker {
    public static void main(String[] args) {
        // Create a Scanner object to take input from the user
        Scanner scanner = new Scanner(System.in);

        // Prompt the user to enter a year
        System.out.print("Enter a year: ");
        
        // Read the input year from the user
        int year = scanner.nextInt();

        // Check if the entered year is a leap year
        if (isLeapYear(year)) {
            System.out.println(year + " is a leap year.");
        } else {
            System.out.println(year + " is not a leap year.");
        }

        // Close the scanner to avoid resource leak
        scanner.close();
    }

    // Method to check if a year is a leap year or not
    private static boolean isLeapYear(int year) {
        // A leap year is either divisible by 4 but not
        by 100, or it is divisible by 400
        return (year % 4 == 0 && year % 100 != 0) ||
        (year % 400 == 0);
    }
}

				
			
				
					OUTPUT:
Enter a year: 2020
2020 is a leap year.

Enter a year: 2023
2023 is not a leap year.


				
			

16. Check Given a number n, add all the numbers from 1 to n ?

Answer:

				
					import java.util.Scanner;

public class SumOfNumbers {
    public static void main(String[] args) {
        // Create a Scanner object to read input from the user
        Scanner scanner = new Scanner(System.in);

        // Prompt the user to enter a number
        System.out.print("Enter a number (n): ");
        
        // Read the entered number
        int n = scanner.nextInt();
        
        // Calculate the sum of numbers from 1 to n
        int sum = calculateSum(n);
        
        // Display the result
        System.out.println("The sum of numbers from 1 to
        " + n + " is: " + sum);
        
        // Close the Scanner to avoid resource leak
        scanner.close();
    }

    // Method to calculate the sum of numbers from 1 to n
    private static int calculateSum(int n) {
        // Initialize the sum to 0
        int sum = 0;

        // Iterate through numbers from 1 to n and add them
        to the sum
        for (int i = 1; i <= n; i++) {
            sum += i;
        }

        // Return the calculated sum
        return sum;
    }
}

				
			
				
					OUTPUT:
Enter a number (n): 5
The sum of numbers from 1 to 5 is: 15



				
			

17. Check Find if a string is an isogram ?

Answer:

				
					import java.util.HashSet;
import java.util.Set;

public class IsogramChecker {
    public static void main(String[] args) {
        String inputString = "programming";
        boolean isIsogram = checkIsogram(inputString);
        
        if (isIsogram) {
            System.out.println(inputString +
            " is an isogram.");
        } else {
            System.out.println(inputString + " is not
            an isogram.");
        }
    }

    static boolean checkIsogram(String str) {
        Set<Character> charSet = new HashSet<>();

        for (char ch : str.toCharArray()) {
            // If the character is already present
        ,
        it's not an isogram
            if (!charSet.add(ch)) {
                return false;
            }
        }

        // If we reach here, it's an isogram
        return true;
    }
}

				
			
				
					OUTPUT:
programming is not an isogram.




				
			

18. Find the number of times each character is repeated in a string ?

Answer:

				
					import java.util.HashMap;
import java.util.Map;

public class CharacterFrequency {

    public static void main(String[] args) {
        String inputString = "programming";

        // Function call to find character frequency
        Map<Character, Integer> charFrequencyMap =
        findCharacterFrequency(inputString);

        // Display the result
        System.out.println("Character frequencies in
        the string:");
        for (Map.Entry<Character, Integer> entry :
        charFrequencyMap.entrySet()) {
            System.out.println(entry.getKey()
            + ": " + entry.getValue());
        }
    }

    // Function to find character frequency in a string
    private static Map<Character, Integer>
         findCharacterFrequency(String str) {
        Map<Character, Integer> charFrequencyMap 
        = new HashMap<>();

        // Convert the string to char array
        char[] charArray = str.toCharArray();

        // Iterate through each character and update the
        frequency map
        for (char c : charArray) {
            if (charFrequencyMap.containsKey(c)) {
                charFrequencyMap.put(c,
                charFrequencyMap.get(c) + 1);
            } else {
                charFrequencyMap.put(c, 1);
            }
        }

        return charFrequencyMap;
    }
}

				
			
				
					OUTPUT:
Character frequencies in the string:
p: 1
r: 2
o: 1
g: 2
a: 1
m: 2
i: 1
n: 1