Walk In Drive : Bengalore , Hyderabad , Delhi , Chennai , Mumbai , Kolkata ->Books : Let Us C (Yashavant P.Kanetkar) , Quantitative Aptittude(RS Agrawal) , Verbal Reasoning(RS Agrawal) , SQL

Java Programming Interview Question

                      Java Program
1.
Java Program to check palindrome.

Java programming source code
******************************

import java.util.*;
 
class Palindrome
{
   public static void main(String args[])
   {
      String original, reverse = "";
      Scanner in = new Scanner(System.in);
 
      System.out.println("Enter a string to check if it is a palindrome");
      original = in.nextLine();
 
      int length = original.length();
 
      for ( int i = length - 1; i >= 0; i-- )
         reverse = reverse + original.charAt(i);
 
      if (original.equals(reverse))
         System.out.println("Entered string is a palindrome.");
      else
         System.out.println("Entered string is not a palindrome.");
 
   }
} 
Output:-
palindrome

2. Java program to check armstrong number:-

Java programming Source code
*****************************

import java.util.Scanner;
 
class ArmstrongNumber
{
   public static void main(String args[])
   {
      int n, sum = 0, temp, remainder, digits = 0;
 
      Scanner in = new Scanner(System.in);
      System.out.println("Input a number to check if it is an Armstrong number");      
      n = in.nextInt();
 
      temp = n;
 
      // Count number of digits
 
      while (temp != 0) {
         digits++;
         temp = temp/10;
      }
 
      temp = n;
 
      while (temp != 0) {
         remainder = temp%10;
         sum = sum + power(remainder, digits);
         temp = temp/10;
      }
 
      if (n == sum)
         System.out.println(n + " is an Armstrong number.");
      else
         System.out.println(n + " is not an Armstrong number.");         
   }
 
   static int power(int n, int r) {
      int c, p = 1;
 
      for (c = 1; c <= r; c++) 
         p = p*n;
 
      return p;   
   }
}
Output

Armstrong number java program output

3. Java program to swap two numbers:-

Swapping using temporary or third variable
*****************************************

import java.util.Scanner;
 
class SwapNumbers
{
   public static void main(String args[])
   {
      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\nx = "+x+"\ny = "+y);
 
      temp = x;
      x = y;
      y = temp;
 
      System.out.println("After Swapping\nx = "+x+"\ny = "+y);
   }
}

Output :-

swap numbers

No comments:

Post a Comment