In this post, we are going to cover most asked java interview programs.
1. A Prime Number
Write a java program to check given number is prime or not.
Java Program:
public class PrimeCheck{
public static void main(String args[]){
int i,m=0,flag=0;
int n=3;
m=n/2;
if(n==0||n==1){
System.out.println(n+" is not a prime number.");
}
else{
for(i=2;i<=m;i++){
if(n%i==0){
System.out.println(n+" is not a prime number.");
flag=1;
break;
}
}
if(flag==0) { System.out.println(n+" is a prime number."); }}}}
2. Verify a number is Even/Odd
Write java program to find number is even or odd.
Java Program:
import java.util.Scanner;
public class EvenOdd {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a number which you want to check whether that is even or odd");
int n = in .nextInt();
if (n % 2 == 0) {
System.out.println(n + " is an even number.");
} else {
System.out.println(n + " is an odd number.");
}
}
}
3. Swap a Numbers without using the third variable's:
Write java program to swap a numbers without using third variables.
Java Program:
import java.util.Scanner;
public class Swapping {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the 1st number: ");
int x = in .nextInt();
System.out.println("Enter the 2nd number: ");
int y = in .nextInt();
System.out.println("Initial value of x: " + x + " and y: " + y);
x = x + y;
y = x - y;
x = x - y;
System.out.println("After swapping value of x: " + x + " and y: " + y);
}
}
4. Verify Number is Armstrong or not
Write a Java program to verify given number is Armstrong or not.
Java Program:
import java.util.Scanner;
public class ArmstrongNum {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a number which you want to check whether that is armstrong or not: ");
int n = in .nextInt();
int a = n, r = 0, s = 0;
while (a != 0) {
r = a % 10;
a = a / 10;
s = s + r * r * r;
}
if (s == n) {
System.out.println("Number " + n + " is an armstrong number.");
} else {
System.out.println("Number " + n + " is not an armstrong number.");
}
}
}
5. Factorial of number:
Write a java program to find factorial of given number
Java Program:
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the number whose factorial you want: ");
int n = in .nextInt();
int f = 1;
for (int i = n; i > 0; i--) {
f = f * i;
}
System.out.println("Factorial of " + n + " is " + f);
}
}
إرسال تعليق